Expressions, functions and CASE
069 min
SELECT does more than show columns — it calculates. This lesson covers arithmetic, working with text and “if … then” with CASE.
Arithmetic
+ - * / and % (remainder) all work:
Watch out when dividing a whole number by a whole number. In PostgreSQL
7 / 2=3(the fraction is dropped), while MySQL gives3.5000. If you need a fraction, make one of the numbers a decimal:7 * 1.0 / 2.
Rounding: ROUND
ROUND(number, n) rounds to n decimal places. There are also CEIL (up) and FLOOR (down).
Text functions
| Function | What it does |
|---|---|
UPPER(s) / LOWER(s) |
upper / lower case |
LENGTH(s) |
number of characters |
TRIM(s) |
removes spaces at the start and end |
SUBSTRING(s, 1, 3) |
3 characters starting at the 1st |
REPLACE(s, 'a', 'b') |
replace |
Joining strings:
In PostgreSQL use the || operator or the CONCAT function:
Calculating with NULL: COALESCE
Any calculation involving NULL gives NULL: 5 + NULL = NULL. COALESCE(a, b) takes b when a is empty:
CASE — “if … then”
The conditions are checked top to bottom and the first match wins. If none matches, ELSE is used, and if there is no ELSE, the result is NULL.
Show each product’s name and the total value of its stock (price * stock).
Show drivers’ first_name and a category by rating: 4.8 and above — 'top', the rest — 'oddiy', and those without a rating — 'yangi'.
Remember
- You can calculate inside
SELECT; be careful when dividing whole numbers. COALESCE(x, 0)puts a value in place ofNULL.CASE WHEN … THEN … ELSE … ENDpicks a value by condition.