Learning navigation

Code with Animation

Expressions & Functions

Calculate new values in a query with arithmetic, text functions and COALESCE, and learn how NULL spreads.

SQL6 min readConcept 11 of 44

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.

SELECT name, points, points + 10 AS result
FROM players;
Result (8 rows)
nametextpointsintegerresultinteger
Asha3141
Ben1727
ChenNULLNULL
Dara2434
EliNULLNULL
Fay2434
Gus4050
Hana1727

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.

  1. 1In PostgreSQL, what is `5 / 2` when both numbers are whole numbers?
  2. 2Chen's points are NULL. What is `name || ' scored ' || points` for Chen?
  3. 3What does `coalesce(points, 0)` return for a player whose points are NULL?

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.