Everything from the map above, on one page. Dashed topics are optional. The hours are rough estimates for reading plus hands-on practice.
Stage 1 · Beginner Querying data
Get a database running on your own computer and learn to read and change data with SQL. Most of what developers do with a database every day is in this stage.
Relational databases and your first database
A relational database stores data in tables: each table has named, typed columns, and each row is one record. A primary key identifies each row, and a foreign key in one table points at a row in another, which is how a database links an order to its customer without copying the customer's details. You describe what data you want in SQL (Structured Query Language), and the database works out how to fetch it.
The popular open-source databases are PostgreSQL (feature-rich, the default choice for new projects), MySQL/MariaDB (very common in web hosting) and SQLite (a whole database in one file, built into phones, browsers and Python). The core SQL is the same in all of them; quoting, types and some functions differ. Install PostgreSQL, or run it in Docker, and use psql or a GUI such as pgAdmin or DBeaver.
What to learn
- Tables, rows, columns, primary keys and foreign keys
- What a database server, a database, a schema and a client are
- PostgreSQL vs MySQL vs SQLite, and when SQLite is enough
- Install PostgreSQL (or
docker run -e POSTGRES_PASSWORD=secret -p 5432:5432 postgres:18) and connect with psql
- SQL statement groups: queries (SELECT), changes (INSERT/UPDATE/DELETE) and definitions (CREATE/ALTER/DROP)
Free resources
Practice
Install PostgreSQL, create a database called practice, create a table books (id, title, author, year), add three rows and read them back with SELECT * FROM books;. Try \dt and \d books in psql.
SELECT basics
Every query starts with SELECT columns FROM table. Choose the columns you need instead of SELECT * in real code, so the query keeps working when columns are added and moves less data. Give columns and tables short names with AS, compute new columns from expressions (price * quantity AS total) and remove duplicate rows with DISTINCT.
A query reads in the order SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT, but the database runs it roughly as FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT. That is why a column alias from SELECT can be used in ORDER BY but not in WHERE. In PostgreSQL, strings use single quotes ('Alice') and double quotes are for names ("Order"); unquoted names are folded to lower case. MySQL uses backticks for names.
What to learn
SELECT, FROM, column lists and why to avoid SELECT * in application code
- Aliases with
AS, arithmetic and string concatenation (||) in SELECT
DISTINCT and DISTINCT ON (PostgreSQL)
- The logical order a query runs in, and why aliases can't be used in WHERE
- Quoting rules:
'strings' vs "names" (vs MySQL `names`)
Free resources
Practice
Do all of SQLBolt lessons 1–4 and the "Basic" section of PostgreSQL Exercises, then solve the problems below.
Practice problems
Filtering, sorting and NULL
WHERE keeps only the rows that match a condition: comparisons, AND/OR/NOT, IN (…), BETWEEN, and pattern matching with LIKE 'abc%' (ILIKE ignores case in PostgreSQL; PostgreSQL and MySQL also offer regular expressions). ORDER BY sorts the result, and LIMIT/OFFSET take a page of it. Without ORDER BY, the database is free to return rows in any order.
NULL means "unknown", and it trips up everyone. x = NULL is never true, not even when x is NULL: use IS NULL / IS NOT NULL. Any comparison with NULL gives NULL, which WHERE treats as false, so WHERE status <> 'done' silently skips rows whose status is NULL. COALESCE(x, 0) replaces NULL with a default, and IS DISTINCT FROM compares values treating NULLs as equal.
What to learn
- WHERE with comparisons, AND/OR/NOT and brackets, IN and BETWEEN
LIKE/ILIKE with % and _, and regex matching (~ in PostgreSQL, REGEXP in MySQL)
- Three-valued logic:
IS NULL, COALESCE, IS DISTINCT FROM
ORDER BY several columns, ASC/DESC, NULLS FIRST/LAST
LIMIT/OFFSET (and FETCH FIRST n ROWS ONLY, the standard form)
Free resources
Practice
On a table with some NULLs, predict then check the row counts of WHERE x = 1, WHERE x <> 1, WHERE x IS NULL and WHERE x IS DISTINCT FROM 1. The first three should not add up to the table size unless you remember NULL.
Practice problems
Functions, CASE and dates
SQL has a large library of built-in functions. String functions (lower, upper, length, substring, trim, replace, concat), maths (round, abs, integer vs decimal division: 7 / 2 is 3 in PostgreSQL), type casts (CAST(x AS numeric) or x::numeric) and, above all, CASE WHEN … THEN … ELSE … END, which is SQL's if/else and works anywhere an expression does.
Dates and times differ most between databases. In PostgreSQL use now(), date_trunc('month', ts), extract(year FROM ts) and interval arithmetic (ts + interval '7 days'). MySQL has DATE_ADD/DATEDIFF, and SQLite stores dates as text or numbers and uses date()/strftime(). Store moments in time as timestamptz (UTC inside) and convert to a time zone only for display.
What to learn
- String functions, concatenation and integer vs decimal division
CASE expressions (searched and simple forms)
- Casting:
CAST(… AS …) and PostgreSQL's ::
- Dates:
now(), date_trunc, extract, intervals, AT TIME ZONE
COALESCE and NULLIF (e.g. avoiding division by zero)
Free resources
Practice
Write one query over an orders table that shows each order's month (date_trunc), a size label from a CASE (small / medium / large by amount) and the customer name in title case. Then solve the problems below.
Practice problems
Inserting, updating and deleting
INSERT INTO t (cols) VALUES (…), (…) adds rows, UPDATE t SET col = … WHERE … changes them and DELETE FROM t WHERE … removes them. Forgetting the WHERE on an UPDATE or DELETE changes every row, so run the same WHERE as a SELECT first, or do it inside a transaction you can roll back. RETURNING (PostgreSQL and SQLite) gives back the rows you changed, such as a newly generated id.
An upsert inserts a row or updates it if it already exists: INSERT … ON CONFLICT (email) DO UPDATE SET … in PostgreSQL and SQLite, INSERT … ON DUPLICATE KEY UPDATE in MySQL, and the standard MERGE in PostgreSQL 15 and later. For bulk loading, PostgreSQL's COPY (or psql's \copy) reads a CSV file far faster than thousands of INSERTs.
What to learn
- Multi-row
INSERT, and INSERT … SELECT
UPDATE and DELETE with WHERE, and checking with a SELECT first
RETURNING to get generated ids back
- Upserts:
ON CONFLICT, MySQL's ON DUPLICATE KEY UPDATE, and MERGE
- Bulk loading with
COPY / \copy from CSV
Free resources
Practice
Generate 1,000 fake users as SQL INSERTs or a CSV, load them, then write an upsert that updates a user's name when the email already exists and inserts otherwise. Use RETURNING to see what happened.
Practice problems
Am I ready? Stage 1 quiz
A table has 10 rows; 3 of them have status NULL and 2 have status = 'done'. How many rows does WHERE status <> 'done' return?
- 8
- 7
- 5
- 0
Comparing NULL with anything gives NULL, which WHERE treats as false, so the 3 NULL rows are dropped: 10 − 2 − 3 = 5.
Why does SELECT price * qty AS total FROM items WHERE total > 100 fail in PostgreSQL?
- WHERE runs before SELECT, so the alias doesn't exist yet
- Aliases need double quotes
total is a reserved word- Expressions aren't allowed in SELECT
Logically, FROM and WHERE run before SELECT. Repeat the expression in WHERE, or wrap the query in a subquery or CTE.
What does SELECT 7 / 2; return in PostgreSQL?
- 3.5
- 4
- An error
- 3
Dividing two integers does integer division. Write 7 / 2.0 or cast one side to numeric for 3.5.
Which statement inserts a user, or updates the name if the email already exists, in PostgreSQL?
INSERT … ON DUPLICATE KEY UPDATEINSERT … ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.nameREPLACE INTO …UPDATE … OR INSERT
ON CONFLICT is the PostgreSQL (and SQLite) upsert; EXCLUDED holds the row you tried to insert. ON DUPLICATE KEY UPDATE is MySQL's version.
You are about to run DELETE FROM orders WHERE … on real data. What is the safest habit?
- Run it and check the row count afterwards
- Add
LIMIT 1 - Run the same WHERE as a SELECT first, and do the delete inside a transaction you can roll back
- Delete through a GUI instead
Checking with a SELECT shows exactly what will go, and BEGIN; DELETE …; ROLLBACK; lets you undo if the count looks wrong.
Stage 2 · Intermediate Combining and summarising data
Real questions need data from several tables, totals per group, and rankings. This stage is where SQL becomes powerful, and it's what SQL interview questions test.
Joins
A join combines rows from two tables using a condition, usually a foreign key: FROM orders o JOIN customers c ON c.id = o.customer_id. An INNER JOIN keeps only rows that have a match on both sides. A LEFT JOIN keeps every row from the left table and fills the right side with NULLs where there is no match, which is how you find "customers with no orders" (WHERE o.id IS NULL). RIGHT and FULL OUTER joins work the same way from the other side or both.
A self join joins a table to itself, for example employees to their managers. A CROSS JOIN returns every combination, which is useful for building a grid such as every student × every subject. Watch for two classic mistakes: a condition on the right table in WHERE turns a LEFT JOIN back into an inner join (put it in ON instead), and joining to a table with several matches per row multiplies rows, which inflates SUMs.
What to learn
INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN, CROSS JOIN
- Anti-joins: LEFT JOIN … WHERE right.id IS NULL (or
NOT EXISTS)
- Self joins (employee → manager, today vs yesterday)
- ON vs WHERE for conditions on the outer side of a LEFT JOIN
- Joining three or more tables, and spotting row multiplication
Free resources
Practice
Solve the "Joins and subqueries" section of PostgreSQL Exercises. Then, on your own data, find customers who have never ordered in three ways (LEFT JOIN, NOT EXISTS, NOT IN) and check they agree. Add a customer_id NULL to the orders table and see which one breaks.
Practice problems
Aggregation: GROUP BY and HAVING
Aggregate functions turn many rows into one value: COUNT, SUM, AVG, MIN, MAX, and in PostgreSQL also string_agg and array_agg. GROUP BY splits rows into groups and gives one result row per group, so every selected column must either be in GROUP BY or inside an aggregate. HAVING filters groups after aggregating (HAVING COUNT(*) >= 5); WHERE filters rows before.
COUNT(*) counts rows, COUNT(col) counts non-NULL values and COUNT(DISTINCT col) counts different values. Aggregates other than COUNT ignore NULLs. For conditional totals, PostgreSQL's COUNT(*) FILTER (WHERE status = 'paid') is clearest; SUM(CASE WHEN … THEN 1 ELSE 0 END) works everywhere. Rates and averages are where integer division and NULLs bite, so cast and round deliberately.
What to learn
COUNT(*) vs COUNT(col) vs COUNT(DISTINCT col)
GROUP BY one or more columns, and the "must be in GROUP BY" rule
HAVING vs WHERE
- Conditional aggregates:
FILTER (WHERE …) and SUM(CASE …)
string_agg/array_agg (MySQL: GROUP_CONCAT), and ROLLUP/GROUPING SETS for subtotals
Free resources
Practice
From an orders table, produce one row per month with the number of orders, revenue, number of distinct customers and the share of paid orders as a percentage rounded to two decimals. Then solve the problems below.
Practice problems
Subqueries and CTEs
A subquery is a query inside another one. It can return a single value (WHERE salary > (SELECT AVG(salary) FROM employees)), a list for IN, or a whole table in FROM. A correlated subquery refers to the outer row and conceptually runs once per row; EXISTS (SELECT 1 FROM … WHERE …) is the usual way to ask "is there a matching row?". Beware NOT IN with a subquery that can return NULL: it then returns no rows at all, so prefer NOT EXISTS.
A CTE (WITH name AS (…)) names a subquery so a long query reads top to bottom in steps. Since PostgreSQL 12, simple CTEs are inlined and optimised like subqueries (add MATERIALIZED to force computing one once). WITH RECURSIVE walks hierarchies such as org charts, category trees or graphs: an anchor query plus a part that joins back to the CTE until no new rows appear.
What to learn
- Scalar, list (
IN) and table subqueries
- Correlated subqueries and
EXISTS / NOT EXISTS
- The
NOT IN + NULL trap
- CTEs with
WITH to break a query into readable steps
WITH RECURSIVE for trees and hierarchies
Free resources
Practice
Build an employees (id, name, manager_id) table four levels deep and write a WITH RECURSIVE query that lists everyone under one manager with their level. Then rewrite one of your Stage 1 queries as a chain of CTEs.
Practice problems
UNION, INTERSECT and EXCEPT
Set operations stack the results of two queries with the same number and types of columns. UNION combines them and removes duplicates; UNION ALL keeps duplicates and is faster, so use it unless you really need de-duplication. INTERSECT keeps rows found in both results and EXCEPT (Oracle: MINUS) keeps rows in the first but not the second.
A common use is "unpivoting": turning columns into rows, such as one query per store column joined with UNION ALL. Another is emulating FULL OUTER JOIN in MySQL, which doesn't have one. Column names come from the first query, and ORDER BY applies to the whole combined result.
What to learn
UNION vs UNION ALL, and why UNION ALL is cheaper
INTERSECT and EXCEPT
- Matching column counts and types; names come from the first query
- Unpivoting columns into rows, and building category rows that may have zero counts
Free resources
Practice
Write a query that lists every email that appears in either a customers or a newsletter table, tagged with where it came from, then one with only the emails in both, then those only in customers.
Practice problems
Window functions
A window function computes a value across a set of rows related to the current row without collapsing them the way GROUP BY does. OVER (PARTITION BY dept ORDER BY salary DESC) defines the window: the rows of the same department, in salary order. With it you can number rows (ROW_NUMBER), rank them (RANK leaves gaps after ties, DENSE_RANK doesn't), look at the previous or next row (LAG, LEAD) and compute running totals or moving averages (SUM(x) OVER (ORDER BY day)).
The classic interview pattern is "top N per group": rank rows in a CTE with DENSE_RANK() OVER (PARTITION BY …), then keep rank <= N outside, because window functions can't be used in WHERE. The frame clause (ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) controls which rows a running aggregate sees. Window functions work in PostgreSQL, MySQL 8.0+ and SQLite 3.25+.
What to learn
OVER, PARTITION BY and ORDER BY inside a window
ROW_NUMBER, RANK, DENSE_RANK, NTILE
LAG / LEAD for comparing a row with the previous or next one
- Running totals and moving averages with frames (
ROWS BETWEEN …)
- Top N per group with a CTE, and "gaps and islands" (consecutive runs)
Free resources
Practice
For a daily sales table, write one query that shows each day's sales, the change from the previous day, a 7-day moving average, the running total for the month and the day's rank within its month.
Practice problems
Am I ready? Stage 2 quiz
You want every customer, including those with no orders, with their order count. Which join?
INNER JOIN ordersLEFT JOIN orders, and COUNT(o.id)CROSS JOIN ordersLEFT JOIN orders, and COUNT(*)
A LEFT JOIN keeps customers without orders. COUNT(o.id) ignores the NULL from the missing match and gives 0; COUNT(*) would count that row and give 1.
What is the difference between WHERE and HAVING?
- None, they are synonyms
- HAVING is faster
- WHERE can only compare numbers
- WHERE filters rows before grouping; HAVING filters groups after aggregation
Use WHERE for row conditions and HAVING for conditions on aggregates such as COUNT(*) > 5.
SELECT * FROM a WHERE id NOT IN (SELECT a_id FROM b) suddenly returns no rows. What is the likely cause?
b.a_id contains a NULLb is empty- NOT IN needs an index
- The subquery must be a CTE
x NOT IN (1, NULL) is never true, because x could equal the unknown value. Use NOT EXISTS, which handles NULLs as you'd expect.
Salaries 100, 90, 90, 80. What does RANK() give the 80, and what does DENSE_RANK() give it?
- 3 and 3
- 4 and 4
- 4 and 3
- 3 and 4
RANK leaves a gap after the tie (1, 2, 2, 4); DENSE_RANK doesn't (1, 2, 2, 3).
Which query combines two lists of emails and keeps duplicates, doing the least work?
UNIONUNION ALLINTERSECTFULL OUTER JOIN
UNION has to sort or hash to remove duplicates; UNION ALL just appends the second result.
Stage 3 · Intermediate Designing and tuning databases
Design tables that keep data correct, make queries fast with the right indexes, change the schema safely, and use the database well from application code.
Schema design and data modelling
Schema design starts from the entities your application deals with (users, orders, products) and the relationships between them. One-to-many is a foreign key on the "many" side (each order has a customer_id). Many-to-many needs a junction table (order_items (order_id, product_id, quantity)) with a primary key over both ids. One-to-one is usually just extra columns, or a separate table sharing the same key. Draw it as an entity–relationship (ER) diagram before writing any SQL.
Every table needs a primary key. A surrogate key (an auto-generated bigint identity or a UUID) never changes, while a natural key (an email, an ISBN) can, so most designs use surrogate keys plus a UNIQUE constraint on the natural one. Pick one naming style (snake_case, singular or plural table names) and stick to it, and model what the data is, not one screen of today's UI.
What to learn
- Entities, attributes and relationships; drawing an ER diagram
- One-to-many, many-to-many (junction tables) and one-to-one
- Surrogate vs natural keys, and
GENERATED ALWAYS AS IDENTITY vs UUIDs
- Naming conventions, and soft deletes vs real deletes
- Modelling history (valid-from / valid-to rows, audit tables)
Free resources
Practice
Design the schema for a small online shop: customers, addresses, products, categories, orders, order items and reviews. Draw the ER diagram, write the CREATE TABLE statements, and write the query for "the five best-selling products in each category last month".
Choosing data types
The right type keeps bad data out and saves space. In PostgreSQL: bigint for ids and counters, numeric(12,2) for money (never float, which can't store 0.1 exactly), text for strings (it performs the same as varchar(n); add a CHECK if you need a length limit), boolean, date, and timestamptz for moments in time. timestamp without time zone stores a wall-clock reading with no zone, which causes bugs as soon as servers or users are in different zones.
uuid ids can be generated anywhere without a round trip to the database. Random version-4 UUIDs scatter inserts across the index, while time-ordered UUID v7 (built into PostgreSQL 18 as uuidv7()) keeps new rows together. jsonb stores flexible JSON that can be indexed, but it isn't a replacement for real columns. SQLite is different: it uses type affinity, so a column declared INTEGER can hold text unless the table is created STRICT.
What to learn
- Integers,
numeric for money, and why not float
text vs varchar(n) in PostgreSQL
timestamptz vs timestamp, and storing UTC
uuid (v4 vs v7) vs bigint identity keys
jsonb, arrays and enums (vs a lookup table or CHECK)
Free resources
Practice
Review the types in your shop schema against the "Don't Do This" page. Then run SELECT 0.1::float8 + 0.2::float8 = 0.3, 0.1::numeric + 0.2 = 0.3; and explain the difference.
Normalisation
Normalisation organises tables so each fact is stored in exactly one place. Duplicated facts drift apart: if a customer's city is copied onto every order, changing it means updating many rows, and missing one leaves the data contradicting itself (an update anomaly). The normal forms are rules for avoiding that. 1NF: one value per column, no repeating groups (no phone1, phone2, phone3, no comma-separated lists). 2NF: every non-key column depends on the whole primary key, not part of a composite key. 3NF: non-key columns depend only on the key, not on another non-key column. In short, "the key, the whole key and nothing but the key".
3NF (or BCNF) is the normal target for transactional data. Denormalising on purpose (storing a count, copying a name onto a row) can make reads cheaper, but then you own keeping the copies in sync. Do it when a measured query needs it, not up front. Reporting and analytics databases are often deliberately denormalised into star schemas.
What to learn
- Update, insert and delete anomalies caused by duplicated data
- Functional dependencies
- 1NF, 2NF, 3NF and BCNF with examples
- When and how to denormalise deliberately
Free resources
Practice
Take a spreadsheet-style table orders(order_id, date, customer_name, customer_email, customer_city, product_names, product_prices, total) and normalise it to 3NF. List each anomaly the original had and show how your design removes it.
Constraints and data integrity
Constraints make the database refuse bad data, whatever code writes to it. NOT NULL requires a value. UNIQUE forbids duplicates (for example one account per email). PRIMARY KEY is NOT NULL + UNIQUE. CHECK (price >= 0) enforces any rule about a row. A FOREIGN KEY … REFERENCES customers(id) guarantees the referenced row exists, and ON DELETE CASCADE, SET NULL or the default RESTRICT/NO ACTION decide what happens when it is deleted.
Application validation is for friendly error messages; constraints are the guarantee, because there is always a second code path, a script or a race between two requests. A unique constraint is the only reliable way to stop two simultaneous sign-ups with the same email. PostgreSQL also has exclusion constraints (for example "no two bookings for the same room may overlap"). Note that PostgreSQL indexes primary keys and unique columns automatically, but not foreign key columns.
What to learn
NOT NULL, UNIQUE, PRIMARY KEY, CHECK and DEFAULT
- Foreign keys and
ON DELETE / ON UPDATE actions
- Why constraints beat application-only validation (races, other writers)
- Indexing foreign key columns yourself in PostgreSQL
- Exclusion constraints and partial unique indexes
Free resources
Practice
Add every constraint your shop schema needs. Then try to break it: insert an order for a customer who doesn't exist, a negative price, a duplicate email, and delete a customer who has orders. Each should fail with a clear error.
Indexes
Without an index, finding rows means reading the whole table (a sequential scan). An index is a separate, sorted structure (a B-tree by default) that lets the database jump to matching rows in a few page reads, like the index at the back of a book. B-trees support =, ranges, ORDER BY and prefix LIKE 'abc%'. A composite index on (customer_id, created_at) helps queries that filter on customer_id, or on both, but not on created_at alone, because it is sorted by the first column first.
Indexes aren't free: each one slows down writes and takes space, so add them for real queries. A function on the column (WHERE lower(email) = …) can't use a plain index; create an expression index on lower(email) instead. PostgreSQL also has partial indexes (WHERE status = 'pending'), covering indexes (INCLUDE (…) for index-only scans), GIN for jsonb, arrays and full-text search, BRIN for huge append-only tables, and hash indexes for equality only.
What to learn
- How a B-tree index works and what it can and can't speed up
- Composite indexes and column order (the leftmost-prefix rule)
- Expression, partial and covering (
INCLUDE) indexes
- GIN, BRIN and hash indexes, and when each fits
- The write cost of indexes, and finding unused ones (
pg_stat_user_indexes)
Free resources
Practice
Load a million rows (generate_series or generated data) into an orders table. Time a lookup by customer and date range with no index, with an index on customer_id, and with one on (customer_id, created_at). Then time 10,000 inserts with and without the indexes.
Query plans and EXPLAIN
The query planner turns your SQL into a plan: which indexes to use, in what order to join tables and with which algorithm (nested loop for few rows, hash join for large unsorted sets, merge join for sorted inputs). It chooses by estimating costs from table statistics. EXPLAIN shows the chosen plan and its estimates; EXPLAIN ANALYZE actually runs the query and adds real row counts and times (it really executes, so wrap UPDATEs and DELETEs in BEGIN … ROLLBACK).
Read plans from the innermost node outwards. The usual problems are a sequential scan on a big table where you expected an index, estimated rows far from actual rows (stale statistics: run ANALYZE), and conditions that can't use an index (functions on the column, leading-wildcard LIKE, implicit casts). Deep OFFSET pagination reads and throws away every skipped row; keyset pagination (WHERE id > last_seen ORDER BY id LIMIT 20) doesn't. pg_stat_statements finds the slowest queries in a real system.
What to learn
EXPLAIN vs EXPLAIN (ANALYZE, BUFFERS), and reading a plan tree
- Seq scan, index scan, index-only scan and bitmap scan
- Nested loop, hash and merge joins
- Statistics,
ANALYZE, and estimated vs actual rows
- Keyset pagination, and finding slow queries with
pg_stat_statements
Free resources
Practice
Using your million-row table, write a slow query on purpose (a function on an indexed column, then a deep OFFSET), read its EXPLAIN ANALYZE, fix it, and compare the plans before and after.
Schema migrations
A schema changes as an application grows, and every environment (your laptop, CI, staging, production) must go through the same changes in the same order. Migrations are numbered, version-controlled scripts (V7__add_status_to_orders.sql) that a tool such as Flyway, Liquibase, Alembic, Django or Rails applies and records in a table, so each database knows which ones it has run. Never edit a migration that has already run somewhere; add a new one.
On a busy production table, some changes lock it for a long time. In PostgreSQL, adding a nullable column or one with a constant default is instant (since version 11), but adding an index locks writes unless you use CREATE INDEX CONCURRENTLY, and adding NOT NULL scans the table. Zero-downtime changes use expand and contract: add the new column, write to both, backfill in batches, switch reads, then drop the old one in a later release. Set a lock_timeout so a migration gives up rather than queueing every query behind it.
What to learn
- Versioned migrations with a tool (Flyway, Liquibase, Alembic or your framework's)
- Never change an applied migration; roll forward with a new one
- Which
ALTER TABLE operations lock or rewrite a table
CREATE INDEX CONCURRENTLY, NOT VALID constraints and lock_timeout
- Expand and contract for renames and type changes, and backfilling in batches
Free resources
Practice
Put your shop schema under a migration tool. Then rename customers.name to full_name with expand and contract, as three separate migrations that could each be deployed without downtime.
Using SQL from application code
Applications talk to the database through a driver (psycopg, node-postgres, JDBC, pgx…). Always send values as parameters (WHERE email = $1 in PostgreSQL, ? in MySQL and SQLite), never by pasting user input into the SQL string. Building SQL with string concatenation is how SQL injection happens, still one of the most common security holes. Parameters also let the database reuse query plans.
Opening a connection is slow and each PostgreSQL connection is a whole server process, so applications use a connection pool (in the driver, or PgBouncer in front of the database) with a small number of connections. ORMs such as SQLAlchemy, Hibernate, Prisma or Django's map tables to objects and save boilerplate, but watch for the N+1 problem (one query for a list, then one more per item) and look at the SQL they generate.
What to learn
- Connecting with a driver and a connection string, and keeping credentials out of code
- Parameterised queries and how SQL injection works
- Connection pools and PgBouncer
- ORMs vs query builders vs plain SQL, and logging the generated SQL
- The N+1 problem and eager loading
Free resources
Practice
Write a tiny script in your language that searches customers by name using a parameterised query. Then write the unsafe string-concatenated version and show that the input ' OR '1'='1 returns every row. Finally, list orders with their items through an ORM, count the queries it sends, and fix the N+1.
Views, functions and triggers
A view is a saved query you can select from like a table, handy for hiding complex joins or exposing only some columns. A materialized view stores the result and is refreshed on demand (REFRESH MATERIALIZED VIEW CONCURRENTLY, which needs a unique index), which suits slow reports. Functions and procedures (in SQL or PL/pgSQL) run logic inside the database, and triggers run a function automatically when rows change, for example to fill an updated_at column or write an audit log.
Logic in the database is close to the data and applies to every writer, but it is harder to test, version and debug than application code. Use it for integrity and auditing; keep business rules in the application unless there is a good reason.
What to learn
- Views and materialized views, and refreshing them
- SQL and PL/pgSQL functions
- Triggers: BEFORE/AFTER, row vs statement level
- Generated columns as a simpler alternative to some triggers
Free resources
Practice
Add a trigger that keeps updated_at current on every table, and an audit trigger that writes old and new values of changed orders as jsonb to an order_history table. Build a materialized view of monthly revenue and refresh it.
Am I ready? Stage 3 quiz
Which index helps WHERE created_at > now() - interval '1 day' on its own?
- An index on
(customer_id, created_at) - A hash index on
created_at - A B-tree index on
created_at (or one with created_at first) - No index can help a range condition
A composite index is sorted by its first column first, so it can't be used efficiently for the second column alone, and hash indexes only support equality.
A table stores order_id, product_id, product_name, quantity with the primary key (order_id, product_id). Which normal form does it break?
- 2NF:
product_name depends on only part of the key - 1NF: it has a composite key
- 3NF:
quantity depends on the key - None, it is fully normalised
product_name depends on product_id alone, so it belongs in a products table. That is a partial dependency, which 2NF forbids.
Which type should hold prices in PostgreSQL?
float8realtextnumeric (e.g. numeric(12,2)), or an integer number of cents
Floating-point types can't store most decimal fractions exactly, so sums drift by fractions of a cent.
What makes EXPLAIN ANALYZE different from EXPLAIN?
- It also rebuilds statistics
- It actually runs the query and shows real row counts and timings
- It only works on SELECT
- It suggests missing indexes
Because it really executes the statement, run it on UPDATE or DELETE only inside a transaction you roll back.
Your code builds "SELECT * FROM users WHERE name = '" + input + "'". What is the fix?
- Escape single quotes with a regex
- Limit the input length
- Use a parameterised query and pass
input as a parameter - Use an ORM's raw SQL method with the same string
Parameters send the value separately from the SQL text, so it can never change the query's structure. Hand-made escaping misses edge cases.
Stage 4 · Advanced Databases in production
Concurrency, PostgreSQL in depth, security, backups and replication, and when a different kind of database is the better fit. The System Design roadmap continues from here.
Transactions and ACID
A transaction groups statements so they succeed or fail together: BEGIN; UPDATE accounts SET balance = balance - 100 WHERE id = 1; UPDATE accounts SET balance = balance + 100 WHERE id = 2; COMMIT;. If anything fails before COMMIT, ROLLBACK undoes it all. The guarantees are called ACID: Atomicity (all or nothing), Consistency (constraints hold after every transaction), Isolation (concurrent transactions don't see each other's half-done work) and Durability (once committed, it survives a crash, thanks to the write-ahead log).
Without an explicit BEGIN, each statement is its own transaction (autocommit). Keep transactions short: an open transaction holds locks and, in PostgreSQL, stops VACUUM from cleaning up old row versions. Never wait for a user or a slow HTTP call inside one. SAVEPOINT lets you roll back part of a transaction.
What to learn
BEGIN, COMMIT, ROLLBACK and autocommit
- What each letter of ACID guarantees
- The write-ahead log (WAL) and how durability works
SAVEPOINT and partial rollback
- Keeping transactions short, and handling errors in application code
Free resources
Practice
Write a money transfer between two accounts as one transaction, with a CHECK that balances can't go negative. Make the second UPDATE fail and confirm the first one was rolled back. Open two psql sessions and watch what the second one sees before and after the first commits.
Isolation levels, MVCC and locking
Running transactions fully one after another would be slow, so databases let them overlap and offer isolation levels that trade safety for speed. The anomalies to know are dirty reads, non-repeatable reads, phantoms, lost updates (two read-modify-write cycles overwrite each other) and write skew. PostgreSQL's default is Read Committed: each statement sees data committed before it started. Repeatable Read gives the whole transaction one snapshot. Serializable guarantees the result equals some one-at-a-time order, and aborts a transaction with a serialization error when it can't, so your code must retry. MySQL's InnoDB defaults to Repeatable Read.
PostgreSQL implements this with MVCC: an update writes a new row version and readers keep seeing the old one, so reads never block writes. Writers to the same row still wait for each other. To avoid lost updates, use an atomic UPDATE … SET stock = stock - 1, lock the row with SELECT … FOR UPDATE, or use optimistic locking with a version column. FOR UPDATE SKIP LOCKED turns a table into a safe job queue. Two transactions locking rows in opposite orders cause a deadlock, which PostgreSQL detects and resolves by aborting one of them.
What to learn
- Anomalies: dirty read, non-repeatable read, phantom, lost update, write skew
- Read Committed, Repeatable Read and Serializable in PostgreSQL (and MySQL's defaults)
- MVCC: row versions, snapshots, and why readers don't block writers
- Row locks:
SELECT … FOR UPDATE, SKIP LOCKED, optimistic locking with a version column
- Deadlocks, lock ordering and retrying serialization failures
Free resources
Practice
In two psql sessions, reproduce a lost update on a stock counter under Read Committed, then prevent it three ways: an atomic UPDATE, FOR UPDATE, and Serializable with a retry. Then cause a deadlock on purpose and read the error.
PostgreSQL in depth
PostgreSQL releases a major version every autumn and supports each for five years (18 is current as of October 2026). One server runs several databases; each database has schemas (namespaces, public by default) holding tables; roles are users and groups. Learn psql well: \l, \c, \dt, \d table, \x, \timing and \e. Extensions add features with one command: pg_stat_statements (query statistics), pgcrypto, PostGIS (maps and geometry), pgvector (vector search).
Beyond plain SQL, PostgreSQL has jsonb with operators (->, ->>, @>) and GIN indexes, arrays, ranges and built-in full-text search. Because of MVCC, updated and deleted rows leave dead versions behind; autovacuum cleans them up and refreshes statistics, and it should be tuned, not turned off. Settings such as shared_buffers, work_mem and max_connections live in postgresql.conf.
What to learn
- Servers, databases, schemas and roles;
search_path
- psql meta-commands and
\copy
jsonb operators and GIN indexes; arrays
- Extensions:
pg_stat_statements, pgcrypto, PostGIS
- VACUUM, autovacuum and table bloat; key settings in
postgresql.conf
- The release cycle and major-version upgrades (
pg_upgrade)
Free resources
Practice
Store product attributes as jsonb, index them with GIN and query "all products where colour is red" with @>; check the plan uses the index. Enable pg_stat_statements and list your five slowest queries.
Database security
Give every application its own role with only the privileges it needs (GRANT SELECT, INSERT, UPDATE ON orders TO shop_app), never a superuser, and separate roles for migrations and read-only reporting. Control who can connect, from where and how in pg_hba.conf, use scram-sha-256 passwords (the default since PostgreSQL 14) and TLS, and keep the database off the public internet.
Row-level security policies make the database itself filter rows, for example so each tenant sees only its own data. Store user passwords only as slow, salted hashes (bcrypt, scrypt or Argon2) computed by the application, never in plain text or with a fast hash like SHA-256. Keep secrets in a secret manager, not in code, and remember that backups contain everything, so encrypt and protect them too.
What to learn
- Roles,
GRANT/REVOKE and least privilege; default privileges
pg_hba.conf, scram-sha-256 and TLS connections
- Row-level security policies for multi-tenant data
- Password hashing (bcrypt/Argon2), and encrypting backups
- Auditing who changed what
Free resources
Practice
Create three roles for your shop: an app role (read/write on its tables only), a read-only reporting role and a migration role that owns the schema. Add a tenant_id column and a row-level security policy, and prove one tenant can't read another's rows.
Backups and point-in-time recovery
A backup you have never restored is a hope, not a backup. PostgreSQL offers two kinds. A logical backup with pg_dump (plus pg_dumpall --globals-only for roles) writes SQL or a compressed archive you restore with psql or pg_restore: simple, portable across versions, but slow for large databases and only as recent as the last dump. A physical backup (pg_basebackup) copies the data files, and together with continuously archived WAL it allows point-in-time recovery (PITR): restore to the second before someone ran a bad DELETE.
Decide two numbers first: RPO (how much data you can afford to lose) and RTO (how long a restore may take). Tools such as pgBackRest or Barman handle base backups, WAL archiving, retention and encryption; managed services like Amazon RDS do it for you. Follow the 3-2-1 rule (three copies, two media, one off-site) and test restores on a schedule. A replica is not a backup: it copies a mistaken DELETE within milliseconds.
What to learn
pg_dump / pg_restore formats and options, and pg_dumpall --globals-only
- Physical backups with
pg_basebackup and WAL archiving
- Point-in-time recovery to a timestamp
- RPO and RTO, retention, the 3-2-1 rule and encrypted off-site copies
- Scheduled, verified test restores
Free resources
Practice
Set up WAL archiving on a local server and take a base backup. Insert some rows, note the time, "accidentally" delete a table, then restore to the moment before the delete. Write down how long each step took: that's your RTO.
Replication and high availability
Replication keeps copies of a database on other servers. In PostgreSQL's streaming replication, the primary sends its WAL to standbys, which replay it and can serve read-only queries (read replicas). It is usually asynchronous: fast, but a replica can lag behind, so a user who writes and then reads from a replica may not see their own change, and a failover can lose the last few transactions. Synchronous replication waits for a standby to confirm each commit, trading latency for zero data loss.
High availability means promoting a standby when the primary fails, automatically with a tool such as Patroni or by a managed service (RDS Multi-AZ), and pointing applications at the new primary. Logical replication (publications and subscriptions) copies changes per table rather than whole servers, which is useful for upgrades with little downtime and for feeding other systems.
What to learn
- Streaming (physical) replication: primary, standby, hot standby
- Asynchronous vs synchronous replication and replication lag
- Read-your-own-writes problems with read replicas
- Failover, promotion and split brain; Patroni and managed Multi-AZ
- Logical replication: publications, subscriptions, zero-downtime upgrades
Free resources
Practice
With Docker Compose, run a primary and a streaming replica. Write on the primary and read on the replica, measure the lag with pg_stat_replication, stop the primary, promote the replica and reconnect.
NoSQL databases: when and which
"NoSQL" covers several kinds of databases built for needs that a single relational server handles poorly. Key-value stores (Redis, DynamoDB) fetch a value by its key extremely fast; Redis keeps data in memory and is the usual cache. Document databases (MongoDB) store JSON-like documents, so an object with nested parts is read in one go. Wide-column stores (Cassandra) spread huge write-heavy data over many machines. Graph databases (Neo4j) follow relationships many hops deep.
Most of them scale out by partitioning data across machines, and in exchange give up some of joins, multi-row transactions or immediate consistency. Design starts from the access patterns (which queries you will run), not the entities: in DynamoDB every query should hit a key you designed for it. For most applications PostgreSQL is still the right default, with jsonb for flexible parts; pick a NoSQL store for a specific need such as caching, enormous scale or a very predictable key-based workload.
What to learn
- Key-value, document, wide-column and graph databases, with an example of each
- Designing from access patterns: partition keys and sort keys
- Trade-offs: joins, transactions and consistency vs horizontal scale
- Redis as a cache, and its data types
- When PostgreSQL with
jsonb is enough
Free resources
Practice
Model your shop's orders in DynamoDB style: list the access patterns ("orders for a customer, newest first", "an order with its items"), then design one table with partition and sort keys that serves them all. Compare the result with your relational schema.
Scaling: partitioning, caching and sharding
Scale a database in steps, measuring as you go. First fix queries and indexes, then a bigger machine, then a connection pooler. Add read replicas for read-heavy traffic and a cache (Redis) for hot data. Partitioning splits one huge table into pieces inside the same server (PostgreSQL declarative partitioning by range, list or hash), so old months can be dropped instantly and queries touch only the partitions they need.
Sharding spreads data across several servers by a shard key (such as tenant id). It raises the write ceiling but makes cross-shard queries, transactions and rebalancing hard, so it is the last step, not the first. Citus (a PostgreSQL extension) and distributed SQL databases such as CockroachDB or YugabyteDB do the sharding for you.
What to learn
- The scaling ladder: tuning → bigger server → pooling → replicas → caching → partitioning → sharding
- Declarative partitioning and partition pruning
- Choosing a shard key, and the cost of cross-shard queries
- Distributed SQL options (Citus, CockroachDB, YugabyteDB)
Free resources
Practice
Partition an events table by month, load a year of data, check with EXPLAIN that a one-month query touches one partition, and drop the oldest month with DETACH PARTITION.
Analytics databases and data warehouses
Transactional databases (OLTP) handle many small reads and writes of single rows. Analytical work (OLAP) scans millions of rows but only a few columns, such as "revenue by region by month". Column-oriented databases store each column together, so such queries read far less data and compress well. Examples are DuckDB (an in-process database, like SQLite for analytics), ClickHouse, and cloud warehouses such as BigQuery, Snowflake and Redshift.
Warehouses are usually loaded from the transactional database by ELT/ETL pipelines and modelled as a star schema: a big fact table (sales) surrounded by dimension tables (date, product, store). Everything you learned about joins, aggregation and window functions applies directly.
What to learn
- OLTP vs OLAP workloads
- Row vs column storage, and why columns compress
- Star schemas: facts and dimensions
- DuckDB for local analytics on CSV and Parquet files
Free resources
Practice
Export a big table to CSV, query it with DuckDB (SELECT … FROM 'orders.csv') and compare the time of a GROUP BY with the same query in PostgreSQL.
Am I ready? Stage 4 quiz
Which ACID property makes sure a committed transfer survives a power cut a millisecond later?
- Atomicity
- Durability
- Isolation
- Consistency
Durability: the commit is only acknowledged once it is safely in the write-ahead log on disk, which is replayed after a crash.
Two requests both read stock = 5, subtract 1 in the application and write 4. Under PostgreSQL's default isolation, what is this, and one fix?
- A dirty read; use Read Uncommitted
- A phantom; add an index
- A deadlock; retry
- A lost update; use
UPDATE … SET stock = stock - 1 or SELECT … FOR UPDATE
Read Committed doesn't stop lost updates. An atomic UPDATE, a row lock, a version check or Serializable (with retries) does.
Someone ran a bad DELETE at 14:05. Which setup lets you get the data back as it was at 14:04?
- A base backup plus archived WAL (point-in-time recovery)
- An asynchronous read replica
- A synchronous standby
- Autovacuum
Replicas replay the DELETE almost at once. PITR replays the archived WAL up to a chosen moment.
A user updates their profile, the next page reads from an async replica and shows the old data. What is this?
- A serialization failure
- A dirty read
- Replication lag breaking read-your-own-writes
- A deadlock
Async replicas can lag behind. Read the user's own recent writes from the primary, or wait until the replica has caught up.
When does a key-value or document store fit better than PostgreSQL?
- Whenever data has relationships
- For a known set of key-based access patterns at very large scale, or as a cache
- When you need multi-table transactions and ad-hoc reporting
- Whenever the schema might change
NoSQL stores shine for predictable key lookups at scale and caching. Ad-hoc queries, joins and transactions are where relational databases are strongest, and jsonb covers changing fields.