Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

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.

  1. round(2.5) in Postgres numeric rounds to…? (Try it!)
  2. Write "cancelled orders as a % of all orders" safely, given counts c and n.
Show the answers
  1. 3 — numeric rounds halves away from zero in PostgreSQL.
  2. 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.

Search the guide