2

I have the problem that I need to insert into a table with 2 entries, where one value is constant but fetched from another table, and the other one is the actual content that changes.

Currently I have something like

INSERT INTO table (id, content) VALUES 
  ((SELECT id FROM customers WHERE name = 'Smith'), 1),
  ((SELECT id FROM customers WHERE name = 'Smith'), 2),
  ((SELECT id FROM customers WHERE name = 'Smith'), 5),
  ...

As this is super ugly, how can I do the above in Postgres without the constant SELECT repetition?

3 Answers 3

4

Yet another solution:

insert into table (id, content)
select id, unnest(array[1, 2, 5]) from customers where name = 'Smith';
Sign up to request clarification or add additional context in comments.

1 Comment

The answer from a_horse_with_no_name is also valuable but this one is closer to the actual question. I wish I could accept two answers. ;)
4

You can cross join the result of the select with your values:

INSERT INTO table (id, content) 
select c.id, d.nr 
from (
  select id 
  from customers 
  where name = 'Smith'
) as c 
  cross join (values (1), (2), (5) ) as d (nr);

This assumes that the name is unique (but so does your original solution).

2 Comments

Just for fun: select id, unnest(array[1, 2, 5]) from customers where name = 'Smith'
You should make that into an answer Abelisto.
0

Well, I believe you can do something like this:

DECLARE
id customers.id%TYPE; 
BEGIN
select c.id into id FROM customers c WHERE name = 'Smith';
INSERT INTO table (id, content) VALUES 
(id, 1),
(id, 2),
....
END;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.