Chapter 5. Number Crunching
A little arithmetic can go a long way in SQL. The language
includes the math functions that you would expect to find in any computer
language, plus a few that are peculiar to databases. It includes functions
such as ISNULL
, COALESCE
, and NULLIF
, which help to deal with NULL
s. It also includes the aggregating functions such as COUNT
, SUM
,
MAX
, MIN
, and AVG
that are used in GROUP
BY
queries.
Multiply Across a Result Set
With certain calculations, such as compound interest, you need to multiply a set of values. How come there’s no PRODUCT aggregate function that is to multiplication as SUM is to addition?
SQL has no aggregate function for multiplication, but you can use logarithms to achieve the desired result. When you add the logarithms of a list of numbers you get the same result you would get if you had taken the logarithm of their product:
log(a) + log(b) + log(c) = log(a*b*c) |
The inverse of the logarithm is the exponent function:
exp(log(a) + log(b) + log(c)) = a*b*c |
So, to multiply the values 3
,
4
, and 5
without using multiplication, you could do
the following:
mysql> select exp( ln(3)+ln(4)+ln(5) );
+------------------------+
| exp(ln(3)+ln(4)+ln(5)) |
+------------------------+
| 60 |
+------------------------+
You can also use this technique to achieve the same effect as a
PRODUCT()
aggregate function.
Suppose you have invested $100 in a savings account that has produced
the interest rates shown in Table 5-1.
yr | rate |
2002 ... |
Get SQL Hacks now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.