Chapter 5 — Key Takeaways
The big idea
SELECT … FROM … WHERE … ORDER BY … LIMIT is the workhorse of SQL. FROM is the source relation, the SELECT list is projection (π), WHERE is selection (σ). Drill these until they're automatic — every chapter in Part II builds on them.
The shape
SELECT columns / expressions / aliases -- π : WHAT
FROM table -- the relation
WHERE condition -- σ : WHICH rows
ORDER BY columns [ASC|DESC] [NULLS FIRST|LAST]
LIMIT n [OFFSET m];
Logical order of evaluation (memorize)
FROM → WHERE → SELECT → ORDER BY → LIMIT
WHEREruns before theSELECTlist → it can't useSELECT-list aliases (repeat the expression).ORDER BYruns after → it can use aliases.
WHERE toolkit
- Comparisons:
=,<>/!=,<,>,<=,>=. - Combine with
AND/OR/NOT—ANDbinds tighter thanOR; always parenthesize when mixing. (Case Study 1.) BETWEEN a AND b(inclusive both ends).IN (list)for "one of these" (cleaner than chainedOR); bewareNULLinNOT IN.LIKE(%= any chars,_= one char);ILIKEfor case-insensitive (PostgreSQL).IS NULL/IS NOT NULL— never= NULL.
Projection extras
- Compute expressions (
price * 1.08), concatenate (first_name || ' ' || last_name), rename withAS. - Name columns in code; reserve
SELECT *for interactive exploration —*leaks new columns and couples output to table shape. (Case Study 2.)
Ordering & slicing
- Rows have no inherent order — use
ORDER BYto impose one. DISTINCTdedupes the whole selected row (not just column 1); it isn't free.LIMITneeds a deterministicORDER BY. For pagination, end the sort with a unique column (the PK) or pages overlap and drop rows. (Case Study 2.)
Performance seed (theme #5)
The WHERE clause is where speed is won or lost: a filter can trigger a full scan or use an index — the 45 s vs. 12 ms difference. Detail in Chapters 23–24; for now, write correct queries and know how you filter will later matter.
You can now…
- ☐ Write fluent
SELECT/FROM/WHERE/ORDER BY/LIMITqueries. - ☐ Project, compute, and alias columns.
- ☐ Filter with all the operators, parenthesizing mixed
AND/OR. - ☐ Explain the evaluation order and alias visibility.
- ☐ Use
DISTINCT,ORDER BY(with null placement), and safe pagination. - ☐ Sanity-check result counts to catch silent logic bugs.
Looking ahead
Chapter 6 — JOINs. The single most important SQL skill. You'll connect Mercado's tables — INNER, LEFT, RIGHT, FULL, CROSS, and self-joins — building from a two-table join to a six-table business query (the book's JOIN-progression anchor).
One sentence to carry forward: A correct query isn't one that runs — it's one that answers the question you actually meant; parentheses,
IS NULL, and a deterministicORDER BYare how you make sure it does.