Hacker News new | ask | show | jobs
by nicoburns 1346 days ago
You can already do SELECT followed by UPDATE/INSERT in a single query in postgres using CTEs...
1 comments

You can do them individually yes, but you can’t do INSERT and UPDATE from the same SELECT CTE.

Before, you’d have to either load the data in the client side or duplicate the CTE across two statements in a transaction.

You can, like this:

    WITH results as (
      SELECT ...
    ),

    inserted_rows AS (
      INSERT ...
      SELECT * FROM results
      ...
    ),

    deleted_rows AS (
      DELETE ...
      USING results
      ... 
    )

    UPDATE ...
    FROM results
Woah! I stand corrected, thanks.

It seems you’re knowledgeable on this, do you know if MERGE useful beyond expressivity?