PostgreSQL: with clause containing a delete statement
Today, I stumbled upon a cool SQL feature (via Markus Winand): the with clause containing a delete statement that returns the deleted records to a subsequent SQL statement.
The subsequent SQL can then process the «deleted» records further.
Apparently, this feature is only available on PostgreSQL (but I'd like to be corrected on that if I am wrong).
I try to demonstrate this feature in the following simple example:
First, we need to create a table to store some data. It contains «important» and «less important» data.
create table abc (
id integer not null,
val_important varchar(10) not null,
val_unimportant varchar(10) not null
);
Then, we need a history table to receive the important data when it is deleted in abc (for whatever reason that I am not able to make up a good reason, currently).
create table abc_hist (
id integer not null,
val_important varchar(10) not null,
delete_date timestamp null
);
Delete one record. Use the with clause and pass the deleted records to an outer insert statement, so that the deleted record can be inserted into the history table with the timestamp (localtimestamp) of the deletion:
with del as (
delete from abc
where
id = 1
returning *
)
insert into abc_hist
select
del.id,
del.val_important,
localtimestamp
from
del;