Sub topic 7
Where an alias can and cannot be used
This chapter assumes you can write SELECT ... FROM ... WHERE queries and use GROUP BY with aggregates such as COUNT and SUM. It also assumes you know how to name a computed column with AS. The question here is where that name is visible. If you get this wrong, you see errors like column "annual_salary" does not exist, even though you just defined it.
The core problem
Consider this query:
SELECT employee_id,
salary * 12 AS annual_salary
FROM employees
WHERE annual_salary > 100000;In standard SQL this fails. PostgreSQL, SQL Server, and Oracle all report an unknown column. The cause is the order in which the database logically evaluates the clauses, which is different from the order you write them.
Logical order of evaluation
You write SELECT first, but the database processes it late. The logical order is:
FROM(and joins)WHEREGROUP BYHAVINGSELECT(the list is computed here, and aliases are created)DISTINCTORDER BYLIMIT/OFFSET/FETCH
An alias comes into existence at step 5. Any clause that runs before that step cannot see it. Clauses that run after it can.
This logical order describes the meaning of the query. A real optimizer can reorder physical work, but the result must match what this order would give.
Where an alias works
ORDER BY
ORDER BY runs after the SELECT list, so every major database accepts an alias there.
SELECT employee_id,
salary * 12 AS annual_salary
FROM employees
ORDER BY annual_salary DESC;You can also sort by position, for example ORDER BY 2 DESC. That sorts by the second item in the SELECT list. Positions are short, but they break silently if someone reorders the list, so prefer aliases in code you keep.
Be careful with alias use inside an expression in ORDER BY. In PostgreSQL, ORDER BY annual_salary works, but ORDER BY annual_salary * -1 raises an error. In that engine an output name is only recognized when it stands alone. If you need a calculation, repeat the original expression or wrap the query in a subquery.
Outer queries
A subquery in the FROM clause produces a derived table. Its aliases become ordinary column names for the outer query. That means the outer WHERE, GROUP BY, and SELECT can all use them.
SELECT employee_id, annual_salary
FROM (
SELECT employee_id, salary * 12 AS annual_salary
FROM employees
) AS e
WHERE annual_salary > 100000;Note the alias e on the subquery. Most databases require a name for every derived table. Oracle accepts the alias without AS, so write ) e there.
Where an alias does not work (in standard SQL)
| Clause | Standard SQL | Why |
|---|---|---|
| `WHERE` | No | Runs before `SELECT` |
| `GROUP BY` | No | Runs before `SELECT` |
| `HAVING` | No | Runs before `SELECT` |
| Another expression in the same `SELECT` list | No | All items in the list are conceptually computed together |
| `ORDER BY` | Yes | Runs after `SELECT` |
| Outer query of a subquery or CTE | Yes | The alias is now a real column of the derived table |
The same-list case catches many people:
SELECT salary * 12 AS annual_salary,
annual_salary * 0.2 AS estimated_tax
FROM employees;This fails in PostgreSQL, SQL Server, and Oracle. The two items are computed as if at the same moment, so the second one cannot read the first.
Fixing the problem
You have three common options.
Option 1: Repeat the expression
SELECT employee_id,
salary * 12 AS annual_salary
FROM employees
WHERE salary * 12 > 100000;This is simple and works everywhere. The cost is duplication. If the formula changes, you must change it in two places, and a mismatch gives wrong results with no error. For long formulas, use another option.
Option 2: Subquery in FROM
This is the form shown earlier. It keeps the formula in one place, but it adds nesting.
Option 3: Common table expression
A common table expression (CTE) is a named query defined with WITH. It reads top to bottom, which many people find clearer than nested subqueries. You can chain several of them, and each one can use the aliases from the previous one.
WITH pay AS (
SELECT employee_id,
salary * 12 AS annual_salary
FROM employees
)
SELECT employee_id,
annual_salary,
annual_salary * 0.2 AS estimated_tax
FROM pay
WHERE annual_salary > 100000
ORDER BY annual_salary DESC;Here the alias is used in the outer WHERE, in the same-level calculation of estimated_tax, and in ORDER BY. All three work because annual_salary is a real column of pay.
Some engines also offer lateral constructs, such as CROSS APPLY in SQL Server or LATERAL in PostgreSQL. They let a later item read the result of an earlier calculation. They are useful, but they are not portable.
A name collision trap
An alias can have the same name as a real column. Then it matters which one a clause picks.
SELECT employee_id,
salary * 12 AS salary
FROM employees
WHERE salary > 100000
ORDER BY salary DESC;The two clauses read different things:
WHERE salaryrefers to the columnemployees.salary(the monthly amount), because the alias does not exist yet at that stage.ORDER BY salaryrefers to the output alias (the annual amount) in standard SQL and PostgreSQL. Engines differ in how they handle this conflict, so check yours.
The query runs without any error, but the filter and the sort use different numbers. Avoid this by giving computed columns names that no real column uses, such as annual_salary.
Dialect differences
Some databases relax the standard rules. These differences matter when you move queries between systems.
| Engine | Alias in `WHERE` | Alias in `GROUP BY` | Alias in `HAVING` |
|---|---|---|---|
| PostgreSQL | No | Yes | No |
| MySQL | No | Yes | Yes |
| SQL Server | No | No | No |
| Oracle | No | No | No |
| SQLite | Yes | Yes | Yes |
| Snowflake | Yes | Yes | Yes |
ORDER BY accepts aliases in all of them. Treat the table as a guide and check your engine's documentation for your version, because rules change between releases.
The practical rule is simple. A query that relies on a relaxed rule will break when it moves to another database. If a query might run on more than one engine, use the subquery or CTE form, which works everywhere.
Aggregates have one more restriction that is not about aliases. Even where HAVING accepts an alias, you cannot put an aggregate in WHERE:
SELECT department_id,
SUM(salary) AS total_salary
FROM employees
GROUP BY department_id
HAVING SUM(salary) > 500000;Writing HAVING SUM(salary) is portable. Writing HAVING total_salary > 500000 works only on engines that allow it.
Why this matters for CASE
A CASE expression often produces a label such as salary_band. You will want to group or filter by that label. Because WHERE and standard GROUP BY cannot see the alias, the usual solution is the subquery or CTE pattern from this chapter. The next chapters rely on it.
Quick checklist
- Does the clause run before
SELECT? Then, in standard SQL, it cannot see the alias. - Does the clause run after
SELECT? (ORDER BY) Then it can, usually only as a bare name. - Do you need the alias in
WHERE,GROUP BY, or another select item? Wrap the query in a subquery or CTE. - Might the query run on another database? Do not depend on relaxed alias rules.
Exercise
This query fails with an unknown-column error in PostgreSQL. Explain why, then rewrite it so it works. SELECT orderid, quantity * unitprice AS linetotal FROM orderlines WHERE line_total > 500;
Show answer
WHERE is evaluated before the SELECT list, so the alias linetotal does not exist yet. One fix is to repeat the expression: WHERE quantity * unitprice > 500. A fix that keeps the formula in one place uses a subquery or CTE: WITH lines AS ( SELECT orderid, quantity * unitprice AS linetotal FROM orderlines ) SELECT orderid, linetotal FROM lines WHERE line_total > 500;
Exercise
In this query, which value does WHERE use and which value does ORDER BY use? What is the risk? SELECT employee_id, salary * 12 AS salary FROM employees WHERE salary > 100000 ORDER BY salary DESC;
Show answer
WHERE uses the real column employees.salary (the monthly figure), because the alias is not created until the SELECT step. In standard SQL and PostgreSQL, ORDER BY uses the output alias (the annual figure). The filter and the sort therefore work on different numbers, with no error. Renaming the alias to annual_salary removes the ambiguity.