01 / 20

SQL Logical Order

Understand the hidden sequence behind every SQL query: how the database actually processes your clauses, from FROM to LIMIT.

SQL

Why Does Order Matter?

You write a SQL query top-to-bottom: SELECT, then FROM, then WHERE. But the database doesn't read it that way. It follows a logical order of operations: a specific sequence that determines which data gets loaded, filtered, grouped, and finally returned.

Written Order vs Logical Order

Written Order
The syntax order you type:
SELECT → FROM → WHERE → GROUP BY → HAVING → ORDER BY → LIMIT
Logical Order
The processing order the engine follows:
FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT

The Seven Clauses

FROM
Identifies source tables and performs JOINs
WHERE
Filters individual rows before grouping
GROUP BY
Groups rows by shared column values
HAVING
Filters groups after aggregation
SELECT
Chooses columns and computes expressions
ORDER BY
Sorts the result set
LIMIT
Restricts the number of rows returned

The Logical Pipeline

1. FROM / JOIN 2. WHERE 3. GROUP BY 4. HAVING 5. SELECT 6. ORDER BY 7. LIMIT Load tables, combine rows Filter individual rows Create groups Filter groups Pick columns, compute Sort result rows Cap row count Step 1 Step 2 Step 3 Step 4 Step 5 Step 6 Step 7

WHERE vs HAVING

Both filter data, but they operate at different stages in the logical pipeline. This is one of the most tested distinctions in SQL.

WHERE HAVING
When it runs Step 2: before grouping Step 4: after grouping
Filters Individual rows Groups of rows
Can use aggregates? ✕ No ✓ Yes
Example WHERE price > 10 HAVING COUNT(*) > 5

Why SELECT Comes Late

SELECT runs at Step 5: after the data has been sourced, filtered, and grouped. This has real consequences for what you can and cannot do in your queries.

1
Column aliases created in SELECT are not available in WHERE or GROUP BY, because those clauses execute first.
2
Aggregate functions in SELECT (like SUM or COUNT) can't be referenced in WHERE, since rows haven't been grouped yet at that stage.
3
ORDER BY and LIMIT run after SELECT, so they can reference column aliases.

How to Apply the Logical Order

1
Read the query you've written (or are debugging) in full.
2
Mentally reorder the clauses into logical sequence: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT.
3
Trace the data through each step. At each stage, ask: "What rows/groups exist at this point?"
4
Check references: Can each clause see the columns, aliases, or aggregates it uses? If not, you've found the bug.
5
Fix placement: Move conditions to the correct clause (e.g., aggregate filters from WHERE to HAVING).

Example 1: Tracing a Query

SELECT department, COUNT(*) AS emp_count FROM employees WHERE salary > 50000 GROUP BY department HAVING COUNT(*) > 3 ORDER BY emp_count DESC;
1
FROM employees: load all rows from the employees table.
2
WHERE salary > 50000: keep only rows where salary exceeds 50,000.
3
GROUP BY department: group remaining rows by department.
4
HAVING COUNT(*) > 3: discard groups with 3 or fewer employees.
5
SELECT department, COUNT(*) AS emp_count: output columns.
6
ORDER BY emp_count DESC: sort by count, highest first.

Example 2: Alias Visibility

-- This query will ERROR: SELECT price * quantity AS total FROM orders WHERE total > 100; -- total not yet defined!
-- The fix: repeat the expression in WHERE SELECT price * quantity AS total FROM orders WHERE price * quantity > 100; -- uses raw columns

Example 3: JOIN + Full Pipeline

SELECT c.name, SUM(o.amount) AS total_spent FROM customers c JOIN orders o ON c.id = o.customer_id WHERE o.status = 'completed' GROUP BY c.name HAVING SUM(o.amount) > 500 ORDER BY total_spent DESC LIMIT 10;

Common Mistakes

✕ Alias in WHERE
Using a SELECT alias in the WHERE clause. WHERE runs before SELECT, so aliases don't exist yet.
✕ Aggregate in WHERE
Writing WHERE COUNT(*) > 5. Aggregates require grouped data, but WHERE runs before GROUP BY. Use HAVING instead.
✕ Wrong Filter Clause
Putting row-level filters in HAVING instead of WHERE. This is less efficient because the database groups first, then discards.

ORDER BY and LIMIT

These two clauses run last in the logical pipeline (Steps 6 and 7). This gives them a special privilege: they can reference column aliases defined in SELECT.

SELECT name, score * 1.1 AS curved_score FROM students ORDER BY curved_score DESC -- alias works here! LIMIT 5;

Think of It Like a Restaurant

1
FROM: Go to the pantry and gather all your ingredients (tables).
2
WHERE: Throw away any spoiled or unwanted ingredients (filter rows).
3
GROUP BY: Sort ingredients into bowls by type (create groups).
4
HAVING: Remove any bowl that doesn't have enough ingredients (filter groups).
5
SELECT: Plate the dish: choose what goes on the plate (pick columns).
6
ORDER BY: Arrange the plates nicely on the counter (sort results).
7
LIMIT: Serve only the first few plates to the customer (cap output).

Summary Reference

Step Clause What It Does Can Use Aliases?
1 FROM / JOIN Load and combine tables ✕
2 WHERE Filter rows ✕
3 GROUP BY Create groups ✕
4 HAVING Filter groups ✕
5 SELECT Choose columns, compute Defines them
6 ORDER BY Sort results ✓
7 LIMIT Cap row count ✓

Question 1 of 5

In the SQL logical order of operations, which clause is processed first?

Question 2 of 5

A query uses WHERE total > 100, where "total" is an alias defined in the SELECT clause. What will happen?

Question 3 of 5

You want to filter groups where the average salary is above 60,000. Which clause should contain this condition?

Question 4 of 5

Which of the following clauses can reference a column alias defined in SELECT?

Question 5 of 5

What is the correct logical order of SQL clause processing?