Skip to the page

Querying · core

SELECT, WHERE, ORDER BY and how a query runs

A SELECT is written as SELECT ... FROM ... WHERE ... GROUP BY ... HAVING ... ORDER BY ... LIMIT, but it is logically evaluated as FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT, which explains why WHERE cannot use a SELECT alias but ORDER BY can.

The notes

What you must know

  • Logical order: FROM/JOIN -> WHERE (filter rows) -> GROUP BY -> HAVING (filter groups) -> SELECT (compute columns, aliases) -> DISTINCT -> ORDER BY -> LIMIT/OFFSET.
  • WHERE filters rows before grouping; it cannot use aggregates or (in standard SQL and Postgres) SELECT aliases. ORDER BY runs after SELECT, so it can use aliases.
  • Filters: =, <>, <, >, BETWEEN a AND b (inclusive), IN (...), LIKE 'abc%' (prefix, can use an index) vs LIKE '%abc' (cannot), ILIKE in Postgres for case-insensitive.
  • Without ORDER BY the row order is not guaranteed, even if it looks stable today. Add a unique tiebreaker for stable results (ORDER BY created_at DESC, id DESC).
  • LIMIT/OFFSET (FETCH FIRST n ROWS ONLY in standard SQL). Big offsets are slow; see keyset pagination.
  • SELECT only the columns you need: less I/O, and it allows index-only scans.
  • Always pass user input as parameters ($1 or ?), never by string concatenation (SQL injection).

The red pen

Common traps: mistake → fix

  • Mistake: SQL runs top to bottom as written

    Fix: the SELECT list is evaluated after WHERE, GROUP BY and HAVING.

  • Mistake: Rows come back in insertion order

    Fix: without ORDER BY the database may return any order.

  • Mistake: WHERE total > 100 works with an alias 'total' from SELECT

    Fix: use the expression or a subquery/CTE; ORDER BY total does work.

Easy to hard

Questions interviewers ask, easy to hard

  1. Write a query for the 10 newest paid orders over 500 rupees in Pune.
  2. In what order does the database logically process a SELECT?
  3. Why can't WHERE use a column alias, but ORDER BY can?
  4. Why is LIKE '%phone' slow?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview