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.
Files WHERE FileID = @FileID SELECT @@ROWCOUNT AS DELETED; But DELETED is shown as 0, though the appropriate records are deleted.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With