Indexes and transactions
Two topics separate hobby SQL from production SQL: making queries fast (indexes) and keeping data correct when things go wrong or many users act at once (transactions).
Indexes: the book index analogy
Without an index, finding WHERE email = 'asha@example.com' means reading every row. This is a full table scan, which is fine for 10 rows and painful for 10 million. An index is a sorted lookup structure (usually a B-tree) that jumps straight to matching rows, like the index at the back of a book.
SCAN orders means a full scan. Now add an index and check again:
Now it says SEARCH orders USING INDEX. (In PostgreSQL and MySQL, use EXPLAIN or EXPLAIN ANALYZE.)
What to index
- Columns used often in
WHERE,JOIN … ONandORDER BY - Foreign key columns (PostgreSQL doesn't index them automatically!)
- Primary keys and
UNIQUEcolumns are indexed automatically
Composite indexes
An index on (customer_id, order_date) helps queries filtering on customer_id, or on customer_id and order_date, but not on order_date alone. This is the leftmost prefix rule.
The cost of indexes
Indexes aren't free. Every INSERT/UPDATE/DELETE must also update every index, and indexes use disk space. Index for the queries you actually run, and measure.
Queries that can't use an index
WHERE LOWER(email) = 'x' -- function on the column (use an expression index instead)
WHERE name LIKE '%son' -- leading wildcard
WHERE price + 0 > 100 -- arithmetic on the columnTransactions and ACID
A transaction groups statements into one all-or-nothing unit. The classic example is a bank transfer: debiting one account and crediting another must both happen, or neither.
If anything fails between BEGIN and COMMIT, the application issues ROLLBACK and the database returns to exactly how it was.
| ACID | Meaning |
|---|---|
| Atomicity | All statements succeed, or none take effect |
| Consistency | Constraints are never violated |
| Isolation | Concurrent transactions don't see each other's half-done work |
| Durability | Once committed, data survives crashes |
Isolation levels and concurrency bugs
When two users act at the same time, you can get:
- Lost update: both read balance 100, both write 100 − 30. One withdrawal vanishes.
- Dirty read: reading another transaction's uncommitted data.
- Non-repeatable read / phantom: the same query gives different results within one transaction.
Databases offer isolation levels (READ COMMITTED, REPEATABLE READ, SERIALIZABLE) that trade safety for speed. A practical fix for lost updates is to do the maths in the database:
-- ✗ read in app, compute, write back (race condition)
-- ✓ atomic update with a guard
UPDATE accounts SET balance = balance - 30 WHERE id = 1 AND balance >= 30;…or lock the row with SELECT … FOR UPDATE (PostgreSQL/MySQL).
Performance checklist
- Select only the columns you need (avoid
SELECT *in apps). - Check
EXPLAINfor full scans on big tables. - Index foreign keys and frequent filters.
- Avoid the N+1 problem: one query per item in a loop. Use a JOIN or
IN (...). - Paginate with keysets on large tables.
- Keep transactions short. Never wait for user input inside one.
Practice
Write the query "all orders for customers in Mumbai, newest first". Check its plan with EXPLAIN QUERY PLAN, add index(es) that help, and check the plan again.
1.An index on (customer_id, order_date) helps which filter?
2.What does the "A" in ACID guarantee?