Reading rows: SELECT, WHERE and ORDER BY
A query has a few parts, and you’ll write them in this order:
SELECT name, price -- which columns
FROM products -- from which table
WHERE price < 20 -- which rows
ORDER BY price DESC -- sorted how (DESC = biggest first)
LIMIT 10; -- how manyThe conditions you can put in WHERE:
| Condition | Meaning |
|---|---|
price = 10, price <> 10 | equal, not equal (!= works too) |
price < 10, price >= 10 | comparisons |
price BETWEEN 10 AND 20 | 10 to 20, both included |
country IN ('RS', 'HR', 'BA') | one of a list |
name LIKE 'Ana%' | a pattern: % is any text, _ is one character |
a AND b, a OR b, NOT a | combine conditions |
Text goes in single quotes: 'Ana'. Double quotes are for names of tables and columns, which you rarely need.
You can compute values and name them with AS:
SELECT name, price * 1.2 AS price_with_tax FROM products;One rule surprises everyone. SQL doesn’t run in the order you write it. It runs like this:
FROM: take the table.WHERE: keep the matching rows.SELECT: compute the columns, including names likeprice_with_tax.ORDER BY: sort.LIMIT: cut.
So WHERE can’t use a name created in SELECT: it doesn’t exist yet. ORDER BY can, because it runs later.
The logical processing order answers most “why doesn’t this work” questions: FROM/JOIN → WHERE → GROUP BY → HAVING → SELECT (including window functions) → DISTINCT → ORDER BY → LIMIT/OFFSET. Aliases are visible only after SELECT; PostgreSQL also accepts them in GROUP BY, MySQL in HAVING, but WHERE never. The planner may physically reorder anything, as long as results match this logical order.
Details that come up in reviews and interviews:
- Precedence.
NOT>AND>OR. Parenthesize every mixed condition. SELECT *in application code breaks when columns are added, sends unused data, and prevents index-only scans. Name the columns.- Patterns.
LIKE 'abc%'can use a B-tree index (with the C collation or atext_pattern_opsindex);LIKE '%abc'can’t. Use a trigram index (pg_trgm) or full-text search for “contains”.ILIKEis PostgreSQL-only; MySQL’s default collations are already case-insensitive. - Determinism.
LIMITwithoutORDER BYreturns arbitrary rows, andORDER BY created_atwith ties returns ties in any order. Add a unique tiebreaker:ORDER BY created_at DESC, id DESC. - Paging.
OFFSET 100000still reads and throws away 100,000 rows; use keyset paginationKeyset paginationPaging by continuing after the last row's sort key instead of skipping a number of rows with OFFSET.Open in glossary → for deep pages (see Database performance). - Standard vs dialect.
LIMITis PostgreSQL, MySQL and SQLite; the standard isFETCH FIRST 10 ROWS ONLY(PostgreSQL, Oracle, SQL Server 2012+ withOFFSET).
Predict the output
Which orders does this query return?
SELECT id, status, total
FROM orders
WHERE status = 'PAID' OR status = 'SHIPPED' AND total > 100;AND binds tighter than OR, so the database reads it as status = 'PAID' OR (status = 'SHIPPED' AND total > 100). A paid order of 5 dollars comes back too. Write the parentheses you mean: (status = 'PAID' OR status = 'SHIPPED') AND total > 100, or status IN ('PAID', 'SHIPPED') AND total > 100.
-- the 20 cheapest active products, cheapest first
SELECT id, name, price
FROM products
WHERE is_active AND price > 0
ORDER BY price, id
LIMIT 20;
-- customers from three countries who signed up this year
SELECT id, name, email
FROM customers
WHERE country IN ('RS', 'HR', 'BA')
AND created_at >= date '2026-01-01'
ORDER BY created_at DESC;
-- products whose name starts with "Mug"
SELECT id, name FROM products WHERE name LIKE 'Mug%';The column that doesn’t exist yet
Tap the line with the bug.
SELECT order_id,
product_id,
quantity * unit_price AS line_total
FROM order_items
WHERE line_total > 100
ORDER BY line_total DESC;Hint: Go back to the order SQL runs in. Has SELECT run when WHERE checks its condition?
PostgreSQL answers ERROR: column "line_total" does not exist. WHERE runs before SELECT, so the name line_total hasn’t been created yet when the condition is checked. ORDER BY line_total on the next line is fine, because sorting happens after SELECT.
Repeat the expression in WHERE:
SELECT order_id, product_id, quantity * unit_price AS line_total
FROM order_items
WHERE quantity * unit_price > 100
ORDER BY line_total DESC;The database computes it only once per row, so repeating it costs nothing. For long expressions, a subquery or a WITH clause (the CTE lesson) lets you name it once.
Deep diveSQL injection, and the part parameters can't protectInterview favorite
Building SQL by joining strings lets user input become code:
// search?q=x' OR '1'='1
val sql = "SELECT * FROM products WHERE name = '" + q + "'"The fix is parameters (prepared statements): the SQL text and the values travel separately, so a value can never change the statement’s structure. WHERE name = ? with JdbcTemplate, :name in JPA, $1 in node-postgres, ? in Room’s @Query and in SQLite’s bind. ORMs parameterize for you unless you concatenate into a native query.
The interview follow-up: parameters only replace values. Table names, column names, ASC/DESC and LIMIT in some drivers can’t be bound. A ?sort=price query parameter must go through an allowlist:
var column = Map.of("price", "price", "newest", "created_at").get(sort);
if (column == null) throw new BadRequestException("sort");
var sql = "SELECT id, name FROM products ORDER BY " + column + ", id LIMIT ?";Defense in depth: the app’s database user has only the privileges it needs (no DROP, no access to other schemas), and errors don’t echo SQL back to the client.
- Logical order:
FROM→WHERE→GROUP BY→HAVING→SELECT→DISTINCT→ORDER BY→LIMIT. NoSELECTaliases inWHERE. ANDbeforeOR: parenthesize. Name columns instead ofSELECT *.LIKE 'x%'can use an index,'%x'can’t (trigram, full-text).LIMITneedsORDER BYwith a unique tiebreaker; deep pages need keyset.- Values through parameters; identifiers through an allowlist.
SELECT id, name, price
FROM products
WHERE (name LIKE 'Mug%' OR name LIKE 'Cup%') AND price < $1
ORDER BY price, id
LIMIT 20;Check this part
Which runs first?
What does name LIKE 'Ana%' match?
A paginated endpoint uses ORDER BY created_at LIMIT 20 OFFSET 40. Users see some rows twice and miss others. Why?
How do you safely let users choose the sort column?