// dialect comparison

Table alias syntax: where AS is optional (and where it fails)

AS is optional almost everywhere, and a syntax error in one place.

Filed under Querying

The verdict

Write table aliases without AS and column aliases with AS; that parses on all five engines. The traps are Oracle, where AS before a table alias fails, and SQL Server's alias = expression form, which no other engine accepts.

Where they differ

All five engines accept FROM orders o; four also accept FROM orders AS o. Oracle rejects AS before a table alias. Column aliases accept AS everywhere, and SQL Server adds its own alias = expression form.

How each engine writes it

SQL Server

SELECT o.id, o.total FROM orders AS o WHERE o.total > 100;

AS is optional for tables and columns. The T-SQL-only form SELECT order_total = o.total also names a column.

PostgreSQL

SELECT o.id, o.total FROM orders o WHERE o.total > 100;

AS is optional. A column alias written without AS can't be a reserved keyword, so SELECT 1 AS from works and SELECT 1 from does not.

MySQL

SELECT o.id, o.total FROM orders o WHERE o.total > 100;

AS is optional. Column aliases may be quoted with backticks, double quotes or even single quotes ('Order Total').

SQLite

SELECT o.id, o.total FROM orders o WHERE o.total > 100;

AS is optional. SQLite also lets a SELECT-list alias be used in WHERE, which no other engine here allows.

Oracle

SELECT o.id, o.total FROM orders o WHERE o.total > 100;

FROM orders AS o fails with a syntax error. Column aliases may use AS or omit it.

Questions that come up

Why does my query fail on Oracle but not SQL Server?

Most likely the AS in FROM orders AS o: Oracle accepts AS only for column aliases. Write FROM orders o and the query runs on every engine.

Can I reference a SELECT-list alias in the WHERE clause?

Not portably. SQL Server, PostgreSQL, MySQL and Oracle reject it because WHERE is evaluated before the SELECT list; SQLite allows it. All five accept aliases in ORDER BY, and MySQL, PostgreSQL, SQLite and Oracle 23ai also in GROUP BY. Elsewhere, repeat the expression or wrap the query in a subquery or CTE.

When is a table alias required?

On derived tables in SQL Server and MySQL: FROM (SELECT …) AS x. PostgreSQL 16+, SQLite and Oracle accept an unnamed subquery, but naming it is portable. You also need aliases when the same table appears twice, as in a self-join.

Keep reading

// write it once, run it anywhere

Switch engines without relearning SQL

SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.