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.
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.
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.
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.
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).
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With