DataBolt

All Lessons

Introduction to SQL
SQL Lesson 1: Your Sample Database
SQL Lesson 2: SELECT — Reading data
SQL Lesson 3: WHERE — Filtering rows
SQL Lesson 4: AND, OR, NOT
SQL Lesson 5: BETWEEN, IN, LIKE
SQL Lesson 6: NULL — The Mystery Value
SQL Lesson 7: ORDER BY
SQL Lesson 8: LIMIT & OFFSET
SQL Lesson 9: Aggregate Functions
SQL Lesson 10: GROUP BY
SQL Lesson 11: HAVING
SQL Lesson 12: INNER JOINs
SQL Lesson 13: LEFT JOINs
SQL Lesson 14: RIGHT JOINs
SQL Lesson 15: SELF JOINs
SQL Lesson 16: UNION JOINs
SQL Lesson 17: Joining Multiple Tables
SQL Lesson 18: Subqueries
SQL Lesson 19: CTEs (WITH)
SQL Lesson 20: CASE Statements
SQL Lesson 21: Window Functions
SQL Lesson 22: String Functions
SQL Lesson 23: Date & Time Functions
SQL Lesson 24: INSERT, UPDATE, DELETE
SQL Lesson 25: CREATE TABLE & DDL
SQL Lesson 26: Indexes & Performance
SQL Lesson 27: Transactions & ACID
SQL Lesson 28: SQL Execution Order
SQL Lesson 29: 50 Practice Problems

CHAPTER 29

SQL Execution Order

The secret that explains 80% of SQL errors.

IN THIS CHAPTER

  • The actual order SQL clauses execute (it is not what you write)
  • Why you cannot use SELECT aliases in WHERE
  • Why aggregate functions are forbidden in WHERE
  • How to write queries with this knowledge

You write SQL in this order: SELECT → FROM → WHERE → GROUP BY → HAVING → ORDER BY → LIMIT

But SQL excute in this order:

Execution StepClauseWhat happens
1FROMIdentify the source table(s)
2JOINCombine joined tables
3WHEREFilter individual rows
4GROUP BYGroup remaining rows
5HAVINGFilter groups
6SELECTCompute output columns and aliases
7DISTINCTRemove duplicate rows
8ORDER BYSort the result
9LIMITRestrict row count

The Practical Implications

These FAIL - and now you know why

-- FAILS: WHERE runs before SELECT, alias 'annual' doesn't exist
yet
SELECT salary * 12 AS annual FROM employees WHERE annual > 100000;
-- FAILS: WHERE cannot use aggregate functions
SELECT department FROM employees WHERE COUNT(*) > 2;
-- FAILS: HAVING is not available without GROUP BY in most dialects
SELECT name FROM employees HAVING salary > 70000;

These FAIL - and now you know why

-- Use the expression directly in WHERE
SELECT salary * 12 AS annual FROM employees WHERE salary * 12 >
100000;
-- Use HAVING for aggregate filters
SELECT department FROM employees GROUP BY department HAVING
COUNT(*) > 2;
-- Alias is fine in ORDER BY (runs after SELECT)
SELECT salary * 12 AS annual FROM employees ORDER BY annual DESC;

Interview Tips: Why can't I use a SELECT alias in a WHERE clause?' is a common interview screening question. It filters candidates who have merely memorised syntax from those who understand how SQL actually executes.