Let's discuss MariaDB/MySQL isolation levels. Understanding them means to know how your DBMS can protect you from anomalies, and how to apply potentially important optimisations.
2. € whoami
● Federico Razzoli
● Freelance consultant
● Writing SQL since MySQL 2.23
hello@federico-razzoli.com
● I love open source, sharing,
Collaboration, win-win, etc
● I love MariaDB, MySQL, Postgres, etc
○ Even Db2, somehow
3. Transactions
START TRANSACTION;
-- check if the product is available
SELECT qty
FROM product
WHERE id = 333
LOCK IN SHARE MODE;
-- create the order
INSERT INTO order
(user_id, status, product_id)
VALUES
(42, 'NEW', 333);
-- decrease quantity in stack
UPDATE product
SET qty = qty - 1
WHERE id = 333
COMMIT;
4. Transactions
START TRANSACTION;
SELECT qty
FROM product
WHERE id = 333
FOR UPDATE;
INSERT INTO order
(user_id, status, product_id)
VALUES
(42, 'NEW', 333);
UPDATE product
SET qty = qty - 1
WHERE id = 333
COMMIT;
START TRANSACTION;
SELECT qty
FROM product
WHERE id = 333
FOR UPDATE;
INSERT INTO order
(user_id, status, product_id)
VALUES
(42, 'NEW', 333);
UPDATE product
SET qty = qty - 1
WHERE id = 333
COMMIT;
6. READ UNCOMMITTED
● We see data that is not COMMITted
○ And maybe will never be
For large queries/transactions, this is a major optimisation
When should I use it?
● Statistics on many rows
● Removing old rows that no one is supposed to be reading
● Read / modify session data
● Inserting data
7. READ COMMITTED
● Only see COMMITted data
● But every query acquires a new view on data
● It’s like running separate transactions, but the queries succeed or fail
altogether
Why should I use it?
● “Gap locks”
○ Big INSERT … SELECT
● Single statement transactions (autocommit=1)
● Can be a great optimisation with big INSERT ... SELECTs
8. REPEATABLE READ
● Only see COMMITted data
● A view on data is acquired at the beginning of the transaction
● Cannot see changes made by others in the middle of the transaction
Why should I use it?
● Purchase a product
● Reserve a ticket
● etc