Notes
All notes

SQL crash course: read and write relational data

SQL is a declarative language for relational databases: you describe the result you want, not the steps to compute it. This note covers the 20% you will use 80% of the time — filtering, joining, aggregating and shaping rows — using one small schema throughout.

The running example

Two tables, users and orders, where one user can place many orders:

\begin{tikzpicture}[
  t/.style={draw,thick,minimum width=2.7cm,minimum height=0.68cm,font=\small\ttfamily},
  h/.style={t,fill=black!12,font=\small\bfseries},
  a/.style={->,thick},
  l/.style={font=\scriptsize}
]
  \node[h] (uh) at (0,0) {users};
  \node[t] at (0,-0.68) {id};
  \node[t] at (0,-1.36) {name};
  \node[h] (oh) at (4.6,0) {orders};
  \node[t] at (4.6,-0.68) {id};
  \node[t] at (4.6,-1.36) {user\_id};
  \node[t] at (4.6,-2.04) {total};
  \draw[a] (1.35,-1.36) -- node[l,above]{1 : N} (3.25,-1.36);
\end{tikzpicture}
CREATE TABLE users (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);

CREATE TABLE orders (
  id      INTEGER PRIMARY KEY,
  user_id INTEGER NOT NULL REFERENCES users(id),
  total   NUMERIC NOT NULL
);

INSERT INTO users VALUES (1, 'Ada'), (2, 'Bob'), (3, 'Cy');
INSERT INTO orders VALUES
  (101, 1, 40), (102, 1, 60), (103, 2, 25);

Note that user 3 (Cy) has no orders — she will matter when we get to joins.

The shape of a query

Almost every read has the same skeleton, and — this is the part people get backwards — the database does not run it top to bottom. The logical order is FROM, then WHERE, then GROUP BY, HAVING, SELECT, ORDER BY, and finally LIMIT:

SELECT   name, COUNT(*) AS n_orders      -- 5. project + name the columns
FROM     users                            -- 1. start here
WHERE    id > 0                           -- 2. filter rows
GROUP BY name                             -- 3. bucket what survived
HAVING   COUNT(*) >= 1                    -- 4. filter buckets
ORDER BY n_orders DESC                    -- 6. sort
LIMIT    10;                              -- 7. cut

WHERE filters rows before grouping; HAVING filters groups after. Mixing those two up is the most common SQL bug there is.

Filtering, sorting, limiting

-- exact match, ranges, sets, patterns
SELECT * FROM users WHERE id = 2;
SELECT * FROM orders WHERE total BETWEEN 30 AND 70;
SELECT * FROM users WHERE name IN ('Ada', 'Cy');
SELECT * FROM users WHERE name LIKE 'A%';   -- starts with A
SELECT * FROM users WHERE name IS NOT NULL; -- never = NULL (NULL is unknown)

-- newest biggest orders first, top 5
SELECT * FROM orders ORDER BY total DESC LIMIT 5;

ORDER BY without LIMIT on a huge table sorts the whole result — fine for notes, expensive in production.

Aggregates and GROUP BY

Aggregate functions collapse rows: COUNT, SUM, AVG, MIN, MAX. GROUP BY collapses them per bucket instead of into one row:

SELECT user_id, COUNT(*) AS n_orders, SUM(total) AS revenue
FROM orders
GROUP BY user_id
ORDER BY revenue DESC;
user_id n_orders revenue
1 2 100
2 1 25

Every non-aggregated column in the SELECT list must appear in the GROUP BY — otherwise the database cannot know which row’s value to show. (HAVING COUNT(*) > 1 after this would keep only user 1.)

JOINs

A join glues rows from two tables on a condition, usually a foreign key. Think of the four variants as Venn diagrams over “users with orders” and “orders with users”:

\begin{tikzpicture}[
  c/.style={draw,thick},
  l/.style={font=\scriptsize\bfseries}
]
  % INNER: only the overlap
  \begin{scope}[shift={(0,0)}]
    \begin{scope}
      \clip (0,0) circle (0.72cm);
      \fill[green!35] (1.15,0) circle (0.72cm);
    \end{scope}
    \draw[c] (0,0) circle (0.72cm);
    \draw[c] (1.15,0) circle (0.72cm);
    \node[l] at (0.57,-1.15) {INNER};
  \end{scope}
  % LEFT: everything on the left
  \begin{scope}[shift={(3.1,0)}]
    \fill[blue!25] (0,0) circle (0.72cm);
    \draw[c] (0,0) circle (0.72cm);
    \draw[c] (1.15,0) circle (0.72cm);
    \node[l] at (0.57,-1.15) {LEFT};
  \end{scope}
  % RIGHT: everything on the right
  \begin{scope}[shift={(6.2,0)}]
    \fill[orange!30] (1.15,0) circle (0.72cm);
    \draw[c] (0,0) circle (0.72cm);
    \draw[c] (1.15,0) circle (0.72cm);
    \node[l] at (0.57,-1.15) {RIGHT};
  \end{scope}
  % FULL: everything
  \begin{scope}[shift={(9.3,0)}]
    \fill[purple!22] (0,0) circle (0.72cm);
    \fill[purple!22] (1.15,0) circle (0.72cm);
    \draw[c] (0,0) circle (0.72cm);
    \draw[c] (1.15,0) circle (0.72cm);
    \node[l] at (0.57,-1.15) {FULL};
  \end{scope}
\end{tikzpicture}
-- INNER: only users who placed orders (Cy disappears)
SELECT users.name, orders.total
FROM users
INNER JOIN orders ON orders.user_id = users.id;

-- LEFT: every user, with NULLs where Cy has no orders
SELECT users.name, orders.total
FROM users
LEFT JOIN orders ON orders.user_id = users.id;
name total (INNER) total (LEFT)
Ada 40 40
Ada 60 60
Bob 25 25
Cy — NULL

If you only remember one join, make it LEFT JOIN — “keep everything on my left, attach matches when they exist” covers most reporting queries.

Subqueries and CTEs

A subquery nests one query inside another; a CTE (WITH) names it so the outer query stays readable. Prefer CTEs — they read top to bottom:

WITH big_orders AS (
  SELECT user_id, SUM(total) AS revenue
  FROM orders
  GROUP BY user_id
  HAVING SUM(total) > 50
)
SELECT users.name, big_orders.revenue
FROM users
JOIN big_orders ON big_orders.user_id = users.id;
-- Ada | 100

Correlated subqueries (referencing the outer query) run once per row — elegant, but check the plan before using them on large tables.

Set ops, DISTINCT and NULLs

SELECT name FROM users
UNION            -- UNION ALL keeps duplicates, UNION drops them
SELECT name FROM admins;

SELECT DISTINCT user_id FROM orders;

-- NULL is not a value, so none of these match it:
-- = NULL, != NULL, IN (NULL). Use IS NULL / IS NOT NULL.
SELECT * FROM orders WHERE user_id IS NOT NULL;

UNION (not UNION ALL) silently sorts and deduplicates — on big inputs that sort can dominate the query time.

Indexes in one paragraph

An index is a sorted copy of a column (usually a B-tree) that turns full scans into lookups. Index the columns you filter and join on (WHERE user_id, JOIN ... ON user_id); do not index everything, because each index slows writes and costs space. EXPLAIN (Postgres) or EXPLAIN QUERY PLAN (SQLite) shows whether yours is actually used.

QQuestionWhen does WHERE run relative to GROUP BY, and why does it matter?
ASolution

WHERE runs before grouping, so it cannot see aggregates — WHERE COUNT(*) > 1 is an error. Filter rows with WHERE, filter groups with HAVING. If a query is slow, check whether a filter that could have run in WHERE was pushed into HAVING instead.

Common pitfalls