ROUND example
We work out a price with an extra 21 % and round the result to two decimal places:
SELECT name,
price,
ROUND(price * 1.21, 2) AS price_with_vat
FROM products
ORDER BY id
LIMIT 6;Check the result with small data
The amounts have three decimal places and we want to show two.
WITH accounts(name, amount) AS (
VALUES ('A',12.345),('B',8.999)
)
SELECT name, ROUND(amount,2) AS rounded
FROM accounts ORDER BY name;| name | rounded |
|---|---|
| A | 12.35 |
| B | 9 |
ROUND changes the precision of the numeric result; it does not change the stored amount. For money calculations, check your engine's decimal type.
Check your understanding: Why is it better to round at the end of a sum rather than rounding every row?
Show answer
Because each intermediate rounding introduces a small error and those errors add up. If you add with full precision and round only the total, the result is closer to the real amount.
How ROUND is used
Without the second argument, engines usually round to the nearest whole number. The accepted types and the rules for negative positions can vary.
Common mix-ups with ROUND
Rounding before the calculation is finished
SUM(ROUND(unit_price * quantity, 2))Rounding each row and then adding up can give a different total from adding at full precision and rounding at the end. The right rule depends on the accounting problem, but it should be deliberate.
Key differences between engines
SQLite, PostgreSQL and MySQL include ROUND, but numeric types, precision and support for negative positions are not identical. For financial calculations, also check the column type: an exact decimal and a floating-point number do not behave the same.