Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres - Return error on update if record not found

Tags:

postgresql

I am wondering if there is a way of getting an error back on update if the row does not exist in the database when I issue an update.

update users set email='[email protected]' where id=200

If users table does not have user with id=200, then postgres simply says "UPDATE 0". However, I am wondering if I can get an error back. That way, I don't have to issue 2 requests to the database, once to check existence, once to update. There could also be a race condition between checking the existence and issuing an update if we do it separately.

Why do I need an error? Simple - so the clients know they have used an invalid user id and they take corrective action.

like image 459
sat Avatar asked May 23 '14 05:05

sat


People also ask

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.

What is returning * Postgres?

A common shorthand is RETURNING * , which selects all columns of the target table in order. In an INSERT , the data available to RETURNING is the row as it was inserted. This is not so useful in trivial inserts, since it would just repeat the data provided by the client.

What is Setof in PostgreSQL?

Alternatively, an SQL function can be declared to return a set (that is, multiple rows) by specifying the function's return type as SETOF sometype , or equivalently by declaring it as RETURNS TABLE( columns ) . In this case all rows of the last query's result are returned. Further details appear below.


2 Answers

You can use something like

update users set email='[email protected]' where id=200 returning id; 

This query will return the id of the updated row. If it returns 0 rows - then throw an error in your application.

Also you may want to check if your db driver / framework returns the count of affected rows (like getUpdateCount() in JDBC).

like image 77
Ihor Romanchenko Avatar answered Oct 08 '22 19:10

Ihor Romanchenko


You can use an anonymous code block.

do $$ begin     update users set email='[email protected]' where id=200;     if not found then raise exception 'User not found';     end if; end $$; 

Or regular function:

create or replace function update_user(new_email text, user_id integer) returns void language plpgsql  as $$ begin     update users set email = new_email where id = user_id;     if not found then raise exception 'User id % not found', user_id;     end if; end $$;      select update_user('[email protected]', 200); 
like image 37
klin Avatar answered Oct 08 '22 19:10

klin