Bitpath

Databases

Write real queries, then open the hood: why an index turns a minute into a millisecond, how transactions keep money from vanishing, and what Postgres does when you press Enter. Every query here really runs.

  • Intermediate
  • 4 units, 12 lessons, 149 exercises
  • SQL
  • Builds on Algorithm Foundations (Big-O), trees from Trees & Heaps help

Unit 01 · 3 lessons

Asking questions

Read tables with SELECT, joins and GROUP BY

  1. > start01Rows and filters
  2. 02Joins
  3. BOSSThe sales report
Unit prize
  1. 01
    Rows and filters

    SELECT, WHERE, ORDER BY, and the trap called NULL

  2. 02
    Joins

    Follow keys from one table to another

  3. BOSS
    The sales report

    COUNT, SUM, GROUP BY and HAVING, end to end

Read the unit guide

A relational database keeps data in tables. Each row is one thing (a user, an order) and each column is one fact about it. SQL is how you ask questions: you describe the rows you want and the database works out how to fetch them.

The core query is SELECT columns FROM table WHERE test. Add ORDER BY to sort, LIMIT to cap the row count and DISTINCT to drop duplicates. Without ORDER BY the order of rows is not promised, even if it looks stable today.

NULL means unknown. Comparing anything with NULL gives unknown, not true or false, and WHERE keeps only rows where the test is true. So age > 26 OR age <= 26 still skips rows with no age. Test for it with IS NULL and IS NOT NULL.

Tables point at each other with keys: orders.user_id holds a users.id. JOIN ... ON produces one row per matching pair, so a user with three orders appears three times and a user with none disappears. LEFT JOIN keeps every row of the left table and fills the missing side with NULL. Many-to-many links (students and courses) go through a third table with one row per link.

Aggregates fold many rows into one value: COUNT, SUM, AVG, MIN, MAX. They skip NULLs, except COUNT(*), which counts rows. GROUP BY gives one output row per group. WHERE filters rows before grouping; HAVING filters groups after.

The clauses run in this order: FROM and joins, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT. The classic trap is aggregating after a join that multiplied your rows: the sum counts the same order once per matching item.

Unit 02 · 3 lessons

Finding rows fast

Know why one query takes a millisecond and its twin a minute

  1. 01The B-tree
  2. 02Composite indexes
  3. BOSSFix the slow query
Unit prize
  1. 01
    The B-tree

    From reading every row to a few steps down a tree

  2. 02
    Composite indexes

    Column order decides which queries an index can serve

  3. BOSS
    Fix the slow query

    Read a plan, pick the index, confirm the fix

Read the unit guide

A table is a heap of rows in no useful order. Finding rows by a column with no index means reading every row: a full table scan, O(n). That is fine for a thousand rows and painful for a hundred million.

An index is a separate, sorted copy of one or more columns, each entry pointing at its row. It is stored as a B-tree: wide pages of sorted keys, a few levels deep, so three or four page reads find one key among millions. Lookups are O(log n), and because the keys are sorted, ranges (age > 60) and ORDER BY come cheap too. The primary key always has an index.

Nothing is free. Every index must be updated on every INSERT, UPDATE and DELETE, and takes disk and memory. Index what your queries filter, join and sort on, not everything.

A composite index on (city, age) is sorted by city, then by age inside each city, like a phone book. It serves queries on a leftmost prefix: city, or city and age, but not age alone. Put columns tested with = first and the range column last. If the index holds every column the query needs, the table is never touched: a covering index.

Indexes get ignored when the query hides the sort order: a function around the column (lower(email), date(created)), a pattern starting with %, or a filter that matches most of the table anyway.

Do not guess: ask. EXPLAIN shows the plan. A scan (SCAN in SQLite, Seq Scan in Postgres) on a big table, or a separate sort step, is your suspect. Change the index or the query, then run EXPLAIN again. And watch for the N+1 pattern: one query per row in a loop, where a single join would do.

Unit 03 · 3 lessons

Transactions

Keep data correct when many users change it at once

  1. 01All or nothing
  2. 02Isolation levels
  3. BOSSThe lost update
Unit prize
  1. 01
    All or nothing

    BEGIN, COMMIT, ROLLBACK and the four ACID promises

  2. 02
    Isolation levels

    What one transaction may see of another

  3. BOSS
    The lost update

    Two buyers, one ticket, three ways to get it right

Read the unit guide

A transaction groups several statements into one unit. BEGIN starts it, COMMIT makes everything permanent at once, and ROLLBACK throws everything away. A crash before COMMIT counts as a rollback. A transfer that subtracts here and adds there either happens completely or not at all.

The promises are called ACID. Atomicity: all or nothing. Consistency: the rules (constraints) hold before and after. Isolation: concurrent transactions do not see each other's half-finished work. Durability: once COMMIT returns, the change survives a crash.

Isolation comes in levels. READ COMMITTED (the Postgres default) lets each statement see whatever is committed at that moment, so the same SELECT can give two answers inside one transaction. REPEATABLE READ gives the whole transaction one snapshot. SERIALIZABLE behaves as if transactions ran one after another, and makes one of them fail and retry when that cannot be kept up. The anomalies have names: dirty read, non-repeatable read, phantom read.

The bug to know by heart is the lost update: two transactions read a value, each computes a new one, and the second write overwrites the first. Fix it by letting the database do the arithmetic in one statement (SET stock = stock - 1 WHERE stock > 0), by locking the row first (SELECT ... FOR UPDATE), or optimistically with a version column and a retry.

Locks are held until the transaction ends, so two transactions that take the same locks in opposite orders can wait on each other forever: a deadlock. The database notices and aborts one of them. Prevent it by always locking things in the same order, and keep transactions short.

Unit 04 · 3 lessons

Design and internals

Shape the data, pick the engine, and look under the hood

  1. 01Modeling data
  2. 02SQL or NoSQL
  3. BOSSInside Postgres
Unit prize
  1. 01
    Modeling data

    One fact in one place, and a schema that says no

  2. 02
    SQL or NoSQL

    What each kind of database gives up, and what it gets

  3. BOSS
    Inside Postgres

    Row versions, the write-ahead log, VACUUM and replicas

Read the unit guide

Good schemas store each fact once. When the same email sits in a thousand order rows, every change has to find every copy, and a missed one leaves data that contradicts itself. Normalizing means splitting tables until each fact lives in one row, with other tables pointing at it by key. Give rows a meaningless id as primary key: real-world values like emails change.

Let the schema say no. Types, NOT NULL, UNIQUE, CHECK and foreign keys are rules the database enforces on every write, whoever does the writing. Store money as an exact type or as integer cents, never as a float. Denormalize (keep a deliberate copy, like a review count) only when a measured read is too slow, and accept that every write must now keep the copy right.

NoSQL databases drop some of what relational ones promise, to gain something else. Key-value stores fetch a blob by key and nothing more. Document stores keep a nested object per item: one read loads it all, but shared facts are copied into many documents. Wide-column and graph stores fit huge time-ordered writes and many-hop relationships. They spread over machines easily because each request touches one key. Unless you know you need that, a single relational database is the safe default, and it can hold JSON too.

Inside Postgres, rows live in fixed-size pages, and an UPDATE never overwrites: it writes a new row version and marks the old one ended. Each transaction's snapshot picks the versions it may see, so readers never block writers. This is MVCC. Dead versions pile up until VACUUM reclaims them.

Durability comes from the write-ahead log. Every change is appended to the WAL, and COMMIT returns once the log is on disk; data pages are written later, and a crash is repaired by replaying the log. Replicas are other servers replaying the same log. By default the primary does not wait for them, so a replica can lag, and a commit can be lost if the primary dies at the wrong moment.

Learn Databases on your phone.

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy