νΈλμμ μ λͺ¨λ μ°μ°μ μ λΆ μ€νλκ±°λ μ ν μ€νλμ§ μμμΌ ν©λλ€ (All or Nothing).
μμ: κ³μ’ μ΄μ²΄ νΈλμμ
BEGIN TRANSACTION;
UPDATE account SET balance = balance - 1000 WHERE user_id = 'sender';
UPDATE account SET balance = balance + 1000 WHERE user_id = 'receiver';
COMMIT;
μ΄ κ²½μ° λ μ λ°μ΄νΈ 쿼리 μ€ νλλΌλ μ€ν¨νλ©΄ μ μ²΄κ° λ‘€λ°±λμ΄μΌ ν©λλ€. μ‘κΈμμ κ³μ’μμ λμ΄ λΉ μ Έλκ°λλ° μμ·¨μΈμ κ³μ’μ μ κΈλμ§ μλ μν©μ μμ΄μλ μ λ©λλ€.
νΈλμμ μ΄ μλ£λ νμλ λ°μ΄ν°λ² μ΄μ€κ° μΌκ΄λ μνλ₯Ό μ μ§ν΄μΌ ν©λλ€. λͺ¨λ λ°μ΄ν°λ μ ν΄μ§ κ·μΉμ λ§μ‘±ν΄μΌ ν©λλ€.
μμ: μ¬κ³ κ΄λ¦¬ μμ€ν
BEGIN TRANSACTION;
UPDATE inventory SET quantity = quantity - 10 WHERE product_id = 1;
INSERT INTO orders (product_id, quantity) VALUES (1, 10);
COMMIT;
μ¬κ³ λ μ λ λ§μ΄λμ€κ° λ μ μλ€λ κ·μΉμ΄ μλ€λ©΄, μ΄ νΈλμμ μ μ¬κ³ κ° 10κ° λ―Έλ§μΌ λ μ€νλμ§ μμμΌ ν©λλ€.
λμμ μ€νλλ νΈλμμ λ€μ μλ‘ μν₯μ λ―ΈμΉμ§ μκ³ λ 립μ μΌλ‘ μνλμ΄μΌ ν©λλ€.
μμ: λμ μ£Όλ¬Έ μ²λ¦¬
-- Transaction 1
BEGIN TRANSACTION;
SELECT quantity FROM inventory WHERE product_id = 1 FOR UPDATE;
-- quantity: 5
UPDATE inventory SET quantity = quantity - 3 WHERE product_id = 1;
COMMIT;
-- Transaction 2 (λμ μ€ν)
BEGIN TRANSACTION;
SELECT quantity FROM inventory WHERE product_id = 1 FOR UPDATE;
-- Transaction 1μ΄ μλ£λ λκΉμ§ λκΈ°
-- quantity: 2
UPDATE inventory SET quantity = quantity - 2 WHERE product_id = 1;
COMMIT;
νΈλμμ μ΄ μ±κ³΅μ μΌλ‘ μλ£(컀λ°)λ νμλ ν΄λΉ κ²°κ³Όκ° μꡬμ μΌλ‘ 보μ₯λμ΄μΌ ν©λλ€.
μμ: μ£Όλ¬Έ λ°μ΄ν° 보쑴
BEGIN TRANSACTION;
INSERT INTO orders (id, user_id, total_amount) VALUES (1, 'user1', 50000);
INSERT INTO order_items (order_id, product_id, quantity) VALUES (1, 100, 2);
COMMIT;
μμ€ν μ΄ κ°μκΈ° μ€λ¨λλλΌλ, 컀λ°λ μ£Όλ¬Έ λ°μ΄ν°λ 보쑴λμ΄μΌ ν©λλ€.
격리μ±μ λ€μκ³Ό κ°μ λ λ²¨λ‘ κ΅¬λΆλ©λλ€:
- READ UNCOMMITTED
- READ COMMITTED
- REPEATABLE READ
- SERIALIZABLE