SQL

Runnable SQL on PostgreSQL 17: step-through animations of clause order, NULLs, joins, windows and isolation, real-output workflows for query life, replication and migrations, and 16 checked problems from top-N to query plans.

Overview

This page is a quick reference you can run. The tables hold the rules, the step-through labs show what PostgreSQL does with each row, and the green labs run real PostgreSQL 17 in your browser with a Check button. Every sql block on the page runs on PostgreSQL 17 against the sample tables below; MySQL and SQL Server versions sit in their own tabs, marked with their dialect.

Most SQL bugs do not raise an error. The query runs and the number is wrong. Three rules explain nearly all of them.

  • NULL means unknown — x = NULL and NOT IN with a NULL silently drop rows — NULL and three-valued logic
  • Clauses run in a fixed logical order, not the written order — aliases missing in WHERE, a LEFT JOIN turned into an inner join — Clause order
  • A join emits one row per matching pair — COUNT and SUM inflate after a one-to-many join — Joins
  • Step-through animations (computed from your input, checked against PostgreSQL) — 15
  • Workflow diagrams with real commands and outputs — 4
  • Problems with Check and a worked solution — 16
  • Try-it labs — 4
  • Syntax cards — 26

The sample tables

The four tables below are tiny on purpose. Fay has no department, Legal has no staff, Ben and Cai tie on salary, and order 6 has no employee. Those gaps are what make the traps show up.

  • departments — 3 — Legal has no employees
  • employees — 7 — Fay has no dept_id; Ana has no manager; Ben and Cai both earn 120000; Dee earns more than her manager Dan
  • orders — 6 — order 6 has no employee_id
  • logins — 6 — user 1 logs in three days in a row, then skips a day

The PostgreSQL labs use three larger datasets of their own; the table chips above each editor list their columns.

  • hr — departments, employees (9 people, a manager tree, a NULL department, tied salaries) — ranking, recursive CTEs, NULL rules
  • shop — customers, products, orders, order_items, events, app_activity, daily_revenue, customer_imports, inventory — joins, analytics, time series, upserts
  • traffic — page_views: 50,000 generated rows — real query plans, indexes, pagination

Sign up free to read the full topic

More Quick References topics

Start free on Cariara · Coding problems · System design studio