Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get count of records affected by INSERT or UPDATE in PostgreSQL

My database driver for PostgreSQL 8/9 does not return a count of records affected when executing INSERT or UPDATE.

PostgreSQL offers the non-standard syntax "RETURNING" which seems like a good workaround. But what might be the syntax? The example returns the ID of a record, but I need a count.

INSERT INTO distributors (did, dname) VALUES (DEFAULT, 'XYZ Widgets') RETURNING did;

like image 292
Un Homme Avatar asked Oct 27 '10 23:10

Un Homme


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.

How does count work in PostgreSQL?

The PostgreSQL COUNT function counts a number of rows or non-NULL values against a specific column from a table. When an asterisk(*) is used with count function the total number of rows returns. The asterisk(*) indicates all the rows.

Do Postgres views update automatically?

Updatable Views. Simple views are automatically updatable: the system will allow INSERT , UPDATE and DELETE statements to be used on the view in the same way as on a regular table.

Does update insert in Postgres?

The idea is that when you insert a new row into the table, PostgreSQL will update the row if it already exists, otherwise, it will insert the new row. That is why we call the action is upsert (the combination of update or insert).


2 Answers

I know this question is oooolllllld and my solution is arguably overly complex, but that's my favorite kind of solution!

Anyway, I had to do the same thing and got it working like this:

-- Get count from INSERT WITH rows AS (     INSERT INTO distributors         (did, dname)     VALUES         (DEFAULT, 'XYZ Widgets'),         (DEFAULT, 'ABC Widgets')     RETURNING 1 ) SELECT count(*) FROM rows;  -- Get count from UPDATE WITH rows AS (     UPDATE distributors     SET dname = 'JKL Widgets'     WHERE did <= 10     RETURNING 1 ) SELECT count(*) FROM rows; 

One of these days I really have to get around to writing a love sonnet to PostgreSQL's WITH clause ...

like image 141
mercurial Avatar answered Oct 12 '22 23:10

mercurial


I agree w/ Milen, your driver should do this for you. What driver are you using and for what language? But if you are using plpgsql, you can use GET DIAGNOSTICS my_var = ROW_COUNT;

http://www.postgresql.org/docs/current/static/plpgsql-statements.html

like image 40
Scott Bailey Avatar answered Oct 13 '22 00:10

Scott Bailey