Return pre-UPDATE column values using SQL only

后端 未结 4 1985
萌比男神i
萌比男神i 2020-11-27 03:25

I posted a related question, but this is another part of my puzzle.

I would like to get the OLD value of a column from a row that was UPDATEd - WITHOUT using triggers

4条回答
  •  忘掉有多难
    2020-11-27 03:54

    The CTE variant as proposed by @MattDiPasquale should work too.
    With the comfortable means of a CTE I would be more explicit, though:

    WITH sel AS (
       SELECT tbl_id, name FROM tbl WHERE tbl_id = 3  -- assuming unique tbl_id
       )
    , upd AS (
       UPDATE tbl SET name = 'New Guy' WHERE tbl_id = 3
       RETURNING tbl_id, name
       )
    SELECT s.tbl_id AS old_id, s.name As old_name
         , u.tbl_id, u.name
    FROM   sel s, upd u;
    

    Without testing I claim this works: SELECT and UPDATE see the same snapshot of the database. The SELECT is bound to return the old values (even if you place the CTE after the CTE with the UPDATE), while the UPDATE returns the new values by definition. Voilá.

    But it will be slower than my first answer.

提交回复
热议问题