Part 03 / Topic 6 of 9
Numeric functions
Rounding and friends:
SELECT round(123.456, 2) AS rounded,
round(123.456) AS to_integer,
ceil(4.1) AS ceiling,
floor(4.9) AS floored,
abs(-7) AS absolute,
mod(17, 5) AS remainder;
rounded | to_integer | ceiling | floored | absolute | remainder
---------+------------+---------+---------+----------+-----------
123.46 | 123 | 5 | 4 | 7 | 2
(1 row)
And the Part 1 trap, now with its professional fix — integer division truncates, so cast one side before dividing:
SELECT 7 / 2 AS int_division,
7 / 2.0 AS numeric_division,
round(7::numeric / 3, 2) AS rounded;
int_division | numeric_division | rounded
--------------+--------------------+---------
3 | 3.5000000000000000 | 2.33
(1 row)
That x::numeric / y pattern appears in every percentage you will ever compute: round(100.0 * part / NULLIF(whole, 0), 1) — decimal forced, zero guarded, tidily rounded. Earmark it.
🧪 Quick quiz — answer from memory, then check.
round(2.5)in Postgresnumericrounds to…? (Try it!)- Write "cancelled orders as a % of all orders" safely, given counts
candn.
Show the answers
3— numeric rounds halves away from zero in PostgreSQL.round(100.0 * c / NULLIF(n, 0), 1).
Done here? The practice set for Part 3 — 7 exercises with solutions — is on the part page.