Skip to content

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.

17 min read0/4 questions

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.

Python
from shopdb import connect, showdb = connect()show(db, """SELECT name, price_cents / 100.0 AS price, stock, price_cents * stock / 100.0 AS stock_valueFROM productsORDER BY stock_value DESCLIMIT 5""")show(db, "SELECT 7 / 2 AS int_division, 7 / 2.0 AS real_division")
Output
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:

Python
from shopdb import connect, showdb = connect()print("Without parentheses:")show(db, """SELECT id, status, customer_id FROM ordersWHERE status = 'paid' OR status = 'shipped' AND customer_id = 1""")print("With parentheses:")show(db, """SELECT id, status, customer_id FROM ordersWHERE (status = 'paid' OR status = 'shipped') AND customer_id = 1""")
Output
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.

Predict the outputSQL

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'
Need a nudge? Hints walk you through it.

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:

Python
from shopdb import connect, showdb = connect()print("BETWEEN with dates:")show(db, """SELECT id, user_id, created_at FROM eventsWHERE created_at BETWEEN '2025-06-01' AND '2025-06-02'""")print("Half-open range:")show(db, """SELECT id, user_id, created_at FROM eventsWHERE created_at >= '2025-06-01' AND created_at < '2025-06-03'""")
Output
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.

Python
from shopdb import connect, showdb = connect()show(db, "SELECT name FROM products WHERE name LIKE 'laptop%'")show(db, "SELECT name FROM products WHERE name LIKE '%-%'")show(db, "SELECT email FROM customers WHERE email LIKE '___@%'")
Output
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 '\'.

Quick check
Your tests run on SQLite and pass. In production on Postgres, a search for WHERE name LIKE 'laptop%' returns no rows. What is the best fix?
Need a nudge? A hint rules out a wrong answer.

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.

Python
from shopdb import connect, showdb = connect()show(db, "SELECT DISTINCT city FROM customers ORDER BY city")show(db, """SELECT name, price_cents FROM productsORDER BY price_cents DESC, nameLIMIT 3 OFFSET 2""")
Output
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 BY means 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, LIMIT and OFFSET can show the same row on two pages and skip another entirely.
  • OFFSET gets slower as it grows. OFFSET 100000 still 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.

Python
from shopdb import connect, showdb = connect()show(db, """SELECT id, status, CASE WHEN status IN ('paid', 'shipped') THEN 'revenue' WHEN status = 'pending' THEN 'waiting' ELSE 'lost' END AS bucketFROM ordersORDER BY CASE status WHEN 'pending' THEN 1 WHEN 'paid' THEN 2 WHEN 'shipped' THEN 3 ELSE 4 END, id""")
Output
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:

Logical processing order of a SELECT
  1. FROM / JOINpick the tables and combine them
  2. WHEREkeep rows that pass the condition
  3. GROUP BYcollapse rows into groups
  4. HAVINGkeep groups that pass
  5. SELECTcompute expressions, assign aliases
  6. DISTINCTremove duplicate result rows
  7. ORDER BYsort the result
  8. LIMIT / OFFSETkeep a slice

First the database works out where rows come from: one table, or several joined together. Everything later sees this combined set of rows.

1/6

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.

Python
from shopdb import connect, showdb = connect()# Works in SQLite, fails in Postgres: column "price" does not existshow(db, "SELECT name, price_cents / 100.0 AS price FROM products WHERE price >= 300")# Portable: repeat the expression, or filter on the stored columnshow(db, "SELECT name, price_cents / 100.0 AS price FROM products WHERE price_cents >= 30000")
Output
Press Run (⌘ Enter) to see what happens.
Put it in order7 steps

Put these clauses in the order the database logically evaluates them.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Building strings

Postgres and SQLite join strings with ||, the SQL standard operator:

Python
from shopdb import connect, showdb = connect()show(db, """SELECT name || ' <' || email || '>' AS contactFROM customersWHERE id <= 4ORDER BY id""")
Output
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.

Predict the outputSQL

How many rows does this return?

SELECT id FROM events
WHERE kind = 'login'
AND created_at BETWEEN '2025-06-02' AND '2025-06-04'
Need a nudge? Hints walk you through it.
Key terms
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.