Syntax Fundamentals

Aliases and Expressions

Rename columns, compute new ones, and produce a result set someone else can read.

Aliases and Expressions

A query does not have to return the columns exactly as they are stored. You can rename them, combine them, and calculate new ones.

Renaming with AS

SQL
SELECT first_name AS given_name,
       last_name  AS family_name,
       salary     AS annual_salary
FROM employees
LIMIT 5;

The stored column names are unchanged — AS only affects this result set.

AS is optional (salary annual_salary works) but write it anyway. Without it, a missing comma turns two columns into one silently:

SELECT first_name last_name FROM employees;

That returns one column of first names, labelled last_name. No error. This is one of the most common typos in SQL, and AS makes it obvious.

Computing new columns

SQL
SELECT first_name,
       salary,
       salary / 12 AS monthly,
       salary * 0.10 AS ten_percent_rise
FROM employees
WHERE salary IS NOT NULL
ORDER BY salary DESC
LIMIT 5;

monthly and ten_percent_rise do not exist in the table. They are computed per row, for this query only.

Joining text together

SQL
SELECT first_name || ' ' || last_name AS full_name,
       hired_on
FROM employees
ORDER BY hired_on
LIMIT 5;

Dialect note. || is the standard concatenation operator and works in PostgreSQL, SQLite and Oracle. MySQL needs CONCAT(first_name, ' ', last_name) unless it is running in ANSI mode. SQL Server uses +.

Quoting names with spaces

If an alias contains a space or a reserved word, quote it — with double quotes in PostgreSQL and SQLite, square brackets in SQL Server, backticks in MySQL:

SQL
SELECT first_name AS "Given name",
       salary     AS "Annual salary"
FROM employees
LIMIT 3;

Single quotes are for string values, never for identifiers. 'Given name' would be the literal text, not a column name — another very common mistake.

Common mistakes

  • Using an alias in WHERE — it does not exist yet at that point. Repeat the expression, or use a subquery.
  • Single quotes around an alias — that is a string, not a name.
  • Forgetting a comma — silently renames the previous column, as shown above.

Interview question

Can you reference a SELECT alias in WHERE? What about ORDER BY?

Not in WHERE — it runs before SELECT. Yes in ORDER BY, which runs after. That asymmetry follows directly from execution order.

Check yourself

  1. What does SELECT first_name last_name FROM employees return?
  2. Which quote style is for identifiers, and which for strings?
  3. Why does ORDER BY accept an alias when WHERE does not?

Next

Next: DISTINCT and sorting — removing duplicates and controlling row order.

Aliases and Expressions — SQL — The Interactive Visual Notebook