What are SQL aliases, and why are they used?

Instruction: Provide an example query that uses an alias for a table name and a column name.

Context: This question tests the candidate's knowledge of aliases in SQL, which are used to temporarily rename tables or columns for the purpose of a particular query.

Updated

Official answer

A table alias names a relation within the query; an output alias labels a returned expression. Neither changes stored table or column names.

Assume PostgreSQL products(product_id integer, price numeric):

SELECT p.product_id AS id, p.price * 1.10 AS price_with_fee
FROM products AS p
ORDER BY p.product_id;

Here p is the table alias, while id and price_with_fee are output labels. A price of 20 produces 22.00 before any presentation formatting. NULL price remains NULL.

Aliases help explain derived columns and disambiguate joins. They do not by themselves guide the optimizer to a faster plan. Check where a database permits output aliases: for example, PostgreSQL does not make price_with_fee directly available in WHERE at this same query level. Use the expression or a named subquery when filtering it.

Related Questions