6

I can use a CTE in a single query like this

with mycte as (...)
  insert into table1 (col1) select col1 from mycte where col1 in
    (select col1 from mycte)

But what if I want to use mycte in multiple queries? How can I make something like this work?

with mycte as (...)
  insert into table1 (col1) select col1 from mycte where col1 in
    (select col1 from mycte),
  insert into table2 (col1) select col1 from mycte where col1 in
    (select col1 from mycte)
3
  • If you want the data to persist across a statement, I think you will need to use a temporary table Commented Oct 22, 2018 at 8:50
  • 2
    A cte is one-time and local to a query. Create a view instead. Commented Oct 22, 2018 at 8:50
  • Could you give an example of this case with a temporary table or a view? Commented Oct 22, 2018 at 9:16

2 Answers 2

5

For multiple inserts, you can put them into the same query:

with mycte as (...),
     i1 as (
      insert into table1 (col1)
          select col1
          from mycte
          where col1 in (select col1 from mycte)
          returning *
     )
insert into table2 (col1)
    select col1
    from mycte
    where col1 in (select col1 from mycte);
Sign up to request clarification or add additional context in comments.

Comments

0

A CTE is an ad-hoc view. If you want a permanent view that you can use in multiple queries, then use CREATE VIEW instead.

2 Comments

Is it possible to make a temporary view that doesn't persist outside of a postgres function? So I can use it in multiple queries in that function/transaction but not outside.
I think in PostgreSQL you can select into an array and then select from this array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.