Recipe · SQL recipes

Common SQL alias mistakes

If an alias fails, check the commas, where it is in scope and the table name. A SELECT alias cannot be used portably in WHERE.

Before continuing: This entry is part of the aliases guide. If you are new to the topic, start with Alias.

Query

Products whose stock value is over 500
SELECT p.name AS product,
       ROUND(p.price * p.stock, 2) AS stock_value
FROM products AS p
WHERE p.price * p.stock > 500
ORDER BY stock_value DESC;

The query uses explicit commas, keeps the table alias p, repeats the calculation in WHERE and keeps the output alias for the column heading and the sort.

Cases that change the result

Mistake 1: forgetting a comma

A valid but misleading query
SELECT name price,
       stock
FROM products;

Because AS can be omitted, the engine may read price as an alias for name. The query returns product names under a heading called price, not the numeric column you expected.

Clear version
SELECT name AS product,
       price,
       stock
FROM products;

Write AS and putting each expression on its own line makes the comma between columns easy to see.

Mistake 2: using the alias too early

The alias does not exist yet in WHERE
SELECT price * stock AS stock_value
FROM products
WHERE stock_value > 500;

WHERE decides which rows get through before the output list is built. Repeat the expression in the filter, or compute the alias first in a subquery.

Mistake 3: mixing the alias and the original name

Inconsistent reference
SELECT products.name, p.price
FROM products AS p;

In PostgreSQL, once a table is given the alias p, that alias becomes its name within the query. Use p.name and p.price consistently. That discipline also avoids ambiguity in queries with several tables.

Mistake 4: repeated output names

Two expressions can share an alias and the engine may accept the query, but the result will be awkward to consume from an application. Avoid returning two columns called total; use names such as order_total and customer_total.

Checklist

  • Write one expression per line and check the commas.
  • Usa AS in column aliases when it makes them easier to read.
  • Do not filter in WHERE using an alias created in the same SELECT.
  • Once you give a table an alias, refer to its columns by that name.
  • Avoid duplicate or overly cryptic aliases.