Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the number of deleted rows in PostgreSQL?

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 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.

like image 304
Erkan Haspulat Avatar asked Feb 12 '10 11:02

Erkan Haspulat


People also ask

How do I count a deleted record in SQL?

Files WHERE FileID = @FileID SELECT @@ROWCOUNT AS DELETED; But DELETED is shown as 0, though the appropriate records are deleted.

How do I count rows in PostgreSQL?

The basic SQL standard query to count the rows in a table is: SELECT count(*) FROM table_name; This can be rather slow because PostgreSQL has to check visibility for all rows, due to the MVCC model.

Will return the number of rows in a PostgreSQL?

The COUNT(*) function returns the number of rows returned by a SELECT statement, including NULL and duplicates. When you apply the COUNT(*) function to the entire table, PostgreSQL has to scan the whole table sequentially.

How can I count deleted records in mysql?

You can use ROW_COUNT() function to check the number of deleted rows. The conditions in the WHERE clause (optional) identify which rows to delete. Without WHERE clause, all rows are deleted. If you specify the ORDER BY clause, the rows are deleted in specified order.


2 Answers

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.

like image 123
Jakub Fedyczak Avatar answered Oct 11 '22 15:10

Jakub Fedyczak


This should be simple in Java.

Statement stmt = connection.createStatement(); int rowsAffected = stmt.executeUpdate("delete from your_table"); System.out.println("deleted: " + rowsAffected); 

See java.sql.Statement.

like image 23
cope360 Avatar answered Oct 11 '22 15:10

cope360