This topic provides specific examples on how to use the SELECT ... LOCK IN SHARE MODE statement to lock query results.
You can use the SELECT ... LOCK IN SHARE MODE statement to obtain a shared lock when you query data. This prevents other transactions from writing data but allows other transactions to read data. This statement sets a shared lock on the read data rows. Other sessions can read these rows but cannot modify them until the current transaction is committed.
Notice
OceanBase Database simulates the feature of the LOCK IN SHARE MODE syntax using write locks. This can meet the compatibility requirements of some software while ensuring the correctness of the syntax. Write locks can cause blocking between read operations that use the LOCK IN SHARE MODE syntax. Therefore, we recommend that you do not use this syntax, especially in performance-sensitive scenarios.
Examples
In Session 1, execute the following SQL statement to start a transaction:
START TRANSACTION;In Session 1, use the
LOCK IN SHARE MODEsyntax to query records whereidis1in thetest_tbl1table and obtain a shared lock.SELECT * FROM test_tbl1 WHERE id = 1 LOCK IN SHARE MODE;The result is as follows:
+------+------+ | id | name | +------+------+ | 1 | A1 | +------+------+ 1 row in setIn Session 2, execute the following SQL statement to start a transaction:
START TRANSACTION;In Session 2, execute the following SQL statement to query the row where
idis1in thetest_tbl1table:SELECT * FROM test_tbl1 WHERE id = 1;The result is as follows:
+------+------+ | id | name | +------+------+ | 1 | A1 | +------+------+ 1 row in setIn Session 2, execute the following SQL statement to change the value of
nametoA1A1A1for the row in thetest_tbl1table whereidis1. The SQL statement waits until the transaction of Session 1 is rolled back or committed.UPDATE test_tbl1 SET name = 'A1A1A1' WHERE id = 1;The result is as follows:
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transactionIn Session 1, execute the following SQL statement to commit the transaction:
COMMIT;In Session 2, execute the
UPDATEstatement in Step 4 again.UPDATE test_tbl1 SET name = 'A1A1A1' WHERE id = 1;The result is as follows:
Query OK, 1 row affected Rows matched: 1 Changed: 1 Warnings: 0