I have a situation where I need to insert data into two tables, where the inserted data is derived from the same long sub query. I know that CTEs can be helpful in similar situations since you can define a subquery once, and reuse it in multiple places in the subsequent statement. The problem is I don’t have a single statement I want to use the subquery for, I have two, and my understanding is the CTEs only be used in a single statement.
So my question is how can I avoid repeating the
SELECT col1
FROM table3
WHERE col2 > 5
AND col2 < 10
ORDER BY col2 DESC
part of the below?
INSERT INTO table1 (col1, othercol)
SELECT col1, 'foo'
FROM
(SELECT col1 FROM table3 WHERE col2 > 5 AND col2 < 10 ORDER BY col2 DESC);
INSERT INTO table2 (col1, othercol)
SELECT col1, 'bar'
FROM
(SELECT col1 FROM table3 WHERE col2 > 5 AND col2 < 10 ORDER BY col2 DESC);
2
Answers
Write it as a temp table first.
Use a better name than tmp π
See example.
CTEs can only be used in a single statement.
There RETURNING clause is helpful.
First INSERT operation in CTE returns all INSERTED rows.
Then insert them into second table.
We can see on query plan, internal query runs 1 time.