How to insert values into a table from a postgres insert select query?
I have a table items (item_id serial, name varchar(10), item_group int) and a table items_ver (id serial, item_id int, name varchar(10), item_group int).
Now I want to insert a row into items_ver from items. Is there any short SQL-syntax for doing this?
I have tried with:
INSERT INTO items_ver VALUES (SELECT * FROM items WHERE item_id = 2);
but I get a syntax error:
ERROR: syntax error at or near "select"
LINE 1: INSERT INTO items_ver VALUES (SELECT * FROM items WHERE item...
I now tried:
INSERT INTO items_ver SELECT * FROM items WHERE item_id = 2;
It worked better but I got an error:
ERROR: column "item_group" is of type integer but expression is of type
character varying
LINE 1: INSERT INTO items_ver SELECT * FROM items WHERE item_id = 2;
This may be because the columns are defined in a different order in the tables. Does the column order matter? I hoped that PostgreSQL would match the column names.
To insert values into a table from a postgres insert select query -
INSERT INTO test_import_two (name, name1, name2)
<strong>(SELECT name, name1, name2 FROM test_import_one WHERE id = 2)</strong>
For same table
INSERT INTO test_import_three (id1, name1, name2)
(SELECT 216 ,name1, name2 FROM test_import_three WHERE id = 4)