Math FunctionsOptional for Computer Science
A single-row function works on one value and gives back one value — unlike an aggregate, which swallowed a whole column. Three of them are arithmetic, and one has a trick in it.
1You can try a function on its own
A select does not need a table when there is nothing to look up. That makes these functions easy to experiment with:
Two to the power three. The heading is the expression, as always with a calculated column.
2POWER(m, n) — m raised to n
power(2,3) is 8 and power(3,2) is 9. The first number is the base, the second is the exponent — base first, exactly as you would read “2 to the power 3”. Swapping them is an easy mark to lose.And anything to the power 0 is 1, which MySQL agrees with. The function is also spelled pow(); both work.
3ROUND(value, d) — round to d decimal places
Three places keeps 3.167; two places rounds the 4-then-5 up to 3.17. Ordinary rounding, doing what you expect.
With 0 as the second argument you get a whole number:
4The trick: a negative second argument
This is the part nobody guesses. A negative number of places rounds to the left of the decimal point — to the nearest ten, the nearest hundred, and so on:
two places after the point
nearest ten (373 → 370)
nearest hundred (373 → 400)
Read the second argument as a position: positive counts places to the right of the decimal point, negative counts to the left. Zero is the point itself.
5MOD(m, n) — the remainder
21 ÷ 6 is 3 remainder 3, and mod() returns the remainder, not the quotient. It is the same job as % in Python.
The case worth checking is when the first number is smaller than the second:
13 does not go into 10 at all, so nothing is taken away and the whole 10 is left over. Whenever m < n, mod(m, n) is just m.
mod(n, 2) = 0 means n is even; mod(id, 5) = 0 picks every fifth record. A where clause can use a function just as easily as a column.6Recap
m to the power n. Base first — power(2,3) is 8.
d places after the point.
Rounds to the left: -1 is the nearest ten, -2 the nearest hundred.
The remainder. If m < n the answer is m.
What does select power(3, 2); return?
What does select round(373.8898745, -2); return?
What does select mod(10, 13); return?