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_hourschooses which columns appear in the result.FROM coursessays which table to read.WHERE level = 'beginner'keeps only the rows where the condition is true.ORDER BY duration_hours ASCsorts the result, smallest first. WithoutORDER 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:
FROM— find the table.WHERE— filter rows.SELECT— pick and compute columns.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?
