Backend Development
SQL logical query order: why the same alias fails in some engines and runs in others
Put a column alias in WHERE and two database engines run the query while two others reject it, so "that always fails" is wrong. This post separates what SQL's logical order explains from what it doesn't: which names each clause can see in each engine, what actually runs first, and which fix holds up where.
SELECT name, salary AS sal FROM employees WHERE sal > 50000 ORDER BY name
-- SQLite
name|sal
Ana|60000
Sofia|80000
-- DuckDB
name|sal
Ana|60000
Sofia|80000
-- PostgreSQL
ERROR 42703: column "sal" does not exist
-- SQL Server
Msg 207, Level 16, State 1, Server <local>, Line 2
Invalid column name 'sal'.
SQLite, DuckDB, PostgreSQL and SQL Server run side by side here, and the output is verbatim, in our script's format.
The logical order, including the parts short lists leave out
The usual explanation of that error does hold for WHERE: according to MySQL's documentation, standard SQL disallows aliases in that clause, because the column value may not be determined yet when the clause is evaluated. What SQLite and DuckDB accept is each engine's own behavior. Here is the sequence SQL Server and PostgreSQL describe, with what short lists skip:
FROM,ONandJOINbuild the starting rows.WHEREdrops rows. An aggregate or window function written here is an error in all four engines.GROUP BYforms the groups.HAVINGdrops groups.SELECTcomputes the list and names the columns. Window functions are written here, and Snowflake documents their step right afterHAVING.DISTINCTcollapses repeated rows.ORDER BYsorts.LIMITorTOPtrims the result.
This sequence is the logical order, not the engine's order of execution: the actual plan can differ.
Where the window sits has visible effects. With WHERE dept = 'eng', COUNT(*) OVER () returns 2, not 5, because it only sees the rows the filter left. SUM(COUNT(*)) OVER () runs over groups that already exist.
SQL Server gives WITH no step of its own; PostgreSQL puts it first, before FROM, as a temporary table its planner may later fold. UNION sits between DISTINCT and ORDER BY: with UNION ALL, the final ORDER BY accepted the first branch's column name in all four engines.
Names and execution: what the order doesn't answer
That list helps you reason about the result. It doesn't say which aliases each engine accepts or when anything gets computed. Two separate contracts sit behind it:
- Names. Which alias each clause can see. Every engine sets this itself, and the order alone doesn't predict it.
- Execution. What gets computed, and when. The planner decides. SQL Server's documentation puts it this way: "The query processor determines the actual physical execution of the statement, and the order might vary from this list." The result has to match the logical order, but an error or a side effect can surface earlier.
Which names each engine sees
The columns from SQLite through SQL Server show what happened when each query ran. Columns marked doc. were not executed: they summarize the documentation, and not stated means the page we read doesn't say.
| Clause | SQLite | DuckDB | PostgreSQL | SQL Server | MySQL / MariaDB (doc.) | Oracle 26 (doc.) | BigQuery (doc.) |
|---|---|---|---|---|---|---|---|
WHERE | yes | yes | no | no | no | no | no, except with reusable column aliases |
GROUP BY | yes | yes | yes | no | yes | yes, from 23 | yes |
HAVING | yes | yes | no | no | yes | yes | yes |
ORDER BY, alone | yes | yes | yes | yes | yes | yes | yes |
Inside an ORDER BY expression | yes | yes | no | no | not stated | not stated | not stated |
Another column in the same SELECT | no | yes | no | no | not stated | not stated | no, except with reusable column aliases |
JOIN ON | yes | no | no | no | not stated | no | no |
The GROUP BY row and the ORDER BY expression row break the explanation based on order. PostgreSQL accepts the alias in a clause that comes before SELECT and rejects it in one that comes after: ORDER BY sal + 1 returns column "sal" does not exist. Its rule is about names: "An output column's name can be used to refer to the column's value in ORDER BY and GROUP BY clauses, but not in the WHERE or HAVING clauses; there you must write out the expression instead." SQL Server asks for something similar in ORDER BY: use the alias on its own, outside any expression.
- In SQLite and DuckDB, the alias of an aggregate or window function still fails in
WHERE. - DuckDB documents aliases in
WHERE,GROUP BYandHAVING, and excludes aJOIN'sON. We didn't find SQLite's behavior in its documentation: treat it as observed behavior, not a contract. - Oracle says the alias works in
ORDER BY"but not other clauses in the query", and also allows it inGROUP BYfrom Release 23. Its new-features guide addsHAVING.
ORDER BY. PostgreSQL also accepts one in GROUP BY; SQL Server accepts none anywhere else.When an alias shares a column's name
The errors in that table at least tell you something went wrong. When an alias repeats a column name, the engine picks one for you and the query keeps running.
In WHERE the column won in all four: SELECT name, salary * 2 AS salary with WHERE salary > 100000 returned 0 rows, where the alias would have returned 2. In ORDER BY it depends on how you write it: the alias wins when it stands alone, the column wins inside an expression. Adding + 0 reverses the order, with no error, and the output matches across all four engines:
-- ORDER BY salary (the alias wins)
SELECT name, -salary AS salary FROM employees WHERE employees.salary IS NOT NULL ORDER BY salary
name|salary
Sofia|-80000
Ana|-60000
Luis|-45000
Marta|-30000
-- ORDER BY salary + 0 (the column wins)
SELECT name, -salary AS salary FROM employees WHERE employees.salary IS NOT NULL ORDER BY salary + 0
name|salary
Marta|-30000
Luis|-45000
Ana|-60000
Sofia|-80000
GROUP BY doesn't follow ORDER BY here either: an ambiguous name resolves to the input column. Grouping by dept with UPPER(SUBSTRING(dept, 1, 1)) AS dept gave 3 groups in all four, where the alias would have given 2.
In HAVING the difference reaches the rows themselves. SQLite and DuckDB accept the same query and return different groups; PostgreSQL and SQL Server reject it:
SELECT dept, COUNT(*) AS salary FROM employees GROUP BY dept HAVING salary > 1 ORDER BY dept
-- SQLite
dept|salary
eng|2
ops|1
-- DuckDB
dept|salary
edu|2
eng|2
-- PostgreSQL
ERROR 42803: column "employees.salary" must appear in the GROUP BY clause or be used in an aggregate function
-- SQL Server
Msg 8121, Level 16, State 1, Server <local>, Line 2
Column 'employees.salary' is invalid in the HAVING clause because it is not contained in either an aggregate function or the GROUP BY clause.
SQLite resolves salary as the column, using the value from an arbitrary row in the group, while DuckDB resolves it as the alias. MySQL, which we did not run, searches in a different order per clause: ORDER BY checks the SELECT list first, while GROUP BY and HAVING check the tables first. It warns when HAVING is ambiguous.
yearly for annual pay, can't collide with anything in the table; salary can.What the order does guarantee
The logical order does decide the result when a filter moves. The same predicate gives different rows in the ON and in the WHERE of a LEFT JOIN, with identical output in all four engines:
-- Filter in ON
SELECT d.dept, e.name FROM departments d LEFT JOIN employees e ON e.dept = d.dept AND e.salary > 50000 ORDER BY d.dept, e.name
dept|name
eng|Ana
hr|NULL
ops|NULL
-- Filter in WHERE
SELECT d.dept, e.name FROM departments d LEFT JOIN employees e ON e.dept = d.dept WHERE e.salary > 50000 ORDER BY d.dept, e.name
dept|name
eng|Ana
ON acts while the tables combine, so departments with no match stay. WHERE comes later, and the NULL in those rows fails the comparison. To keep them, the filter belongs in ON.
The order leaves other things open:
DISTINCTwithORDER BYon a column that isn't selected fails in PostgreSQL and SQL Server. SQLite returnededu, ops, eng, DuckDBops, eng, edu.- In ascending sort,
NULLcomes first in SQLite and SQL Server, last in PostgreSQL and DuckDB. WithDESC, only PostgreSQL puts it first. - If you trim rows with
LIMIT, theORDER BYhas to produce a unique order. Otherwise, PostgreSQL warns of "an unpredictable subset of the query's rows".
The actual plan doesn't follow that order
ORDER BY amount LIMIT 3 reads like sort, then trim. With an index on amount, none of these three plans has a sort step, and PostgreSQL stopped after 3 rows of a 2000-row table:
-- SQLite
SCAN orders USING INDEX ix_orders_amount
-- PostgreSQL
Limit
-> Index Scan using ix_orders_amount on orders
-- SQL Server (SELECT TOP 3)
|--Top(TOP EXPRESSION:((3)))
|--Index Scan(OBJECT:([tempdb].[dbo].[orders].[ix_orders_amount]), ORDERED FORWARD)
-- PostgreSQL, actual rows
Limit (actual rows=3.00 loops=1)
-> Index Scan using ix_orders_amount on orders (actual rows=3.00 loops=1)
FROM doesn't choose which table is read first either. For FROM orders o JOIN customers c with WHERE c.id = 7 AND o.amount > 100, SQLite, PostgreSQL and SQL Server all started with customers. In SQLite, inner joins can be reordered and outer joins can't. A HAVING status = 'open' with no aggregate was applied before grouping in PostgreSQL, DuckDB and SQL Server:
-- FROM orders o JOIN customers c WHERE c.id = 7 AND o.amount > 100: SQLite
SEARCH c USING INDEX sqlite_autoindex_customers_1 (id=?)
SEARCH o USING INDEX ix_orders_customer (customer_id=?)
-- Same query: PostgreSQL
Nested Loop
-> Seq Scan on customers c
Filter: (id = 7)
-> Bitmap Heap Scan on orders o
-- GROUP BY status HAVING status = 'open': PostgreSQL
GroupAggregate
-> Seq Scan on orders
Filter: ((status)::text = 'open'::text)
These plans come from small tables, and PostgreSQL ran on PGlite, its 32-bit WebAssembly build, which we did not compare with a native server. Check your own query with EXPLAIN rather than assuming.
The guard that doesn't protect you
Suppose a text column holds numbers only on rows where kind = 'n', and one row with kind = 't' holds abc. The natural move is to filter and convert in the same WHERE, with the filter as a guard so the CAST only sees numbers. This table shows that written position isn't enough:
| Query | SQLite | DuckDB | PostgreSQL | SQL Server |
|---|---|---|---|---|
LOWER(UPPER(kind)) = 'n' AND CAST(v AS INTEGER) > 5 | passes* | error | error | error |
CAST(v AS INTEGER) > 5 AND LOWER(UPPER(kind)) = 'n' | passes* | passes | error | error |
CAST(v AS INTEGER) > 5 AND kind = 'n' | passes* | passes | passes | passes |
The wrapped guard in a subquery, CAST outside | passes* | passes | error | error |
The same guard in a CTE, CAST outside | passes* | passes | error | error |
The CTE above with MATERIALIZED | passes* | passes | passes | n/a |
CASE WHEN LOWER(UPPER(kind)) = 'n' THEN CAST(v AS INTEGER) END > 5 | passes* | passes | passes | passes |
kind = 'n' AND TRY_CAST(v AS INTEGER) > 5 | n/a | passes | n/a | passes |
SQLite's asterisk warns that its result proves nothing: there, CAST('abc' AS INTEGER) returns 0 instead of failing. n/a means the engine doesn't have that form. The first two rows are the same guard, wrapped in two functions, in different positions: moving it let DuckDB pass, while PostgreSQL and SQL Server kept failing. The third has a simple guard, written last, and failed nowhere.
SELECT v FROM raw_values WHERE LOWER(UPPER(kind)) = 'n' AND CAST(v AS INTEGER) > 5 ORDER BY v
-- DuckDB
ERROR ConversionException: Conversion Error: Could not convert string 'abc' to INT32 when casting from source column v
-- PostgreSQL
ERROR 22P02: invalid input syntax for type integer: "abc"
-- SQL Server
Msg 245, Level 16, State 1, Server <local>, Line 2
Conversion failed when converting the varchar value 'abc' to data type int.
"The order of evaluation of subexpressions is not defined", says PostgreSQL. SQL Server warns about "uncommon cases" involving an indexed view and a CONVERT; in our test the error came up on an ordinary table with no view. That is a result from these versions and this data, not a guarantee, and the documentation doesn't explain this particular planner decision.
Moving the guard into a subquery or a CTE doesn't put it in front: PostgreSQL and SQL Server kept failing, while DuckDB passed. PostgreSQL can fold the CTE into the parent query to optimize both together, and MATERIALIZED forces separate calculation.
The documented fix is CASE, which PostgreSQL recommends when evaluation order has to be forced, with the warning that it "will defeat optimization attempts". SQL Server documents that guarantee for scalar expressions; in DuckDB we only observed it. CASE orders the check but only protects what its condition tests: with a row where kind = 'n' and v = 'abc', that CASE failed in DuckDB, PostgreSQL and SQL Server. It doesn't protect aggregates either: CASE WHEN MIN(divisor) > 0 THEN AVG(amount / divisor) END gave NULL in SQLite and DuckDB and a division by zero in PostgreSQL and SQL Server, because the aggregate is computed before the CASE around it. With aggregates, the guard goes inside: AVG(CASE WHEN divisor <> 0 THEN amount / divisor END) or AVG(amount / NULLIF(divisor, 0)); both gave 11 in all four.
CAST or a division relies on a filter to avoid failing, don't trust the order of an AND or a CTE. Put it inside a CASE whose condition really checks the data; with an aggregate, inside the aggregate. If the data can't be trusted, check the value: TRY_CAST alongside your filter in DuckDB and SQL Server, or pg_input_is_valid as the CASE condition, from PostgreSQL 16. For a division, NULLIF(divisor, 0).Fixing the alias, and what each fix misses
The three portable forms returned Ana 720000, Sofia 960000 in all four engines:
-- Repeat the expression
SELECT name, salary * 12 AS yearly FROM employees WHERE salary * 12 > 600000 ORDER BY name
-- Derived table
SELECT name, yearly FROM (SELECT name, salary * 12 AS yearly FROM employees) t WHERE yearly > 600000 ORDER BY name
-- CTE
WITH t AS (SELECT name, salary * 12 AS yearly FROM employees) SELECT name, yearly FROM t WHERE yearly > 600000 ORDER BY name
-- Result in SQLite, DuckDB, PostgreSQL and SQL Server
name|yearly
Ana|720000
Sofia|960000
-- LATERAL (PostgreSQL, DuckDB)
SELECT e.name, x.yearly FROM employees e CROSS JOIN LATERAL (SELECT e.salary * 12 AS yearly) x WHERE x.yearly > 600000 ORDER BY e.name
-- CROSS APPLY (SQL Server)
SELECT e.name, x.yearly FROM employees e CROSS APPLY (SELECT e.salary * 12 AS yearly) x WHERE x.yearly > 600000 ORDER BY e.name
| Fix | Where it ran | What it doesn't cover |
|---|---|---|
| Repeat the expression | All four | Two copies that can drift apart |
| Derived table or CTE | All four | Names the value but guarantees neither materialization nor when it's evaluated |
LATERAL | PostgreSQL and DuckDB; CROSS APPLY in SQL Server; syntax error in SQLite | Not portable |
| Window inside a derived table | All four | Needs the extra level: its alias doesn't work in WHERE either |
CASE | All four | Aggregates and data the condition doesn't test; can block optimizations |
TRY_CAST | DuckDB and SQL Server | What it can't convert becomes NULL, with no count of the rows lost. Without your filter, rows it excluded get in. '' gave 0 in SQL Server and '12.5' gave 13 in DuckDB. In SQL Server, it doesn't protect a division |
MATERIALIZED | PostgreSQL and DuckDB; it runs in SQLite, but as a non-binding hint | Can cost performance |
Our opinion: repeat the expression if it is short and used in one filter; use a derived table or CTE if you reuse it; use LATERAL or CROSS APPLY only if the query will stay on that engine. None of them saves rows lost to NULL in a comparison: of 5 employees, 4 have a salary and only those 4 pass sal > 0.
Frequently asked questions
Can I sort or group by position?
ORDER BY 2 ran in all four engines. GROUP BY 1 ran in three, and SQL Server rejects it with error 164. A position that doesn't exist, like ORDER BY 9, fails everywhere.
Does alias case matter?
Without quotes, AS Sal could be referenced as sal in all four. With quotes, AS "Sal" passed in SQLite, DuckDB and SQL Server, and PostgreSQL returned error 42703. In SQL Server it depends on the collation: that holds for a case-insensitive one, and on a case-sensitive one both forms return error 207.
What ran and what didn't
SQLite 3.50.4, DuckDB 2.0.0, PostgreSQL 18.6 on PGlite 0.5.12 and SQL Server 2025 17.0.4025.3 on LocalDB, in memory or in tempdb. These results apply only to these versions and the configuration they ran with; others may differ. The ISO/IEC 9075 standard is paywalled and we did not read it: what is attributed to it comes from the linked documentation. No timings were measured. Tables to repeat the queries:
CREATE TABLE employees (id INT PRIMARY KEY, name VARCHAR(20), dept VARCHAR(10), salary INT);
INSERT INTO employees VALUES (1,'Ana','eng',60000),(2,'Luis','eng',45000),(3,'Marta','ops',30000),(4,'Ivan','edu',NULL),(5,'Sofia','edu',80000);
CREATE TABLE departments (dept VARCHAR(10) PRIMARY KEY, city VARCHAR(20));
INSERT INTO departments VALUES ('eng','Bogota'),('ops','Lima'),('hr','Quito');
CREATE TABLE raw_values (id INT PRIMARY KEY, kind VARCHAR(1), v VARCHAR(10));
INSERT INTO raw_values VALUES (1,'n','10'),(2,'n','22'),(3,'t','abc');
CREATE TABLE ratios (id INT PRIMARY KEY, amount INT, divisor INT);
INSERT INTO ratios VALUES (1,100,5),(2,100,0),(3,100,50);
-- The plan examples also use 20 customers and 2000 generated orders.
Conclusion
The logical order explains why an aggregate can't go in WHERE and why a filter in ON keeps rows. It doesn't tell you which aliases your engine accepts or when an expression will run. For names, check your engine's column in the names table; for execution, run EXPLAIN.
Look through your project today for the query that converts types inside a WHERE, or the one about to change engines, and test it against real data. If a CAST depends on a filter, move it into a CASE and check that the condition covers every bad row.
References
- SELECT (Transact-SQL): logical processing order (learn.microsoft.com)
- PostgreSQL 18: SELECT (postgresql.org)
- PostgreSQL 18: Value Expressions, expression evaluation rules (postgresql.org)
- MySQL 8.4: Problems with Column Aliases (dev.mysql.com)
- MariaDB: SELECT (mariadb.com)
- Oracle AI Database 26: SELECT (docs.oracle.com)
- DuckDB 2.0: Friendly SQL (duckdb.org)
- BigQuery: Query syntax (docs.cloud.google.com)
Tags
Share this post
Subscribe
Get the latest posts delivered right to your inbox.
Leave a comment