Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres - Inserting data from another table for one column only

Tags:

sql

postgresql

I am attempting the following query in Postgres 9.6.3

INSERT INTO join_table ("table_1_id", "table_2_id") VALUES
      (7, SELECT "id" from "table_2" where label='Foo Bar');

This throws ERROR: syntax error at or near "SELECT" at character 94

I have seen examples for nested selects inside of an insert statement work where only the things being selected are inserted. Is the above query even possible?

like image 436
Adzz Avatar asked Dec 02 '22 11:12

Adzz


2 Answers

Try putting parens around the sub-query:

INSERT INTO join_table ("table_1_id", "table_2_id") VALUES
      (7, (SELECT "id" from "table_2" where label='Foo Bar'));
like image 157
melpomene Avatar answered Dec 04 '22 06:12

melpomene


Use insert . . . select. values is unnecessary:

INSERT INTO join_table (table_1_id, table_2_id)
    SELECT y, "id" 
    FROM "table_2" 
    WHERE label = 'Foo Bar';

This also allows you to insert multiple rows from the other table.

like image 43
Gordon Linoff Avatar answered Dec 04 '22 06:12

Gordon Linoff