MySQL has two special clauses that are very useful in certain scenarios.
FOR UPDATE:
In certain scenarios, we need atomicity i.e we try to lock certain rows, do something and then update the set of rows. FOR UPDATE clause is specifically for this reason.
Example:
START TRANSACTION;
SELECT * FROM table WHERE col1 BETWEEN 1 AND 5
FOR UPDATE;
....
COMMIT;
At this point whatever rows match the criteria, would be locked, the rows can be updated as per needs and COMMIT or ROLLBACK.
However, if there are other queries running in parallel, the performance might be slightly affected. Specifically, in large-scale multi-threaded applications. For this we would use SKIP LOCKED, i.e the other query would run, skipping the rows that were locked.
Now combing these two concepts, we can write a sql statement that locks some rows based on WHERE criteria and other sql statements can still continue happen.
START TRANSACTION;
SELECT * FROM table WHERE col1 BETWEEN 1 AND 5
FOR UPDATE SKIP LOCKED;
....
COMMIT;
–
Mr. Kanti Kalyan Arumilli
B.Tech, M.B.A
Founder & CEO, Lead Full-Stack .Net developer
ALight Technology And Services Limited
Phone / SMS / WhatsApp on the following 3 numbers:
+91-789-362-6688, +1-480-347-6849, +44-07718-273-964
+44-33-3303-1284 (Preferred number if calling from U.K, No WhatsApp)
kantikalyan@gmail.com, kantikalyan@outlook.com, admin@alightservices.com, kantikalyan.arumilli@alightservices.com, KArumilli2020@student.hult.edu, KantiKArumilli@outlook.com and 3 more rarely used email addresses – hardly once or twice a year.