Sub topic 1
Computing Values in the SELECT List
Prerequisites
This chapter assumes you can write SELECT ... FROM ... WHERE queries, that you know the common column types (numbers, text, and dates), and that you have seen GROUP BY and aggregate functions such as COUNT and SUM. You should also know that NULL marks a missing value.
Computing Values in the SELECT List
The SELECT list can hold expressions, not only column names. The database evaluates each expression once per row and returns the result as a column. The table itself does not change.
SELECT first_name,
last_name,
salary,
salary * 12 AS annual_salary
FROM employees;Literals and Operators
A literal is a fixed value written in the query, such as 5 or 'USD'. Text literals use single quotes. Numeric literals do not.
| Operator | Example | Meaning |
|---|---|---|
| + | salary + 500 | Add 500 to each salary |
| - | salary - tax | Subtract a column from another |
| * | salary * 12 | Multiply each salary by 12 |
| / | salary / 2 | Divide each salary by 2 |
Integer division can surprise you. In many databases, 7 / 2 returns 3. Write 7.0 / 2 to get 3.5.
Scalar Functions Inside Expressions
A scalar function takes one value per row and returns one value per row. Examples include ROUND and UPPER. You can nest them inside any expression.
SELECT UPPER(last_name) AS last_name_upper,
ROUND(salary * 1.05, 2) AS raised_salary
FROM employees;How NULL Behaves in Expressions
NULL means unknown, not zero. Arithmetic with NULL returns NULL. A comparison with NULL is neither true nor false, so filters skip those rows.
SELECT first_name,
salary + commission AS total_pay
FROM employees;> The rows with a NULL commission show NULL in total_pay, not the salary. Missing values need handling, which this tutorial covers later.
Exercise
Exercise
An employee has a NULL commission. What does salary + commission return for that row?
Show answer
NULL. Any arithmetic involving NULL returns NULL.