Lesson 2 of 29Querying basics
SELECT, WHERE and ORDER BY
Choose columns, filter rows, sort and page results, and learn the logical order SQL runs in, which explains half the errors you will hit.
A support lead messages you: "Can you pull every paid or shipped order for Ada since March, newest first?" You will get requests like this every week, from support, finance, product and your own debugging. Most of them are one SELECT with a WHERE and an ORDER BY, and most of the wrong answers come from three small traps: AND binding tighter than OR, BETWEEN missing the last day, and results that come back in a different order next time. This lesson covers the clauses you will write most often, and the order in which SQL actually evaluates them, which explains a surprising number of error messages.
Choosing columns and computing expressions
SELECT lists what each result row contains. That can be plain columns, but also any expression: arithmetic, function calls, string building. AS gives a result column a name, called an alias.
Press Run (⌘ Enter) to see what happens.Two details from that block catch people out. Dividing two integers gives an integer in both Postgres and SQLite, so 7 / 2 is 3. Divide by 100.0, or cast one side, when you want a fraction. MySQL is the odd one out: its / always returns a decimal.
At work, avoid SELECT * in application code. It returns every column, including the large ones you did not need, and it changes shape when someone adds a column, which can break code that reads columns by position. List the columns you use. SELECT * is fine when you are exploring a table by hand.
Filtering rows with WHERE
WHERE keeps the rows for which a condition is true. You combine conditions with AND, OR and NOT, using the usual comparisons: =, <> (or !=), <, <=, >, >=.
The trap is precedence. AND binds tighter than OR, just as multiplication binds tighter than addition. Here is the support lead's request, written naively and then correctly:
Press Run (⌘ Enter) to see what happens.The first query reads as status = 'paid' OR (status = 'shipped' AND customer_id = 1), so it returns every paid order for anyone, plus Ada's shipped ones. Nothing errors and the result looks plausible, which is what makes it dangerous. The rule seniors follow: whenever a WHERE mixes AND and OR, add parentheses, even if you are sure of the precedence. The next reader is not.
How many rows does this return on the shop data?
SELECT id FROM orders WHERE customer_id = 2 OR customer_id = 5 AND status = 'pending'
IN, BETWEEN and the end-date trap
IN tests membership in a list and replaces a chain of ORs: status IN ('paid', 'shipped') is shorter and cannot suffer from the precedence bug. BETWEEN a AND b means >= a AND <= b. It is inclusive at both ends, and that causes one of the most common reporting bugs in SQL.
The events table stores times, such as '2025-06-02 08:30'. Suppose you want every event on 1 and 2 June:
Press Run (⌘ Enter) to see what happens.The BETWEEN version silently drops everything on 2 June. The upper bound '2025-06-02' means midnight at the start of that day, and '2025-06-02 08:30' is later than that. Postgres behaves the same way with real timestamptz columns, because the date literal is converted to midnight. Daily revenue reports built with BETWEEN are quietly missing the last day's sales until someone notices the totals do not match finance's.
The fix is a half-open range: >= the start, < the day after the end. It works for dates, timestamps with any precision and numbers, it never double-counts a row that sits exactly on a boundary between two periods, and it can still use an index on the column. Use it for every time range.
Pattern matching with LIKE
LIKE matches text against a pattern. % matches any run of characters (including none), and _ matches exactly one character.
Press Run (⌘ Enter) to see what happens.The first query matched Laptop Pro 14 even though the pattern is lower case. That is SQLite, and it is not what Postgres does.
Two performance facts are worth knowing early. A pattern with a fixed prefix, such as 'Lap%', can use a suitable index. A leading wildcard, such as '%top', cannot, so it scans every row. If users search inside text, you want full-text search, which a later lesson covers, not LIKE '%term%' on a large table. To match a literal % or _, escape it: LIKE '%10\%%' ESCAPE '\'.
WHERE name LIKE 'laptop%' returns no rows. What is the best fix?DISTINCT, ORDER BY and LIMIT
DISTINCT removes duplicate result rows. It applies to the whole row you select, not to the first column. SELECT DISTINCT city, name gives distinct pairs, which here is every customer.
ORDER BY sorts the result. You can sort by several keys, each with ASC (the default) or DESC, and by an alias from the SELECT list. LIMIT n keeps the first n rows and OFFSET m skips m rows first.
Press Run (⌘ Enter) to see what happens.Notice the NULL city sorted first. SQLite and MySQL put NULLs first in ascending order, and Postgres puts them last, which the next lesson, NULL and three-valued logic, deals with properly.
Three rules keep sorted results correct:
- No
ORDER BYmeans no order. The database returns rows in whatever order is cheapest. It often looks stable in development and then changes in production after a new index, a parallel plan or a table rewrite. If the order matters, say so. - Make the order total. If two rows can tie on the sort key, add a unique tiebreaker, usually the primary key:
ORDER BY created_at DESC, id DESC. Without it,LIMITandOFFSETcan show the same row on two pages and skip another entirely. OFFSETgets slower as it grows.OFFSET 100000still reads and throws away 100,000 rows. Deep pagination on big tables uses keyset pagination instead (WHERE (created_at, id) < (?, ?)), covered in Query Patterns That Scale.
LIMIT is not in the SQL standard. The standard spelling is FETCH FIRST n ROWS ONLY, which Postgres, SQL Server and Oracle accept. SQLite and MySQL only accept LIMIT:
-- Postgres: both of these work
SELECT name FROM products ORDER BY price_cents DESC LIMIT 3;
SELECT name FROM products ORDER BY price_cents DESC OFFSET 0 ROWS FETCH FIRST 3 ROWS ONLY;CASE: derived columns and custom sort orders
CASE is SQL's if/else, and it is an expression, so it can go anywhere a value can: in SELECT, in WHERE and in ORDER BY.
Press Run (⌘ Enter) to see what happens.The searched form, CASE WHEN condition THEN ..., is the general one. The simple form, CASE status WHEN 'pending' THEN ..., compares one value for equality. Branches are tried top to bottom and the first match wins, so put specific conditions before general ones. Without an ELSE, unmatched rows get NULL, which is a common source of blank cells in reports.
The ORDER BY CASE trick sorts by business meaning instead of alphabetically. Alphabetical order would put cancelled first and shipped before pending, which is useless for an operations screen.
The order SQL actually runs in
You write a query in this order: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT. The database evaluates it, logically, in a different order. The planner may physically do things in another order again, but the result is always as if it followed this sequence:
First the database works out where rows come from: one table, or several joined together. Everything later sees this combined set of rows.
This one diagram answers a family of questions. Why can ORDER BY use an alias when WHERE cannot? Because of where each sits in the order. Why can you not filter on an aggregate in WHERE? Because grouping has not happened yet, which is what HAVING is for. Why does LIMIT 10 without ORDER BY return different rows on different days? Because there was no sort to slice.
Press Run (⌘ Enter) to see what happens.Put these clauses in the order the database logically evaluates them.
- Tap the steps below in the right order.
Building strings
Postgres and SQLite join strings with ||, the SQL standard operator:
Press Run (⌘ Enter) to see what happens.Katherine Johnson has no email, and her whole contact came out NULL: any || with a NULL gives NULL. The next lesson explains why and how to fix it with COALESCE.
The dialects differ here more than anywhere else in basic SQL. MySQL treats || as logical OR by default and uses CONCAT(a, b, ...). Postgres also has concat(), which treats NULL as an empty string. The SQLite version that runs these examples (3.39) has no concat() at all, as it only arrived in a later release. If you write SQL that must run on several engines, this is where it breaks first.
How many rows does this return?
SELECT id FROM events WHERE kind = 'login' AND created_at BETWEEN '2025-06-02' AND '2025-06-04'
- alias
- A name given to a result column or table with AS, such as price_cents / 100.0 AS price.
- predicate
- A condition that is true or false for a row, such as status = 'paid', used in WHERE.
- half-open range
- A range written as >= start AND < end, which includes the start and excludes the end. The safe way to filter times.
- DISTINCT
- Removes duplicate rows from the result, comparing every selected column.
- CASE expression
- SQL's if/else. Returns the value of the first branch whose condition is true, or ELSE, or NULL.
- logical processing order
- The order SQL clauses are evaluated: FROM, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY, LIMIT.
- total order
- A sort with a unique tiebreaker, such as the primary key, so rows always come back in the same order.