Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres INSERT INTO with SELECT

Tags:

postgresql

I'm trying to write some SQL to insert records into a PG table.

This is the logic:

  • For every record in the costprojects table that has coststatus_id=1
  • insert a new record into costestimates table
    • costcat_id=30, amount=0, costproject_id=costproject.id(from the costprojects record) , maintenance=‘FALSE’, position=22

This is the SQL code I tried:

INSERT INTO costestimates (costcat_id, amount, costproject_id, maintenance, position) VALUES (30, 0, costproject.id, false, 22)
(SELECT id FROM costprojects WHERE coststatus_id=1)

I get ERROR: syntax error at or near "("

like image 234
Reddirt Avatar asked Mar 16 '16 19:03

Reddirt


People also ask

Which is faster insert into or select into?

INTO' creates the destination table, it exclusively owns that table and is quicker compared to the 'INSERT … SELECT'. Because the 'INSERT … SELECT' inserts data into an existing table, it is slower and requires more resources due to the higher number of logical reads and greater transaction log usage.

What is the difference between insert into and select into?

INSERT INTO SELECT vs SELECT INTO: Both the statements could be used to copy data from one table to another. But INSERT INTO SELECT could be used only if the target table exists whereas SELECT INTO statement could be used even if the target table doesn't exist as it creates the target table if it doesn't exist.


2 Answers

It should be something like this:

INSERT INTO costestimates (costcat_id, amount, costproject_id, maintenance, position)
SELECT 30, 0, id, false, 22 FROM costprojects WHERE coststatus_id=1;

See postgres INSERT syntax

like image 139
Ildar Musin Avatar answered Sep 27 '22 18:09

Ildar Musin


Your syntax is a bit off; what you want is to actually compose the VALUES list using your SELECT statement.

Try something like this:

INSERT INTO
  costestimates (costcat_id, amount, costproject_id, maintenance, position)
  (SELECT 30, 0, id, false, 22 FROM costprojects WHERE coststatus_id=1)
like image 35
Hamms Avatar answered Sep 27 '22 16:09

Hamms