Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return number of rows deleted in postgresql function

Tags:

postgresql

Here is a very simplified example of what I am trying to do. Consider this table of people:

CREATE TABLE people (pid SERIAL PRIMARY KEY, firstname TEXT, isalive BOOLEAN);

INSERT INTO people (firstname, isalive) VALUES
    ('Sam', TRUE),
    ('Leslie', FALSE),
    ('Parker', FALSE);

Now I want to delete dead people from the table. When I do this in psql, I see a message telling me how many rows were deleted.

postgres=> DELETE FROM people WHERE isalive = FALSE;
DELETE 2
postgres=>

However, if I put this delete statement into a function and call it, I don't see the same message.

CREATE OR REPLACE FUNCTION deletedead() RETURNS void AS $$
  DELETE FROM people WHERE isalive = FALSE;
$$ LANGUAGE SQL;

SELECT deletedead();

This deletes the rows as expected, but it doesn't give any message saying how many rows were deleted. How do I get a message like "DELETE 2" from this function?

I tried modifying my function to return the number of rows deleted:

-- This doesn't work
CREATE OR REPLACE FUNCTION deletedead() RETURNS int AS $$
  DELETE FROM people WHERE isalive = FALSE RETURNING COUNT(*);
$$ LANGUAGE SQL;

... but I get an error saying ERROR: aggregate functions are not allowed in RETURNING

like image 268
Michael Avatar asked Dec 17 '17 16:12

Michael


People also ask

How can I count deleted records in SQL Server?

Step 1: Use the beneath referenced command to check the number of rows present in the table from which the data got erased. Step 3: Collect all the data about the erased records from the SQL Server table to recover data. By using this command, you will acquire a Transaction ID of deleted records.

What is Rowcount in PostgreSQL?

PostgreSQL ROW_COUNT equivalent to MS SQL @@ROWCOUNT In MSSQL @@ROWCOUNT is used to get the number of records affected by the last executed sql query statement, like this in PostgreSQL ROW_COUNT is used to get the last executed sql query statements affected row count.

How do I DELETE multiple rows in PostgreSQL?

How to Delete Multiple Rows in PostgreSQL? Use the below syntax to delete multiple rows of a Postgres table: DELETE FROM tab_name WHERE col_name IN (row_1, row_2, ..., row_N); - Firstly, use the DELETE query followed by the FROM keyword, and then specify the table name from which you want to delete the rows.


1 Answers

The error message is correct. You should be able to do:

CREATE OR REPLACE FUNCTION deletedead() RETURNS bigint AS $$
  WITH d as (
        DELETE FROM people WHERE isalive = FALSE RETURNING *
       )
  SELECT COUNT(*)
  FROM d;
$$ LANGUAGE SQL;
like image 190
Gordon Linoff Avatar answered Sep 27 '22 22:09

Gordon Linoff