Every once in a while, I find myself needing to round a number up to the nearest even power of 10, or round a time interval to the nearest quarter of an hour, or something like that. This is actually quite simple, but for some reason I always find myself confused about how to do it. I have to reason it out all over again, instead of just remembering how to do it. Perhaps writing this blog post will help me remember next time.
The basic idea for rounding to whole multiples is to divide the number, losing precision. Then round, floor, or ceiling the resulting number, and multiply to get back to the original magnitude. For rounding to fractions, reverse the process: multiply, round and divide again.
This actually works for any programming language, not just SQL. But I find myself doing it in SQL most often.
Here’s an example of how to turn a year into a decade:
mysql> SELECT FLOOR(YEAR(NOW()) / 10) * 10 AS …[Read more]