Fantastic! Time for another chunk of knowledge :)
So far, we've deleted records from a table without seeing any of the deleted values. Sometimes, though, we would like to know details about what we're deleting. For this, PostgreSQL gives us the RETURNING
clause, which displays the column values of deleted rows. It looks like this:
DELETE FROM student
WHERE last_name IS NULL
RETURNING *;
This returns a table with all the removed records – in this case, the records for any students without a last name.
The new element in this DELETE
statement is the RETURNING
clause, which you put at the end of the query. After the RETURNING
clause, we put an asterisk (*
) to denote that we wanted data from all columns. We could also list certain column names, like this:
DELETE FROM student
WHERE last_name IS NULL
RETURNING id, first_name;
This allows you to see the ID and first name values for all deleted records.