Sub topic 1
Computing values in the SELECT list
A SELECT list does more than name columns. Each item in it is an expression, and the database evaluates that expression once for every row the query produces. This chapter covers what an expression is, how SQL evaluates it, and the errors that come up most often. Later chapters cover operators, functions, NULL, aliases, and CASE in detail.
Prerequisites
This chapter assumes you already know the following:
- Basic
SELECT ... FROM ... WHEREqueries. - Common column data types: numbers, text, and dates.
GROUP BYand aggregate functions such asCOUNTandSUM, which appear briefly near the end.
The examples use an employees table with the columns employee_id, first_name, last_name, salary, commission, and department_id. The commission column allows NULL. Other tables are introduced where they appear.
What counts as an expression
An expression is anything the database can reduce to a single value. In a SELECT list, each item is an expression. The simplest forms are:
- A column reference, such as
salary. - A literal, such as
12or'USD'. - A combination of these using operators, such as
salary * 12. - A function call, such as
UPPER(last_name). - A
CASEexpression, covered in later chapters. - A scalar subquery, which is a subquery that returns one row and one column.
Expressions can be nested. (salary + 500) * 12 is an expression made of smaller expressions. The database evaluates the inner parts first and uses their results in the outer parts.
Evaluating an expression per row
The key idea is row-by-row evaluation. For each row that survives the FROM and WHERE steps, the database computes every expression in the SELECT list and returns one output row.
SELECT first_name,
last_name,
salary,
salary * 12 AS annual_salary
FROM employees;The first three items are plain column references. The fourth, salary * 12, is computed separately for each employee. If the table has 500 rows, the expression is evaluated 500 times and the result has 500 rows. The AS annual_salary part names the result column. Aliases are covered in a later chapter. For now, treat it as a label.
The computed value is not stored anywhere. It exists only in the query result. Changing the expression never changes the table.
Where an expression sits in the query
SQL is written with SELECT first, but the database processes the clauses in a logical order. The order below is simplified and shows where the SELECT list fits.
This order explains several behaviors you will meet later in this tutorial:
WHEREruns before theSELECTlist, so it cannot see names defined in theSELECTlist.ORDER BYruns after theSELECTlist, so it can use those names.- With
GROUP BY, theSELECTlist is evaluated once per group, not once per source row.
The order is a logical model, not a physical one. The optimizer may rearrange the real work as long as the result is the same.
Mixing columns, literals, and operators
You can combine any values of compatible types. A few typical patterns:
SELECT employee_id,
first_name || ' ' || last_name AS full_name,
salary / 12 AS monthly_salary,
'USD' AS currency
FROM employees;Here || concatenates text in standard SQL, / divides, and 'USD' is a literal that produces the same value in every row. A literal column is useful for labeling output or for lining up queries that you combine with UNION.
Concatenation differs by product. MySQL uses CONCAT(first_name, ' ', last_name) by default, and SQL Server accepts + or CONCAT. The dialect chapter returns to this.
Expressions need a type
Every expression has a result type, and the database determines it before running the query. The type depends on the operands and the operator.
| Expression | Operand types | Typical result type | Column | Column |
|---|---|---|---|---|
| `salary * 12` | decimal and integer | decimal | ||
| `first_name \ | \ | last_name` | text and text | text |
| `hire_date + 30` | date and integer | date (in some products) | ||
| `5 / 2` | integer and integer | integer `2` in many products, decimal `2.5` in others |
The last row is a classic source of wrong numbers. In PostgreSQL, SQL Server, and several other products, dividing two integers performs integer division and drops the fraction. MySQL's / returns a decimal, and it has a separate DIV operator for integer division. If you need a fractional result, make at least one operand non-integer.
SELECT 5 / 2 AS int_division,
5 / 2.0 AS decimal_division,
CAST(5 AS DECIMAL(10, 2)) / 2 AS cast_division;In PostgreSQL this returns 2, 2.5000000000000000, and 2.5000000000000000. The exact number of decimal places varies by product.
Expressions without a table
Many products allow a SELECT with no FROM clause. This is handy for testing an expression in isolation.
SELECT 7 * 6 AS answer, 'hello' || ' world' AS greeting;PostgreSQL, SQL Server, MySQL, and SQLite accept this. Oracle requires FROM dual. Db2 requires FROM sysibm.sysdual or a VALUES form. When an expression behaves in a way you do not expect, run it on its own like this before you put it into a bigger query.
Expressions and grouping
Once a query has GROUP BY or an aggregate, every plain column in the SELECT list must be either grouped or used inside an aggregate. Expressions are checked by the same rule.
SELECT department_id,
COUNT(*) AS headcount,
AVG(salary) * 12 AS avg_annual_salary
FROM employees
GROUP BY department_id;AVG(salary) * 12 is valid. The aggregate is computed per group first, and the multiplication is applied to its result. By contrast, SELECT department_id, salary * 12 ... GROUP BY department_id is an error in standard SQL. salary is neither grouped nor aggregated, so there is no single value to use for the group.
The order inside the expression matters for the result. SUM(salary * 12) multiplies each row first and then adds. SUM(salary) * 12 adds first and then multiplies. With plain multiplication these two give the same total. With SUM(salary / 12) and integer salaries they can differ, because each division can lose a fraction before the sum.
Common errors
These are the mistakes that show up most often when people start writing computed columns.
- Using an alias too early.
SELECT salary * 12 AS annual_salary FROM employees WHERE annual_salary > 100000fails in standard SQL, becauseWHEREruns before theSELECTlist. Repeat the expression or use a subquery. The alias chapters cover this fully. - Unexpected integer division.
total / countwith two integer columns drops the fraction in many products. Cast one side, or multiply by1.0. - NULL spreading through arithmetic.
salary + commissionis NULL for any row wherecommissionis NULL. The NULL chapter explains why, and theCOALESCEchapter shows the fix. - Division by zero.
x / 0raises an error in most products.NULLIF(divisor, 0)turns the zero into NULL so the result is NULL instead of an error. - Mixing incompatible types. Adding text to a number either fails or triggers an implicit conversion, depending on the product.
'10' + 5is15in MySQL and SQL Server, and an error in PostgreSQL. Convert explicitly withCAST. - Ungrouped columns beside aggregates. See the grouping section above.
Reading the result column names
When you do not give an expression a name, the database invents one. The invented names vary a great deal.
| Product | Name for `salary * 12` with no alias |
|---|---|
| PostgreSQL | `?column?` |
| MySQL | `salary * 12` |
| SQL Server | no name (blank) |
| Oracle | `SALARY*12` |
| SQLite | `salary * 12` |
Application code that reads columns by name will break if it depends on a generated name. Give every computed column an explicit alias. The next chapters build on that habit.
Check your understanding
Exercise
A table orders has the integer columns items_total and item_count. The query SELECT items_total / item_count AS avg_item FROM orders returns 3 for a row where items_total is 10 and item_count is 3, in PostgreSQL. Why, and how do you get 3.33? Also, in which logical step is the expression evaluated relative to WHERE?
Show answer
Both columns are integers, so PostgreSQL performs integer division and drops the fraction. Cast or scale one operand, for example items_total / CAST(item_count AS DECIMAL(10, 2)) or items_total * 1.0 / item_count, and round if you want two places. The expression is evaluated in the SELECT step, after FROM and WHERE, so it is computed only for rows that passed the WHERE filter.
Exercise
Why does SELECT department_id, salary * 12 FROM employees GROUP BY department_id fail in standard SQL, and what are two ways to fix it?
Show answer
After grouping, the query returns one row per department, but salary has many values within a department and is neither grouped nor aggregated. Fix it by aggregating, for example SUM(salary) * 12 or AVG(salary) * 12, or by adding salary to the GROUP BY list if you want one row per distinct salary within each department.