DataBolt

SQL LEARNING PLATFORM

27

CHAPTER 27

SQL Execution Order

The secret that explains 80% of SQL errors.

4

Learning Blocks

SQL

Interactive Queries

In This Chapter

Concepts you'll master

1

The actual order SQL clauses execute (it is not what you write)

2

Why you cannot use SELECT aliases in WHERE

3

Why aggregate functions are forbidden in WHERE

4

How to write queries with this knowledge

The Practical Implications

These FAIL - and now you know why
SQL QUERY
-- 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
SQL QUERY
-- 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.