Chapter 8 · Lesson 7 of 8
Why SELECT Aliases Work in ORDER BY
Learn why a SELECT alias works in ORDER BY but not in WHERE, and sort employees by a calculated annual bonus column.
SELECT runs later than WHERE but earlier than ORDER BY.
That has an important consequence:
• In standard SQL, WHERE cannot use a SELECT alias
• ORDER BY can use a SELECT alias
Example:
SELECT name, salary * 0.10 AS annual_bonus
FROM employees
ORDER BY annual_bonus DESCBy the time ORDER BY runs, annual_bonus already exists in the result shape, so sorting by it is allowed.
DuckDB is permissive with some aliases in earlier clauses, but this standard logical-order rule is the most portable habit to learn.
Sample data
This lesson loads the employees table (8 rows) into DuckDB in your browser with one click, so you can run every example without uploading anything.
Setup SQL for employees
CREATE OR REPLACE TABLE employees (
id INTEGER,
name VARCHAR,
department VARCHAR,
salary DECIMAL(10,2),
hire_date DATE
);
INSERT INTO employees VALUES
(1, 'Alice', 'Engineering', 95000, '2021-03-15'),
(2, 'Bob', 'Marketing', 72000, '2020-07-01'),
(3, 'Charlie', 'Engineering', 110000, '2019-01-10'),
(4, 'Diana', 'Sales', 68000, '2022-11-20'),
(5, 'Eve', 'Marketing', 78000, '2021-09-05'),
(6, 'Frank', 'Engineering', 102000, '2020-02-28'),
(7, 'Grace', 'Sales', 71000, '2023-04-12'),
(8, 'Hank', 'Marketing', 65000, '2022-06-30');Practice challenge
Return name and annual_bonus, where annual_bonus is salary * 0.10. Order the result by annual_bonus descending.
Hint: Select salary * 0.10 AS annual_bonus, then ORDER BY annual_bonus DESC.
Run your query in the editor and the lesson checks the result automatically.
Lessons in Execution Order
Understand the logical order in which SQL evaluates FROM, WHERE, GROUP BY, HAVING, window functions, SELECT, ORDER BY, and LIMIT.