Querydrill

Basics Updated November 2026

Aliases (AS)

An alias renames a column or table for one query: SELECT price * qty AS total names the computed column, and FROM orders AS o lets you write o.id instead of orders.id. AS is optional. Column aliases work in ORDER BY (and in GROUP BY and HAVING in SQLite and PostgreSQL), not in WHERE.

Syntax

SELECT expression AS column_alias FROM table_name AS table_alias

Examples

SELECT name, price * 0.9 AS discounted FROM products ORDER BY discounted DESC;

Result: name | discounted Cap | 13.5

ORDER BY can use the alias because it runs after SELECT.

SELECT o.id, c.name
FROM orders o
JOIN customers c ON c.id = o.customer_id;

Result: Short table aliases keep join queries readable

SELECT name AS "Customer name", country AS "Country" FROM customers;

Result: Column headers with spaces and capitals

Double quotes make an identifier; use them for aliases with spaces or that must keep their case in PostgreSQL.

Common mistakes

  • Using a column alias in WHERE (WHERE discounted > 10) fails with no such column; repeat the expression or use a subquery or CTE.
  • Once a table has an alias the original name is gone in that query: FROM orders o ... WHERE orders.id = 1 raises an error, use o.id.
  • Wrapping an alias in single quotes (AS 'total') creates a string literal alias that works in SQLite but is invalid in PostgreSQL; use double quotes or no quotes.

Practice Aliases (AS)

These drills check your answer on live data, free, no account needed.

Questions

Is AS required for aliases?

No. SELECT price * qty total and FROM orders o both work in SQLite and PostgreSQL. Writing AS for column aliases is clearer and avoids the missing-comma trap.

Why can I use an alias in ORDER BY but not in WHERE?

SQL evaluates FROM and WHERE before the SELECT list, so the alias does not exist yet in WHERE. ORDER BY runs after SELECT and can see it.

Related

  • SELECTHow to write a SQL SELECT: choose columns from a table, select everything with *, compute expressions, and combine it with WHERE, ORDER BY and LIMIT.
  • INNER JOININNER JOIN returns rows that have a match in both tables. Syntax with ON, joining three tables, aliases, columns from both sides, and the common pitfalls.
  • ORDER BYORDER BY sorts the rows of a query result. Learn ASC and DESC, sorting on multiple columns, sorting by an expression or alias, and where NULLs end up.
  • SubqueryA subquery is a SELECT inside another query. Scalar subqueries (compare to an average), IN subqueries, correlated subqueries and derived tables in FROM.

Previous: Primary and foreign keys