Learn SQL

The standard language for querying and managing relational databases

40 lessons · 8 hours · 4 levels · covers SQL SQL:2023 / PostgreSQL 17+

SQL is the declarative language used to define, query and change data in relational databases such as PostgreSQL, MySQL, SQL Server, Oracle and SQLite. It is how backends, analysts and data tools talk to stored data, and it has outlived every trend for fifty years. This curriculum uses PostgreSQL as the reference dialect and notes where others differ.

How deep do you want to go?

1. EssentialsRead and write simple code, do the everyday basics12 lessons · 2 hours in total
2. PracticalUse it productively at work, with the usual idioms24 lessons · 4 hours in total
3. AdvancedThe less common features, performance and trade-offs33 lessons · 6 hours in total
4. ExpertInternals and the edge cases experts know40 lessons · 8 hours in total

The SQL tree

SQLTables, rows and the relational modelTables, rows and therelational modelSELECT: reading dataSELECT: reading dataExpressions, aliases and DISTINCTExpressions, aliasesand DISTINCTFiltering rows with WHEREFiltering rows withWHEREIN, BETWEEN and LIKEIN, BETWEEN andLIKENULL and three-valued logicNULL andthree-valued logicSorting and limiting resultsSorting and limitingresultsAggregate functionsAggregate functionsGROUP BY and HAVINGGROUP BY andHAVINGCreating and altering tablesCreating and alteringtablesChoosing data typesChoosing data typesINSERT, UPDATE and DELETEINSERT, UPDATE andDELETEPrimary keys and identity columnsPrimary keys andidentity columnsForeign keys and referential integrityForeign keys andreferential integrityNOT NULL, UNIQUE, CHECK and DEFAULTNOT NULL, UNIQUE,CHECK and DEFAULTInner joinsInner joinsOuter joins: LEFT, RIGHT and FULLOuter joins: LEFT,RIGHT and FULLSubqueries and EXISTSSubqueries andEXISTSCASE, COALESCE and NULLIFCASE, COALESCEand NULLIFString functionsString functionsDates, times and intervalsDates, times andintervalsViews and materialized viewsViews andmaterialized viewsIndex basicsIndex basicsTransactions and ACIDTransactions andACID
Essentials and Practical shown (24 of 40 lessons); the full list is below. Click a lesson to read it.

All 40 lessons, in order

Querying basics

  1. Tables, rows and the relational model · Essentials · 8 min

    Relational databases store data as tables of typed columns and rows, linked by matching values rather than pointers.

  2. SELECT: reading data · Essentials · 8 min

    Read columns from a table with SELECT ... FROM, choosing exactly which columns you need.

  3. Expressions, aliases and DISTINCT · Essentials · 9 min

    Compute new columns with expressions, rename them with AS, and remove duplicate rows with DISTINCT.

  4. Filtering rows with WHERE · Essentials · 9 min

    Keep only the rows that satisfy a condition, combining comparisons with AND, OR and NOT.

  5. IN, BETWEEN and LIKE · Essentials · 8 min

    Match against lists, ranges and text patterns with IN, BETWEEN and LIKE.

  6. NULL and three-valued logic · Essentials · 10 min

    NULL means unknown; comparisons with it are neither true nor false, so you test it with IS NULL.

  7. Sorting and limiting results · Essentials · 8 min

    Sort results with ORDER BY, and return only the first rows with LIMIT / FETCH FIRST.

Aggregation and analytics

  1. Aggregate functions · Essentials · 9 min

    Collapse many rows into one value with COUNT, SUM, AVG, MIN and MAX, and know how they treat NULL.

  2. GROUP BY and HAVING · Essentials · 12 min

    Aggregate per group with GROUP BY, and filter whole groups with HAVING.

  3. Window functions · Advanced · 15 min

    Compute rankings, running totals and row-to-row comparisons with OVER, without collapsing rows.

Tables and changing data

  1. Creating and altering tables · Essentials · 10 min

    Define tables with CREATE TABLE, and change or remove them with ALTER TABLE and DROP TABLE.

  2. Choosing data types · Essentials · 10 min

    Pick the right type for numbers, money, text, booleans, dates and ids, and avoid the classic mistakes.

  3. INSERT, UPDATE and DELETE · Essentials · 12 min

    Add rows with INSERT, change them with UPDATE, remove them with DELETE, and see the affected rows with RETURNING.

  4. Upserts: ON CONFLICT and MERGE · Advanced · 11 min

    Insert a row or update it if it already exists, atomically, with INSERT ... ON CONFLICT or MERGE.

Keys and schema design

  1. Primary keys and identity columns · Practical · 10 min

    Identify every row with a primary key, usually a database-generated identity column or UUID.

  2. Foreign keys and referential integrity · Practical · 10 min

    Use foreign keys so the database guarantees that every reference points at a row that exists.

  3. NOT NULL, UNIQUE, CHECK and DEFAULT · Practical · 10 min

    Encode business rules in the schema with NOT NULL, UNIQUE, CHECK and DEFAULT constraints.

  4. Normalization and schema design · Advanced · 14 min

    Design tables so each fact is stored once, and know when deliberate denormalization is worth it.

Joins, subqueries and CTEs

  1. Inner joins · Practical · 12 min

    Combine rows from several tables by matching key values with JOIN ... ON.

  2. Outer joins: LEFT, RIGHT and FULL · Practical · 12 min

    Keep rows without a match using LEFT, RIGHT and FULL joins, and find unmatched rows.

  3. Subqueries and EXISTS · Practical · 12 min

    Nest one query inside another as a value, a list, a derived table, or an EXISTS test.

  4. Views and materialized views · Practical · 9 min

    Save a query under a name with CREATE VIEW, or store its result with a materialized view.

  5. Common table expressions (WITH) · Advanced · 11 min

    Break a complex query into named steps with WITH, and know when PostgreSQL inlines or materialises them.

  6. Recursive CTEs and hierarchies · Advanced · 13 min

    Walk trees and graphs such as category hierarchies with WITH RECURSIVE.

  7. UNION, INTERSECT and EXCEPT · Advanced · 8 min

    Combine the results of whole queries by stacking, intersecting or subtracting their rows.

Expressions and data functions

  1. CASE, COALESCE and NULLIF · Practical · 9 min

    Write conditional logic inside queries with CASE, and handle NULLs with COALESCE and NULLIF.

  2. String functions · Practical · 9 min

    Clean, search, split and assemble text with SQL's string functions and pattern matching.

  3. Dates, times and intervals · Practical · 11 min

    Do date arithmetic, truncate and extract parts of timestamps, and handle time zones correctly.

  4. JSON columns with jsonb · Advanced · 13 min

    Store, query and index semi-structured data in PostgreSQL jsonb columns, and know when not to.

Indexes and performance

  1. Index basics · Practical · 12 min

    Speed up lookups, joins and sorts with B-tree indexes, and understand what they cost.

  2. Reading query plans with EXPLAIN · Advanced · 15 min

    Use EXPLAIN and EXPLAIN ANALYZE to see how PostgreSQL executes a query and where the time goes.

  3. Advanced indexing · Advanced · 15 min

    Use partial, expression, covering and multicolumn indexes, and pick GIN, GiST or BRIN when B-tree is not enough.

  4. The query planner and statistics · Expert · 16 min

    How PostgreSQL's cost-based planner estimates row counts from statistics and chooses join methods and order.

  5. Table partitioning · Expert · 14 min

    Split very large tables into partitions by range, list or hash, and use pruning and detach for speed and data lifecycle.

  6. Performance tuning in practice · Expert · 18 min

    A method for finding and fixing slow database workloads: measure, read plans, fix queries, then tune the server.

Transactions and internals

  1. Transactions and ACID · Practical · 11 min

    Group statements with BEGIN, COMMIT and ROLLBACK so they succeed or fail as a unit.

  2. MVCC, row versions and VACUUM · Expert · 15 min

    How PostgreSQL keeps multiple row versions so readers never block writers, and why VACUUM must clean them up.

  3. Isolation levels and anomalies · Expert · 16 min

    What READ COMMITTED, REPEATABLE READ and SERIALIZABLE guarantee in PostgreSQL, and which anomalies each allows.

  4. Locks, SKIP LOCKED and deadlocks · Expert · 15 min

    Row and table locks in PostgreSQL, explicit locking with FOR UPDATE, queue patterns, and how deadlocks arise.

  5. Write-ahead log, backups and replication · Expert · 16 min

    How the write-ahead log makes commits durable, and how it powers crash recovery, point-in-time recovery and replicas.