Sub topic 2
COALESCE and NULLIF
This chapter assumes you can write SELECT ... FROM ... WHERE queries, you know that NULL marks a missing value, and you have used aggregates such as COUNT and SUM.
Handling missing values with COALESCE
COALESCE(a, b, ...) returns its first argument that is not NULL. Any arithmetic with NULL also returns NULL, so a missing commission would erase the whole total unless you replace it.
SELECT first_name,
salary + COALESCE(commission, 0) AS total_pay
FROM employees;Avoiding division by zero with NULLIF
NULLIF(a, b) returns NULL when a equals b, and otherwise returns a. Dividing by NULL gives NULL, while dividing by zero raises an error in most databases.
SELECT total_revenue / NULLIF(order_count, 0) AS avg_order_value
FROM sales_summary;Naming results with column aliases
AS gives a computed column a name. The alias becomes the column heading in the result.
SELECT employee_id,
salary * 12 AS annual_salary
FROM employees
ORDER BY annual_salary DESC;Where an alias can and cannot be used
An alias is created in the SELECT list. The database runs clauses in a fixed order, so an alias exists only for clauses that run after SELECT.
Because WHERE runs before SELECT, standard SQL does not allow an alias in WHERE. Use a subquery to name the value first, then filter in the outer query:
SELECT employee_id, annual_salary
FROM (
SELECT employee_id, salary * 12 AS annual_salary
FROM employees
) AS e
WHERE annual_salary > 100000;Searched CASE: WHEN condition THEN result
A searched CASE tests each WHEN condition in order and returns the result of the first true one. If none is true and there is no ELSE, the result is NULL.
SELECT first_name,
salary,
CASE
WHEN salary >= 100000 THEN 'high'
WHEN salary >= 50000 THEN 'medium'
ELSE 'low'
END AS salary_band
FROM employees;Test for missing values with IS NULL. The condition commission = NULL never returns true.
SELECT first_name,
CASE
WHEN commission IS NULL THEN 'no commission'
ELSE 'has commission'
END AS commission_status
FROM employees;Exercise
An employee has salary 5000 and a NULL commission. What does the total_pay expression salary + COALESCE(commission, 0) return for that employee?
Show answer
5000. COALESCE replaces the NULL commission with 0, so the addition works.