Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writeable common table expression and multiple insert statements

How do I write the following in a valid Postgres SQL query:

with foo as (select * from ...)
insert into bar select * from foo
insert into baz select * from foo
like image 872
Michiel Borkent Avatar asked Oct 18 '16 11:10

Michiel Borkent


People also ask

Can we use CTE with insert statement?

We cannot reuse the CTE. Its scope is limited to the outer SELECT, INSERT, UPDATE, or MERGE statements. You can use multiple CTES; however, they should use UNION ALL, UNION, INTERSECT, or EXCERPT operators.

Can you run multiple insert statements in SQL?

If you want to insert more rows than that, you should consider using multiple INSERT statements, BULK INSERT or a derived table. Note that this INSERT multiple rows syntax is only supported in SQL Server 2008 or later. To insert multiple rows returned from a SELECT statement, you use the INSERT INTO SELECT statement.

Can insert statement be used to insert multiple rows in a single statement?

Description. The Oracle INSERT ALL statement is used to add multiple rows with a single INSERT statement. The rows can be inserted into one table or multiple tables using only one SQL command.


1 Answers

You can use CTEs, if you want this all in one statement:

with foo as (
      select * from ...
     ),
     b as (
      insert into bar
          select * from foo
          returning *
     )
insert into baz
    select * from foo;

Notes:

  • You should include column lists with insert.
  • You should specify the column names explicitly for the select *. This is important because the columns may not match in the two tables.
  • I always use returning with update/insert/delete in CTEs. This is the normal use case -- so you can get serial ids back from an insert, for instance.
like image 150
Gordon Linoff Avatar answered Oct 11 '22 15:10

Gordon Linoff