Sub topic 6
Naming results with column aliases
This chapter assumes you can write basic SELECT ... FROM ... WHERE queries and know the common column types. It also assumes you know what GROUP BY does. You have already seen that the SELECT list can hold computed expressions. Here you learn how to give each result column a name, and which rules and pitfalls come with doing so.
What a column alias is
A column alias is a name you assign to a column in the result set. It does not change the table. It only labels the output of one query.
SELECT first_name,
last_name,
salary,
salary * 12 AS annual_salary
FROM employees;The expression salary * 12 is computed for each row. AS annual_salary gives the result column that name.
Why aliases matter
A plain column such as first_name keeps its own name in the output. A computed expression has no natural name, so the database invents one. Each product invents it differently.
| Database | Name given to `salary * 12` with no alias |
|---|---|
| PostgreSQL | `?column?` |
| MySQL | `salary * 12` (the expression text) |
| SQL Server | No name at all (an empty header) |
| Oracle | `SALARY*12` (the expression text, uppercased) |
Generated names cause three kinds of trouble:
- Application code that reads columns by name breaks, or depends on one product's naming.
- Reports show headers such as
?column?. - Views and subqueries cannot use a column that has no usable name.
Treat every computed column as needing an alias.
The alias syntax
The general form is expression AS alias_name. You can alias any item in the SELECT list: a plain column, an arithmetic expression, a function call, or a CASE expression.
SELECT employee_id AS id,
UPPER(last_name) AS last_name_upper,
salary + COALESCE(commission, 0) AS total_pay
FROM employees;Renaming a plain column, as in employee_id AS id, is allowed. It changes only the name in the output. The column in the table keeps its name.
The AS keyword is optional, but keep it
Most databases let you leave out AS:
SELECT salary * 12 annual_salary
FROM employees;Oracle accepts this form for column aliases, but not AS on table aliases. PostgreSQL requires AS when the alias is also a keyword. Dropping AS also creates a well-known bug. If you forget a comma between two columns, the second column silently becomes an alias for the first:
SELECT first_name last_name
FROM employees;This query returns one column, first_name values labeled last_name. No error appears. Always writing AS makes the mistake easy to spot, because first_name last_name no longer looks like two columns.
Quoting aliases
An unquoted alias must follow the rules for identifiers. It has to start with a letter or underscore, contain no spaces, and not be a reserved word. If you need spaces, special characters, or a specific letter case, quote the alias. Standard SQL uses double quotes:
SELECT salary * 12 AS "Annual Salary"
FROM employees;Other databases use their own quoting characters.
| Database | Quote style | Example |
|---|---|---|
| Standard SQL, PostgreSQL, Oracle | Double quotes | `"Annual Salary"` |
| MySQL | Backticks | `` `Annual Salary` `` |
| SQL Server | Square brackets or double quotes | `[Annual Salary]` |
Quoting also controls letter case. PostgreSQL folds unquoted names to lowercase, and Oracle folds them to uppercase. AS AnnualSalary therefore comes back as annualsalary in PostgreSQL and ANNUALSALARY in Oracle. AS "AnnualSalary" keeps the exact case, but then you must write the quotes and the exact case every time you refer to that name.
For code that other people or programs will read, choose names that need no quoting. Use lowercase words joined by underscores, such as annual_salary.
Aliases in subqueries, views, and created tables
The alias is more than a display label. Wherever a query becomes a source for something else, its output column names become real column names.
SELECT employee_id, annual_salary
FROM (
SELECT employee_id, salary * 12 AS annual_salary
FROM employees
) AS e;The outer query can only use annual_salary because the inner query named it. Without that alias the outer query would have no reliable way to refer to the column.
The same applies when you save a query:
CREATE VIEW employee_pay AS
SELECT employee_id,
salary * 12 AS annual_salary
FROM employees;annual_salary is now a column of the view. SQL Server rejects a view that has an unnamed computed column, and other databases create a column with an unusable generated name. The same holds for CREATE TABLE ... AS SELECT. You can also list column names in the view or table definition instead of aliasing inside the query. The result is the same.
Aliases and client code
Applications that fetch rows usually read values by column name, for example row["annual_salary"]. The alias is the contract between your query and that code. Renaming an alias is therefore a breaking change for any caller that reads it by name.
Duplicate names cause a related problem. This query returns two columns with the same name:
SELECT e.name, d.name
FROM employees AS e
JOIN departments AS d ON d.department_id = e.department_id;Many client libraries keep only one of them when they build a name-to-value map. Alias each column so the names differ:
SELECT e.name AS employee_name,
d.name AS department_name
FROM employees AS e
JOIN departments AS d ON d.department_id = e.department_id;Here e and d are table aliases. They label tables inside the query, not output columns. A column alias names something in the result set. A table alias names a source in the FROM clause. The two use similar syntax but do different jobs.
Edge cases and common errors
Reusing an existing column name
You can give an expression the same name as a real column:
SELECT salary * 12 AS salary
FROM employees;This is legal, but it is confusing. Later in the query, a name such as salary might refer to the table column or to your alias, depending on the clause and the database. Choose an alias that differs from every column in the source tables.
Using the same alias twice
Two columns with the same alias are allowed in a top-level query. They are a problem when the query is a subquery or view, because the outer query cannot tell them apart. Some databases report an ambiguous-column error and others fail when the view is created.
Reserved words
A word such as order, group, user, or year can be reserved or special, depending on the database. Using it as an unquoted alias may give a syntax error or surprising behavior. Quote it or pick another name. order_total is a safer choice than order.
An alias does not make an expression reusable
Defining annual_salary in the SELECT list does not let you use it in every clause of the same query. Whether a clause can see the alias depends on the order in which the database evaluates the clauses. The next chapter covers this rule. Until then, remember that SELECT salary * 12 AS annual_salary ... WHERE annual_salary > 100000 fails in standard SQL.
Aliases for aggregates
Aggregate results have the same naming problem as other expressions, so alias them too:
SELECT department_id,
COUNT(*) AS headcount,
AVG(salary) AS average_salary
FROM employees
GROUP BY department_id;Without aliases, these columns are named count and avg in PostgreSQL, COUNT(*) and AVG(salary) in MySQL, and nothing in SQL Server.
Naming guidelines
- Always write
AS. - Use lowercase words separated by underscores, such as
total_pay. - Name the value, not the formula.
annual_salarysays more thansalary_times_12. - Make every alias in a query distinct from every source column name.
- Avoid reserved words and anything that needs quoting.
- Alias every expression, function call, aggregate, and CASE in the SELECT list.
Summary
An alias gives a result column a stable name. It matters most for computed columns, because databases otherwise invent names that differ between products or leave the column unnamed. The alias becomes a real column name in subqueries, views, and tables created from a query. It is also the name that client code reads. Write AS, quote only when you must, and avoid duplicates and reserved words.
Exercise
A teammate writes SELECT first_name last_name, salary FROM employees; and reports that the result has a column called last_name that contains first names. What happened, and how do you fix and prevent it?
Show answer
The comma between first_name and last_name is missing, so last_name was read as an optional-AS alias for first_name. Fix it by adding the comma: SELECT first_name, last_name, salary FROM employees;. Prevent it by always writing AS when you alias, because first_name AS last_name is obviously an alias while first_name last_name looks like a missing comma.
Exercise
Write a query on employees that returns employee_id and a column named Annual Salary (with the space and that exact case) equal to salary * 12. Then explain why you might choose annual_salary instead.
Show answer
SELECT employee_id, salary * 12 AS "Annual Salary" FROM employees; (use backticks in MySQL or square brackets in SQL Server). annual_salary needs no quoting, so it avoids quoting differences between databases and case-folding surprises. It is also easier to refer to in subqueries, views, and application code.