Skip to content
Engineering Bible
SQL and Databases

SQL and Databases on queries

SELECT asks a question about a table

  • SELECT picks the columns, FROM picks the table, WHERE keeps the rows that match.
  • Without ORDER BY, rows come back in whatever order is fastest. Never rely on it.
  • LIMIT 10 returns at most 10 rows. Pair it with ORDER BY, or which 10 is random.

A join matches rows across tables

  • JOIN orders ON orders.user_id = users.id pairs each user with their orders.
  • INNER JOIN keeps only pairs that match. A user with no orders disappears.
  • LEFT JOIN keeps every user. Users with no orders get NULL in the order columns.
A JOIN BRows you get back
INNER JOINOnly pairs that match
LEFT JOINEvery A row, NULLs where no B matches
RIGHT JOINEvery B row, NULLs where no A matches
FULL JOINEvery row from both, NULLs in the gaps
CROSS JOINEvery A row paired with every B row
With 3 users and 4 orders, a CROSS JOIN returns 12 rows.

GROUP BY folds rows into one row per group

  • Aggregates like count, sum and avg turn many rows into one value.
  • GROUP BY u.id gives one result row per user.
  • WHERE filters rows before grouping. HAVING filters the groups after.
SELECT u.email, count(*) AS order_count,
       sum(o.total) AS spent
FROM users u
JOIN orders o ON o.user_id = u.id
WHERE o.created_at >= now() - interval '30 days'
GROUP BY u.id
HAVING sum(o.total) > 100
ORDER BY spent DESC
LIMIT 10;
The 10 users who spent the most in the last 30 days, among those who spent over 100.

A query runs in a different order than it reads

  • The logical order is FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT.
  • So WHERE cannot use sum(total). The groups do not exist yet. That is HAVING's job.
  • In a LEFT JOIN, a WHERE test on an order column throws away users with no orders.
  • Put that test in ON instead to keep them.

INSERT, UPDATE and DELETE change rows

  • INSERT adds rows. Add RETURNING id to get the new key back in the same statement.
  • UPDATE and DELETE hit every row that matches WHERE. With no WHERE, that is every row.
  • ON CONFLICT (email) DO UPDATE turns a duplicate insert into an update: an upsert.

Parameters stop SQL injection

  • Never glue user input into a SQL string. Input like ' OR '1'='1 becomes part of the query.
  • Write placeholders, WHERE email = $1, and pass the values separately.
  • The database treats those values as data only, never as SQL.
  • Placeholders cannot stand for table or column names. Pick those from a fixed list.
SQL and Databases in seven pages2 / 7