Sub topic 3
Computing values and naming them with aliases
This chapter assumes you can write a basic SELECT ... FROM query, you know what tables, rows, and columns are, and you have a SQL client connected to PostgreSQL, MySQL, or SQLite. The examples use an employees table with the columns first_name, last_name, department, salary, hire_date, and manager_id.
Expressions in the select list
A column name is not the only thing you can put after SELECT. Any expression works. An expression is a combination of columns, literal values, operators, and functions that the database evaluates to produce one value for each row.
SELECT first_name, salary * 12 AS annual_salary
FROM employees;For each row, the database reads salary, multiplies it by 12, and returns the result next to first_name. The table itself is not changed. The computed value exists only in the result set, which is the set of rows the query returns.
Common expression types:
| Kind | Example | Result | Column | Column | Column | Column |
|---|---|---|---|---|---|---|
| Arithmetic | `salary * 12`, `salary + 500`, `salary / 2` | A number | ||||
| Literal | `'active'`, `1`, `3.14` | The same constant on every row | ||||
| Function call | `UPPER(last_name)`, `ROUND(salary / 12, 2)` | Depends on the function | ||||
| Concatenation | `first_name \ | \ | ' ' \ | \ | last_name` | Text (see the dialect note below) |
Naming results with AS
If you leave an expression unnamed, the database invents a column name. PostgreSQL names salary * 12 as ?column?. SQLite and MySQL use the expression text itself. None of these names are pleasant to read or to refer to from application code.
A column alias is a name you give to a result column. You write it after the expression, using the AS keyword.
SELECT first_name, salary * 12 AS annual_salary
FROM employees;The alias changes only the label in the output. It does not create a column in the table, and it does not exist in any other query.
You can alias plain columns too, which is useful for producing friendlier headings:
SELECT first_name AS given_name,
last_name AS family_name
FROM employees;AS is optional, but write it anyway
The SQL standard allows you to omit AS, so salary * 12 annual_salary works in most databases. The omission causes a common bug: a missing comma between two columns turns the second one into an alias for the first.
SELECT first_name last_name
FROM employees;This query does not fail. It returns one column, the first names, labeled last_name. Writing AS every time makes aliases visible, and it makes this kind of mistake easier to spot.
Aliases with spaces or mixed case
An alias that contains spaces, or that must keep its capital letters, needs quoting. The standard uses double quotes. MySQL uses backticks by default, and SQLite accepts both.
SELECT salary * 12 AS "Annual Salary"
FROM employees;In PostgreSQL, unquoted names are folded to lowercase. AS AnnualSalary produces a column called annualsalary, while AS "AnnualSalary" keeps the capitals. The simplest habit is to use lowercase names with underscores, such as annual_salary, and avoid quoting altogether.
Computing without a table
An expression does not need a column. You can select literals and function results directly, which is a quick way to test how an expression behaves.
SELECT 7 / 2 AS quotient, 7 % 2 AS remainder;PostgreSQL, MySQL, and SQLite accept a SELECT with no FROM. Oracle requires FROM dual. This chapter's examples use employees, so you can run them as they are.
Edge cases that affect computed values
Integer division
When both operands are integers, PostgreSQL and SQLite perform integer division and discard the fraction, so 7 / 2 returns 3. MySQL returns 3.5000 for the same expression. If salary is an integer column and you want a fractional result in PostgreSQL or SQLite, make one operand a decimal.
SELECT first_name,
salary / 12.0 AS monthly_salary
FROM employees;NULL propagates through arithmetic
If any operand is NULL, the whole arithmetic expression is NULL. A NULL bonus added to a salary gives NULL, not the salary. The function COALESCE returns its first non-NULL argument and is the usual remedy. This table has no bonus column, so the next query uses manager_id only to show the shape of the technique.
SELECT first_name,
COALESCE(manager_id, 0) AS manager_or_zero
FROM employees;Chapter 10 returns to NULL in detail. For now, remember that a computed column is NULL whenever one of its inputs is.
Text concatenation differs by database
The standard operator for joining text is ||. PostgreSQL and SQLite support it. MySQL treats || as a logical OR unless a special mode is enabled, so it uses CONCAT() instead.
SELECT first_name || ' ' || last_name AS full_name
FROM employees;In MySQL, write CONCAT(first_name, ' ', last_name) AS full_name. CONCAT also works in PostgreSQL. In SQLite 3.44 and later it works too.
Where an alias can and cannot be used
An alias is defined in the SELECT list, and that fact decides where you can use it. A database does not evaluate a query in the order you write it. It conceptually processes FROM first, then WHERE, then SELECT, and finally ORDER BY.
The diagram shows this order and where the alias comes into existence.
WHERE runs before SELECT, so the alias does not exist yet when WHERE is evaluated. This query fails:
SELECT first_name, salary * 12 AS annual_salary
FROM employees
WHERE annual_salary > 600000;The error is typically "column annual_salary does not exist" (PostgreSQL) or "no such column" (SQLite). The fix is to repeat the expression in WHERE:
SELECT first_name, salary * 12 AS annual_salary
FROM employees
WHERE salary * 12 > 600000;ORDER BY runs after SELECT, so it can use the alias:
SELECT first_name, salary * 12 AS annual_salary
FROM employees
WHERE salary > 40000
ORDER BY annual_salary DESC;Aliases cannot refer to each other
Two aliases in the same select list cannot see one another. This fails in standard SQL:
SELECT salary * 12 AS annual_salary,
annual_salary / 52 AS weekly_salary
FROM employees;Repeat the expression (salary * 12 / 52) or use a subquery, which a later chapter covers.
Common errors
- Using an alias in
WHERE. The alias does not exist yet. Repeat the expression. - Forgetting a comma.
SELECT first_name last_namereturns one aliased column, not two columns. - Quoting with the wrong marks. Single quotes create text values, not names.
AS 'Annual Salary'works in some databases and fails in others. Use double quotes, or backticks in MySQL. - Expecting integer division to return decimals. Cast or use a decimal literal such as
12.0. - Assuming
NULLacts like zero. Arithmetic withNULLgivesNULL.
Exercise
A colleague writes this query and gets an error in PostgreSQL. Explain the cause and write a corrected version that still sorts by the computed value. SELECT firstname, salary * 12 AS annualsalary FROM employees WHERE annualsalary > 600000 ORDER BY annualsalary DESC;
Show answer
WHERE is evaluated before SELECT, so the alias annualsalary does not exist yet at that step. ORDER BY runs after SELECT, so the alias is valid there. The corrected query repeats the expression in WHERE and keeps the alias in ORDER BY: SELECT firstname, salary 12 AS annual_salary FROM employees WHERE salary 12 > 600000 ORDER BY annual_salary DESC;
Exercise
What does SELECT firstname lastname FROM employees return, and how would you change it to return both columns?
Show answer
It returns one column containing first names, labeled lastname, because without a comma the second word is treated as an alias for firstname. Add the comma: SELECT firstname, lastname FROM employees. Writing AS before every alias makes this mistake easier to see.
Exercise
Write a query that returns each employee's firstname and a column called monthlysalary, computed as salary divided by 12 with a fractional result, even if salary is stored as an integer.
Show answer
SELECT firstname, salary / 12.0 AS monthlysalary FROM employees; Dividing by the decimal literal 12.0 avoids integer division in PostgreSQL and SQLite.