PostgreSQL return select results AND add them to temporary table? PostgreSQL return select results AND add them to temporary table? postgresql postgresql

PostgreSQL return select results AND add them to temporary table?


I think you can do this with a Postgres feature that allows data modification steps in CTEs. The more typical reason to use this feature is, say, to delete records for a table and then insert them into a log table. However, it can be adapted to this purpose. Here is one possible method (I don't have Postgres on hand to test this):

with q as (      <your query here>     ),     t as (      insert into temptable(pk)          select pk          from q     )select *from q;

Usually, you use the returning clause with the data modification queries in order to capture the data being modified.