Guidance on using the WITH clause in SQL

后端 未结 2 1320
萌比男神i
萌比男神i 2021-02-02 16:28

I understand how to use the WITH clause for recursive queries (!!), but I\'m having problems understanding its general use / power.

For example the followin

2条回答
  •  情深已故
    2021-02-02 16:47

    If there can be concurrent write access to involved tables, there are race conditions in the above following queries. Consider:

    • Postgres UPDATE … LIMIT 1

    Your example can use a CTE (common table expression), but it will give you nothing a subquery couldn't do:

    WITH x AS (
       SELECT  psp_id
       FROM    global.prospect
       WHERE   status IN ('new', 'reset')
       ORDER   BY request_ts
       LIMIT   1
       )
    UPDATE global.prospect psp
    SET    status = status || '*'
    FROM   x
    WHERE  psp.psp_id = x.psp_id
    RETURNING psp.*;
    

    BTW, the returned row will be the updated version.


    If you wanted to insert the returned row into another table, that's where a WITH clause becomes essential:

    WITH x AS (
       SELECT  psp_id
       FROM    global.prospect
       WHERE   status IN ('new', 'reset')
       ORDER   BY request_ts
       LIMIT   1
       ), y AS (
       UPDATE global.prospect psp
       SET    status = status || '*'
       FROM   x
       WHERE  psp.psp_id = x.psp_id
       RETURNING psp.*
       )
    INSERT INTO z
    SELECT *
    FROM   y
    

    Data modifying queries using CTE are possible with PostgreSQL 9.1 or later.
    Read more in the excellent manual.

提交回复
热议问题