Created by Aidas Klimas
Please be careful while testing SQL queries.
Everything you see here should be executed on LOCAL environment.
Please double check if your .env file and SQL client is not connected to production.
SELECT * FROM dogs FOR UPDATE;
-- Entire table is locked
SELECT * FROM dogs WHERE id = 2 FOR UPDATE;
-- Only one row is locked
SELECT * FROM dogs WHERE id > 2 FOR UPDATE;
-- Range is locked + Gap locking
CREATE TABLE dogs (
id INT PRIMARY KEY, name varchar(255)
);
INSERT INTO dogs (id, name) VALUES
(1, 'Gile'), (2, 'Pukis');
--;
START TRANSACTION;
SELECT * FROM dogs FOR UPDATE;
UPDATE dogs set name='Pukis';
--;
--;
--;
--;
--;
--;
--;
--;
--;
--;
--;
--;
--;
--;
--;
SELECT * FROM dogs;
--> ?
START TRANSACTION;
SELECT * FROM dogs;
--> ?
CREATE TABLE dogs (
id INT PRIMARY KEY, name varchar(255)
);
INSERT INTO dogs (id, name) VALUES
(1, 'Gile'), (2, 'Pukis');
--;
START TRANSACTION;
SELECT * FROM dogs WHERE id > 2
FOR UPDATE;
--;
--;
--;
--;
--;
--;
--;
--;
--;
INSERT INTO dogs (id, name) VALUES
(3, 'Apelsinas');
--> ?
CREATE TABLE dogs (
id INT PRIMARY KEY, name varchar(255)
);
INSERT INTO dogs (id, name) VALUES
(1, 'Gile'), (2, 'Pukis');
--;
START TRANSACTION;
SELECT * FROM dogs WHERE name = 'Pukis'
FOR UPDATE;
--;
--;
--;
--;
--;
--;
--;
--;
--;
INSERT INTO dogs (id, name) VALUES
(3, 'Apelsinas');
--> ?
DROP TABLE dogs;
CREATE TABLE dogs (
id INT PRIMARY KEY, name varchar(255),
INDEX(name)
);
INSERT INTO dogs (id, name) VALUES
(1, 'Gile'), (2, 'Pukis');
--;
START TRANSACTION;
SELECT * FROM dogs WHERE name = 'Pukis'
FOR UPDATE;
--;
--;
--;
--;
--;
--;
--;
--;
--;
--;
--;
INSERT INTO dogs (id, name) VALUES
(3, 'Apelsinas');
--> ?
Always make sure that at least one field is using an index then locking.
START TRANSACTION;
SELECT * FROM dogs WHERE id = 1
FOR UPDATE;
SELECT * FROM dogs WHERE id = 2
FOR UPDATE;
--> ?
START TRANSACTION;
SELECT * FROM dogs WHERE id = 2
FOR UPDATE;
SELECT * FROM dogs WHERE id = 1
FOR UPDATE;
--> ?
Go to
https://gitlab.com/ekomlita/workshop/database-transactions/-/tree/day-2-locks
clone and follow readme
Get slides from klimas.lt/slides