Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 30/ 160
02. Aggregations, Functions & Data Manipulation

Numeric & Math Functions (ROUND, CEIL, FLOOR, ABS, MOD, POWER)

Round, bucket, and transform numbers for reporting and feature engineering.

BeginnerROUND / CEIL / FLOOR · ABS / MOD3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Math functions round numbers, remove signs, find remainders and group numbers into ranges.

Think of it like…

A shopkeeper's tools: rounding a bill to the nearest rupee (ROUND), packing items into boxes of ten and counting full boxes (FLOOR of a division), and counting what's left over (MOD).

Where you’ve seen it

Price bands for a report: SELECT FLOOR(price / 500) * 500 AS band_start, COUNT(*) FROM products GROUP BY 1 ORDER BY 1; puts ₹0–499 in band 0, ₹500–999 in band 500, and so on.

Words you’ll hear

ROUND(x, n)
Rounds to n decimal places; tie behaviour depends on the type.
CEIL / FLOOR
Round up / down to the nearest integer (FLOOR(-2.5) = -3).
MOD(a, b) / %
Remainder of a ÷ b; its sign follows a.
WIDTH_BUCKET
Assigns a value to one of N equal-width buckets (PostgreSQL, Oracle).

Visual diagram

Loading interactive diagram

Theory & example queries

Rounding correctly

ROUND(x, n) rounds to n decimal places; n can be negative (ROUND(1249, -2) = 1200). In PostgreSQL, rounding a numeric value breaks ties away from zero (2.5 → 3, -2.5 → -3), while rounding a double precision value usually rounds half to even (2.5 → 2), so the same-looking query can give different answers depending on the column type. Money should be numeric for this reason too.

CEIL rounds up and FLOOR rounds down, towards positive and negative infinity respectively, so FLOOR(-2.5) is -3 and CEIL(-2.5) is -2, while TRUNC(-2.5) is -2 because it simply drops the decimals. Rounding each line of an invoice and then summing can differ from rounding the total, so decide which one the business rule wants.

Same value, different roundingQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  ROUND(2.5::numeric) AS numeric_round,3  ROUND(2.5::float8) AS float_round,4  FLOOR(-2.5) AS floor_neg,5  TRUNC(-2.5) AS trunc_neg;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/5
3OutputInspect the representative rows, affected-row count, plan, or command status.
PostgreSQL result1 sample row
PostgreSQL result
numeric_roundfloat_roundfloor_negtrunc_neg
32-3-2

Note: Values follow the PostgreSQL numeric-versus-double rounding rules described in the lesson; another database may use different tie behavior.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

returns 3, 2, -3 and -2 in PostgreSQL.

Key takeaway: Know your type's tie rule; FLOOR and TRUNC differ for negatives.

Bucketing, remainders and other helpers

To group values into fixed-width ranges, divide, floor and multiply back: FLOOR(amount / 500) * 500 gives the start of each ₹500 band. PostgreSQL's WIDTH_BUCKET(amount, 0, 5000, 10) assigns values to 10 equal buckets between 0 and 5,000, with out-of-range values in bucket 0 or 11. MOD gives remainders, useful for every-nth-row sampling (WHERE MOD(id, 10) = 0) and cycles; its result has the sign of the dividend, so MOD(-7, 3) is -1.

GREATEST and LEAST pick the largest or smallest of several values; in PostgreSQL they ignore NULLs, while in MySQL any NULL argument makes the result NULL. When percentages are rounded individually they often add up to 99 or 101; if a report must total 100, round the parts and give the remainder to the largest one.

Order value bandsQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  WIDTH_BUCKET(amount, 0, 5000, 5) AS bucket,3  MIN(amount),4  MAX(amount),5  COUNT(*)6FROM7  orders8GROUP BY9  110ORDER BY11  1;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/11
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative order bands4 sample rows
Representative order bands
bucketminmaxcount
12509503
2110019004
3225029502
4310049003

Note: Sample amounts are illustrative. WIDTH_BUCKET returns 0 or 6 for values outside the 0–5000 range, so real output can contain those extra groups.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: FLOOR(x / width) * width or WIDTH_BUCKET for bands; MOD for remainders.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Types

Check the column type

Numeric and floating-point values round differently, and integers divide without decimals.

Focus at this step

amount numeric(12,2) vs ratio float8

What to watch at this step
Money
numeric
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

SQL's math functions shape numbers for reports and analysis. ROUND(x, n) rounds to n decimal places, CEIL and FLOOR round up or down to whole numbers, TRUNC cuts off decimals, ABS removes the sign, MOD (or %) gives the remainder, and POWER, SQRT, LN and LOG do the rest. Together with integer division, they're also the standard tools for bucketing values into ranges.

Why it matters: Price bands, rounding for invoices, percentages that should add up to 100, every-nth-row sampling: small numeric details decide whether totals reconcile. Rounding rules differ between data types and databases, which is a classic source of off-by-a-paisa bugs.

When to reach for it

  • Price and amount bands in reports
  • Rounding money and percentages for display
  • Sampling every nth row with MOD

When to avoid or be careful

  • Rounding floating-point money values
  • Rounding every line and the total separately without deciding which is authoritative
  • Assuming FLOOR and TRUNC are the same for negative numbers

ROUND vs TRUNC vs FLOOR/CEIL

ROUND
Best for: Displaying values and money to a fixed precision

Strengths: Nearest value; supports decimal places.

Watch out: Tie rules differ between numeric and float types.

TRUNC
Best for: Dropping decimals without rounding

Strengths: Predictable: just cuts digits.

Watch out: Always moves towards zero, which biases totals.

FLOOR / CEIL
Best for: Bucketing and "how many full boxes" questions

Strengths: Consistent direction, including for negatives.

Watch out: Only to whole numbers (scale first for decimals).

Interview signals & numbers to know

When this topic comes up

  • “Group prices into ranges”
  • “The total is off by one paisa”
  • “Percentages add up to 101%”
  • Rounding rules
  • Feature engineering

Benchmarks & rules of thumb

ROUND(2.5::numeric) -
= 3
FLOOR(-2.5) -
= -3; TRUNC(-2.5) = -2
MOD(-7, 3) -
= -1

Common mistakes & follow-ups

Common interview mistakes

  • Using FLOOR on negative amounts (refunds) and getting bands one lower than expected.
  • Getting 0% everywhere because ROUND(100 * a / b) used integer division.
  • Expecting GREATEST(a, NULL) to return a in MySQL; it returns NULL.

Likely interviewer follow-ups

  • How would you group order amounts into ₹500 bands?
  • Why might ROUND(2.5) return 2 in one query and 3 in another?
  • How do you make rounded percentages add up to 100?
Interview tip: Show the bucketing formula and mention the numeric-vs-float rounding difference. That combination shows both practical use and attention to detail.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Numeric & Math Functions (ROUND, CEIL, FLOOR, ABS, MOD, POWER) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
String Splitting & Pattern Extraction (SPLIT_PART, POSITION, LENGTH)
Next topic
Date & Time Extraction (EXTRACT, DATE_PART, DATE_TRUNC)