Skip to content
Bronze 7 min read · Basics 3 practice problems ↓

SELECT, WHERE and ORDER BY

A table can hold millions of rows and dozens of columns, and you almost never want all of them. SELECT picks the columns, WHERE picks the rows, ORDER BY and LIMIT pick the top few. This lesson starts there, then shows the order SQL really runs a query in, which explains most beginner errors.

Foundations · SQL for data engineers · Bronze · Reading a table, lesson 1 of 3

In plain words first

Think of a table as a big spreadsheet of food orders. A query is a set of instructions to someone holding it:

FROM

"Take the orders sheet."

WHERE

"Cross out every row that is not from Pune."

SELECT

"Copy only the restaurant and amount columns."

ORDER BY and LIMIT

"Sort by amount, biggest first, and keep the top 3."

Those instructions always run in that order, whatever order you write them in. Keep the picture in mind; the rest of the lesson fills in the details.

The shape of a query

Almost every query you write has the same skeleton. You read it top to bottom, but SQL runs it in a different order, and that order explains most beginner errors:

  1. 1 · FROM

    Which table

  2. 2 · WHERE

    Which rows

  3. 3 · SELECT

    Which columns

  4. 4 · ORDER BY

    In what order

  5. 5 · LIMIT

    How many

GROUP BY and HAVING run between WHERE and SELECT; they get their own lesson. The sample table below is the orders table of a small food delivery app. Notice order 103 has no amount and order 104 has no status: real tables always have rows like these.

SELECT: choose and compute columns

SELECT lists the columns you want back. Each item can be a column, or an expression computed from columns, renamed with AS.

Spark SQL · Pick columns and compute one

Input: orders

order_idcustomer_idrestaurantcityamountstatusplaced_at
1011Spice RoutePune420delivered2026-03-01 12:10:00
1022Pizza LabDelhi650cancelled2026-03-01 19:40:00
1031Pizza LabPunenullNULL: A missing or unknown value. It is not 0 or an empty string, and any comparison with it is unknown instead of true or false. Learn more →delivered2026-03-02 13:05:00
1043Spice RoutePune310null2026-03-03 20:15:00
1052Wok InnDelhi280delivered2026-03-04 21:00:00
1064Spice RoutePune540delivered2026-03-05 13:30:00
1079Wok InnMumbai190delivered2026-03-05 20:45:00
1081Wok InnPune360refunded2026-03-06 19:10:00
SELECT order_id,
       restaurant,
       amount,
       amount + 25 AS with_delivery_fee
FROM orders

Every input row gives exactly one output row: SELECT changes columns, never the number of rows. Order 103 shows the first NULL rule: NULL + 25 is NULL, because adding to an unknown amount gives an unknown total.

Tip: SELECT * is fine for exploring, but name your columns in anything you keep. A query that names its columns still works when someone adds a column to the table, and it reads less data from columnar files like ParquetParquet: A columnar file format: values of each column are stored together, so queries read only the columns they need. Learn more →.

WHERE: keep the rows you need

WHERE is a condition checked on every row. A row is kept only when the condition is true. These are the operators you will use most:

OperatorExampleNotes
=, <>, <, >, <=, >=status = 'delivered'!= works too. Text comparisons are case-sensitive.
INcity IN ('Pune', 'Delhi')Shorter than a chain of ORs.
BETWEENamount BETWEEN 300 AND 500Inclusive at both ends: 300 and 500 are kept.
LIKErestaurant LIKE 'Pi%'% matches any run of characters, _ exactly one.
IS NULLstatus IS NULLThe only way to find missing values. = NULL never matches.
AND, OR, NOTa AND (b OR c)AND binds tighter than OR, so use brackets when you mix them.
Spark SQL · Pune orders between 300 and 500

Input: orders

order_idcustomer_idrestaurantcityamountstatusplaced_at
1011Spice RoutePune420delivered2026-03-01 12:10:00
1022Pizza LabDelhi650cancelled2026-03-01 19:40:00
1031Pizza LabPunenulldelivered2026-03-02 13:05:00
1043Spice RoutePune310null2026-03-03 20:15:00
1052Wok InnDelhi280delivered2026-03-04 21:00:00
1064Spice RoutePune540delivered2026-03-05 13:30:00
1079Wok InnMumbai190delivered2026-03-05 20:45:00
1081Wok InnPune360refunded2026-03-06 19:10:00
SELECT order_id, restaurant, amount
FROM orders
WHERE city = 'Pune'
  AND amount BETWEEN 300 AND 500
ORDER BY amount

Three Pune orders qualify: 104 (310), 108 (360) and 101 (420). Order 103 is in Pune, but its amount is NULL, and NULL BETWEEN 300 AND 500 is not true, so WHERE drops it. The next lesson is about exactly this.

Watch out: WHERE restaurant = 'Wok Inn' OR restaurant = 'Pizza Lab' AND amount > 300 reads as Wok Inn OR (Pizza Lab AND amount > 300), because AND is evaluated first. It returns every Wok Inn order, cheap ones included. Write WHERE restaurant IN ('Wok Inn', 'Pizza Lab') AND amount > 300, or add brackets.

ORDER BY and LIMIT: a top N

Without ORDER BY, rows come back in whatever order the engine finds them, and that order can change between runs. To get the "top 3", sort first, then cut:

Spark SQL · The three largest orders

Input: orders

order_idcustomer_idrestaurantcityamountstatusplaced_at
1011Spice RoutePune420delivered2026-03-01 12:10:00
1022Pizza LabDelhi650cancelled2026-03-01 19:40:00
1031Pizza LabPunenulldelivered2026-03-02 13:05:00
1043Spice RoutePune310null2026-03-03 20:15:00
1052Wok InnDelhi280delivered2026-03-04 21:00:00
1064Spice RoutePune540delivered2026-03-05 13:30:00
1079Wok InnMumbai190delivered2026-03-05 20:45:00
1081Wok InnPune360refunded2026-03-06 19:10:00
SELECT order_id, restaurant, amount
FROM orders
ORDER BY amount DESC NULLS LAST, order_id
LIMIT 3

In Spark, NULLs come first when you sort ascending and last when you sort descending. Writing NULLS LAST or NULLS FIRST makes the choice visible, and it matters when you move a query between engines: PostgreSQL and Oracle do the opposite by default. The second sort key, order_id, breaks ties, so the same query always returns the same three rows.

Why an alias does not work in WHERE

Go back to the running order: WHERE runs before SELECT, so a name you create in SELECT does not exist yet when WHERE runs. This fails:

Spark SQL · Fails: with_fee does not exist yet
SELECT order_id, amount + 25 AS with_fee
FROM orders
WHERE with_fee > 400

Error

[UNRESOLVED_COLUMN.WITH_SUGGESTION] A column, variable, or function
parameter with name `with_fee` cannot be resolved.

Repeat the expression in WHERE (WHERE amount + 25 > 400), or compute it in a subquerysubquery: A query inside another query, in brackets: in FROM as a table, or in WHERE with IN or EXISTS. Learn more → or CTECTE: A common table expression: a named step of a query, written WITH name AS (...), that later steps use like a table. Learn more → first. ORDER BY runs after SELECT, so ORDER BY with_fee does work.

Common mistakes

  • Using LIMIT without ORDER BY — You get some rows, not the top ones, and a different set each run on a distributed engine. Always sort before you cut.
  • Mixing AND and OR without brackets — AND is evaluated first, so a OR b AND c means a OR (b AND c). Bracket every mix, or use IN.
  • Filtering on a SELECT alias — WHERE runs before SELECT, so the alias does not exist yet. Repeat the expression, or filter in an outer query.
  • Forgetting that BETWEEN is inclusive — placed_at BETWEEN '2026-03-01' AND '2026-03-02' includes midnight on the 2nd and nothing after it. For time ranges, write >= start AND < next_day.

Key takeaways

  • SQL runs FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT, in that order, whatever order you write them in.
  • WHERE keeps a row only when its condition is true: false and NULL both drop the row.
  • BETWEEN includes both ends. For time ranges use >= start AND < end.
  • Sort before LIMIT, add a tie-breaker, and say NULLS FIRST or NULLS LAST when NULLs can appear.

Interview prep

THE QUESTION

"Return the three most expensive delivered orders. Two orders tie for third place: what does your query return?"

WHERE status = 'delivered' ORDER BY amount DESC, order_id LIMIT 3. LIMIT cuts after exactly three rows, so one of the tied orders is left out, and without the order_id tie-breaker which one could change between runs. Say that out loud. If both tied orders must appear, LIMIT is the wrong tool: rank with DENSE_RANK() and keep ranks up to 3 (the window functions lesson).

Avoid: "ORDER BY amount DESC LIMIT 3" with nothing more. It returns three rows, but which of the tied rows you get is left to chance, and the interviewer asked about the tie on purpose.

Follow-ups · answer out loud, then open

Follow-up"In what order does the database evaluate FROM, WHERE, GROUP BY, HAVING, SELECT and ORDER BY?"
FROM (and joins), WHERE, GROUP BY, HAVING, SELECT, then ORDER BY and LIMIT. That is why a SELECT alias works in ORDER BY but not in WHERE, and why WHERE cannot test an aggregate.
Scenario"A query filters placed_at BETWEEN '2026-03-01' AND '2026-03-31' on a timestamp column, and March 31 looks almost empty. Why?"
The string '2026-03-31' becomes midnight at the start of the 31st, and BETWEEN includes only that instant, so everything later that day is lost. Use a half-open range: placed_at >= '2026-03-01' AND placed_at < '2026-04-01'.
Trap"Is SELECT * FROM t LIMIT 10 a fine way to get the ten newest rows?"
No. Without ORDER BY there is no defined order; on a distributed engine you get whichever ten rows the first tasks return, and that can change between runs. Sort by the timestamp descending, with a tie-breaker, then LIMIT.

Check yourself

4 questions

Which clause runs first?

Show the answer

WHERE. FROM, then WHERE, then (GROUP BY, HAVING) SELECT, ORDER BY and LIMIT.

What does WHERE a = 1 OR b = 1 AND c = 1 mean?

Show the answer

a = 1 OR (b = 1 AND c = 1). AND binds tighter than OR.

You sort amounts ascending in Spark without NULLS FIRST or LAST. Where is the order with a NULL amount?

Show the answer

First. Spark puts NULLs first in ascending order and last in descending order.

Does amount BETWEEN 300 AND 500 keep an amount of 500?

Show the answer

Yes. BETWEEN is inclusive at both ends.

Practise this

Problems that use this, graded on hidden tests

See all 4 problems →

Keep going

Up next · Reading a table · lesson 2 of 3 · 6 min read
NULL and three-valued logic
Why NULL = NULL is not true, how WHERE quietly drops unknown rows, and the functions that handle NULL safely.

Related lessons

Primary sources: SELECT · WHERE clause · ORDER BY clause