Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

SQL
SQL
0/12 completed
Beginner
What is a database?SELECT: reading dataFiltering with WHERESorting and limiting results
Intermediate
Aggregates and GROUP BYJOINs: combining tablesINSERT, UPDATE and DELETECreating tables and constraints
Advanced
Subqueries and CTEsWindow functions
Pro
Indexes and transactionsDatabase design and normalization
Tracks / SQL / Pro

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.

SQL · editable

SCAN orders means a full scan. Now add an index and check again:

SQL · editable

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 … ON and ORDER BY
  • Foreign key columns (PostgreSQL doesn't index them automatically!)
  • Primary keys and UNIQUE columns 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.

SQL · editable

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

sql
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 column

Transactions 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.

SQL · editable

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:

sql
-- ✗ 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

  1. Select only the columns you need (avoid SELECT * in apps).
  2. Check EXPLAIN for full scans on big tables.
  3. Index foreign keys and frequent filters.
  4. Avoid the N+1 problem: one query per item in a loop. Use a JOIN or IN (...).
  5. Paginate with keysets on large tables.
  6. 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.

SQL · editable
✎ Check your understanding

1.An index on (customer_id, order_date) helps which filter?

2.What does the "A" in ACID guarantee?

← Window functions