Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql function return affected row count

Tags:

postgresql

I created a function. I defined returning value void. But I want to show affected row count. How can I do?

CREATE OR REPLACE FUNCTION update() RETURNS void  AS 
$BODY$
BEGIN
   update test_a set name='cde' where name='abc';
   update test_b set name='mno' where name='klm';
END;
$BODY$   
LANGUAGE plpgsql VOLATILE   
COST 100; 
ALTER FUNCTION update()   
OWNER TO postgres;
like image 785
David Barbata Avatar asked Aug 10 '16 14:08

David Barbata


People also ask

Which function will return the number of rows affected by a query?

To overcome this issue, SQL Server introduces the ROWCOUNT_BIG system function, which returns the number of rows affected by a specific query in the BIGINT data type.

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.

What is $$ in PostgreSQL?

In PostgreSQL, the dollar-quoted string constants ($$) is used in user-defined functions and stored procedures. In PostgreSQL, you use single quotes for a string constant like this: select 'String constant'; When a string constant contains a single quote ('), you need to escape it by doubling up the single quote.

How do you find the row count for all your tables in Postgres?

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.


1 Answers

you should look into GET DIAGNOSTICS, since this is a PLpgSQL function. You might also find the Postgres SQL extension RETURNING * for UPDATE/INSERTS useful.

CREATE OR REPLACE FUNCTION update() RETURNS void  AS 
$BODY$
DECLARE
  a_count integer;
  b_count integer;
BEGIN
   update test_a set name='cde' where name='abc';
   GET DIAGNOSTICS a_count = ROW_COUNT;
   update test_b set name='mno' where name='klm';
   GET DIAGNOSTICS b_count = ROW_COUNT;

   RAISE NOTICE 'The rows affected by A=% and B=%', a_count, b_count ;
END;
$BODY$   
LANGUAGE plpgsql VOLATILE   
COST 100; 
ALTER FUNCTION update()   
OWNER TO postgres;

Depending on what you might want to achieve, the special boolean variable "FOUND" could serve; UPDATE, INSERT, and DELETE statements set FOUND true if at least one row is affected, false if no row is affected.

like image 106
emacsx Avatar answered Sep 19 '22 07:09

emacsx