For example, you need to change your password.
The query UPDATE users SET password = $new_password WHERE id = $user_id AND session_key = $session_key
will find the pair
id and session_key and will continue to search even though we know for sure that there is only one such pair of id and session. How can I make the query stop searching after the first find?
Can Postgres understand that id is a unique key and there can no longer be such matches and it needs to stop searching or will it still continue searching?
I know that in MySQL you can add a LIMIT at the end of the query and solve the main problem, but I want to solve in Postgres. The IN (SELECT …) query behaves just like a regular query.
3
How to limit an UPDATE query to one execution?
Run it once and it’ll execute once.
The query (…) will find the pair id and session_key and will continue to search even though we know for sure that there is only one such pair
Unless you defined a unique
index/constraint on (id)
or (id,session_key)
, Postgres won’t know that. If you did, it does finish searching at that point. If you think it’s doing something more, you might have that impression because something else keeps locking the table/index/rows, or the latency of your connection or the db storage makes it look like that.
You can check with explain(analyze, verbose, buffers, settings)
suggested by @Frank Heikens to see what it actually, really does:
explain(analyze, verbose, buffers, settings)
UPDATE users SET password = $new_password WHERE id = $user_id AND session_key = $session_key;
Can Postgres understand that id is a unique key and there can no longer be such matches and it needs to stop searching or will it still continue searching?
Explain that to it in Data Definition Language with a constraint:
alter table users add constraint your_constraint_name unique(id);
The IN (SELECT …) query behaves just like a regular query.
It is a regular query. If you can’t add the constraint, the construct you described can be used to get the behaviour you want, where Postgres will just grab the first row matching your criteria and update that. The built-in system column ctid
is always guaranteed to uniquely identify each row.
UPDATE users
SET password = $new_password
WHERE ctid=(SELECT ctid
FROM users
WHERE id = $user_id
AND session_key = $session_key
LIMIT 1);