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
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.
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.
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.
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:
insert
.select *
. This is important because the columns may not match in the two tables.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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With