Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update Returning Order by in postgresql

Tags:

postgresql

I have a query updating rows in a table. I want the query to update the rows and return the rows affected.

Currently I have

UPDATE employees SET name = 'John' RETURNING employees.*;

This works fine. But what if I want to return the rows affected in a specified order. Something like

UPDATE employees SET name = 'John' RETURNING employees.* ORDER BY name ASC;

This does not work. Anyone got a good suggestion?

like image 263
Kevin Joymungol Avatar asked Sep 03 '14 17:09

Kevin Joymungol


People also ask

What does update query return in Postgres?

It is an expression, which is used to return a value of type Boolean. And this expression returns true only for rows.

What does an update query return?

Update queries now consistently return the number of all rows matched by the query. Executed update queries always return the number of rows matched by the query, including rows that didn't have to be updated because their values wouldn't have changed.

How Update works in Postgres?

PostgreSQL implements multiversioning by keeping the old version of the table row in the table – an UPDATE adds a new row version (“tuple”) of the row and marks the old version as invalid. In many respects, an UPDATE in PostgreSQL is not much different from a DELETE followed by an INSERT .


1 Answers

This can be done using a data modifying CTE (common table expression):

with updated as (
    UPDATE employees 
        SET name = 'John' 
    RETURNING *
)
select *
from updated
ORDER BY empname ASC;
like image 113
a_horse_with_no_name Avatar answered Nov 16 '22 00:11

a_horse_with_no_name