Expressions & Functions
Calculate new values in a query with arithmetic, text functions and COALESCE, and learn how NULL spreads.
Compute values inside the query
An expression combines values with operators and functions to make a new value. You can use one in the select list, in WHERE, or in ORDER BY.
Arithmetic uses +, -, *, / and % (the remainder). Text uses || to join pieces, and functions such as upper(), lower() and length().
coalesce(a, b, c) returns the first argument that is not NULL. It is the standard way to give a default.
Let the database do the work
Computing in the query means every program that reads the data gets the same answer, and you send one finished value over the network instead of several raw ones.
Three small examples
SELECT name,
points / 2 AS half,
name || ' (' || team || ')' AS label,
coalesce(points, 0) AS points_or_zero
FROM players;Asha has 31 points, so half is 15, not 15.5. When both numbers are whole, / gives a whole number, cut toward zero. If you want decimals, one side must be a decimal number: 5.0 / 2 gives 2.5000000000000000.
length() counts characters, so length('Asha') is 4. upper('Asha') is ASHA.
Compute a new column
Pick an expression and read the result column for every player. Compare || with concat() on the players who have no points.
| nametext | pointsinteger | resultinteger |
|---|---|---|
| Asha | 31 | 41 |
| Ben | 17 | 27 |
| Chen | NULL | NULL |
| Dara | 24 | 34 |
| Eli | NULL | NULL |
| Fay | 24 | 34 |
| Gus | 40 | 50 |
| Hana | 17 | 27 |
Arithmetic works on every row. A NULL in any calculation makes the whole result NULL.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Expressions combine values with operators and functions, and are worked out once per row.
- Two whole numbers divide to a whole number: 5 / 2 is 2.
- A NULL in arithmetic or in || makes the whole result NULL.
- concat() ignores NULL, and coalesce() returns its first argument that is not NULL.
Done with this concept?
Mark it complete to track your progress. No login needed.