How to get the number of deleted rows in PostgreSQL?

Erkan Haspulat picture Erkan Haspulat · Feb 12, 2010 · Viewed 23.9k times · Source

I am looking for a way to return the number of rows affected by a DELETE clause in PostgreSQL. The documentation states that;

On successful completion, a DELETE command returns a command tag of the form

DELETE count

The count is the number of rows deleted. If count is 0, no rows matched the condition (this is not considered an error).

If the DELETE command contains a RETURNING clause, the result will be similar to that of a SELECT statement containing the columns and values defined in the RETURNING list, computed over the row(s) deleted by the command.

But I am having trouble finding a good example of it. Can anyone help me with this, how can I find out how many rows were deleted?


EDIT: I accepted Milen's solution, but I wanted to present an alternative that I have found later. It can be found in here, explained under 38.5.5. Obtaining the Result Status title.

Answer

Jakub Fedyczak picture Jakub Fedyczak · Mar 21, 2014

You can use RETURNING clause:

DELETE FROM table WHERE condition IS TRUE RETURNING *;

After that you just have to check number of rows returned. You can streamline it with CTE:

WITH deleted AS (DELETE FROM table WHERE condition IS TRUE RETURNING *) SELECT count(*) FROM deleted;

This should return just the number of deleted rows.