Skip to main content
ZORK Academy

Your first SQL query, explained line by line

SELECT, FROM, WHERE and ORDER BY: what each part of a basic SQL query does, and the order the database actually runs them in.

Published

Suppose a table called courses stores a title, a level and a duration in hours for each course. Here is a query that lists beginner courses, shortest first:

SELECT title, duration_hours
FROM courses
WHERE level = 'beginner'
ORDER BY duration_hours ASC;

What each line does

  • SELECT title, duration_hours chooses which columns appear in the result.
  • FROM courses says which table to read.
  • WHERE level = 'beginner' keeps only the rows where the condition is true.
  • ORDER BY duration_hours ASC sorts the result, smallest first. Without ORDER BY, the database may return rows in any order — never rely on it.

The order the database runs it in

You write SELECT first, but the database works roughly like this:

  1. FROM — find the table.
  2. WHERE — filter rows.
  3. SELECT — pick and compute columns.
  4. ORDER BY — sort what is left.

This explains a common surprise: you cannot use a column alias created in SELECT inside WHERE, because WHERE runs first.

A note on NULL

If some courses have no duration recorded, duration_hours is NULL — meaning unknown, not zero. WHERE duration_hours > 5 silently leaves those rows out, because "unknown is greater than 5" is not true. To find them, use WHERE duration_hours IS NULL.

Try it yourself

Change the query to list advanced courses, longest first. Then add LIMIT 3 at the end to see only the top three.

Want to practise this properly?

Free career advice

Career advice is free and there is no obligation. Share your number only if you would like us to respond.