Reading history

SQL Math Functions: ROUND, CEIL, FLOOR, ABS and MOD

5 min read 0 views

Learn SQL math functions with examples: ROUND, CEIL, FLOOR, ABS, POWER, SQRT and the % (MOD) operator, plus the integer division and floating-point rounding traps.

Reports are full of calculations: prices with VAT, average marks, boxes needed for an order, percentages rounded to one decimal place. SQL has a small set of math functions and operators for this work. Most of them behave as you expect, but integer division and floating-point rounding catch out many beginners. This lesson shows each function with real output and points out those traps.

In this lesson you will learn

  • Rounding with ROUND, CEIL and FLOOR
  • Arithmetic operators, including % (modulo)
  • Why 7 / 2 can give 3 instead of 3.5
  • ABS, POWER and SQRT
  • Using math in real queries: VAT, averages and even/odd checks

The examples use the students, orders and enrollments tables from earlier lessons. You should already know aggregate functions such as SUM and AVG.

Rounding and Basic Math

-- Rounding a value up, down and to the nearest
SELECT name, cgpa,
       ROUND(cgpa, 1) AS round_1dp,
       ROUND(cgpa)    AS round_whole,
       CEIL(cgpa)     AS ceil,
       FLOOR(cgpa)    AS floor
FROM students
WHERE cgpa IS NOT NULL
ORDER BY cgpa DESC
LIMIT 4;

-- Integer division, remainder, absolute value and powers
SELECT 7 / 2       AS int_div,
       7 / 2.0     AS real_div,
       7 % 3       AS remainder,
       ABS(-15)    AS absolute,
       POWER(2, 10) AS two_pow_10,
       ROUND(SQRT(2), 4) AS root_2;

Output

+--------+------+-----------+-------------+------+-------+
| name   | cgpa | round_1dp | round_whole | ceil | floor |
+--------+------+-----------+-------------+------+-------+
| Tania  | 3.95 | 4.0       | 4.0         | 4.0  | 3.0   |
| Nusrat | 3.82 | 3.8       | 4.0         | 4.0  | 3.0   |
| Mitu   | 3.67 | 3.7       | 4.0         | 4.0  | 3.0   |
| Sabbir | 3.55 | 3.5       | 4.0         | 4.0  | 3.0   |
+--------+------+-----------+-------------+------+-------+
(4 rows)

+---------+----------+-----------+----------+------------+--------+
| int_div | real_div | remainder | absolute | two_pow_10 | root_2 |
+---------+----------+-----------+----------+------------+--------+
| 3       | 3.5      | 1         | 15       | 1024.0     | 1.4142 |
+---------+----------+-----------+----------+------------+--------+
(1 row)
  • ROUND(x, n) rounds to n decimal places. With no second argument it rounds to a whole number, so 3.55 becomes 4.0.
  • CEIL (or CEILING) always rounds up to the next whole number, and FLOOR always rounds down. Every CGPA here lies between 3 and 4, so they give 4 and 3.
  • 7 / 2 returns 3 because both numbers are integers, so the database does integer division and drops the fraction. Writing 2.0 makes it real division: 3.5.
  • % gives the remainder after division, so 7 % 3 is 1. MySQL, PostgreSQL and Oracle also offer MOD(7, 3).
  • ABS removes the minus sign, POWER(a, b) raises a to the power b, and SQRT returns the square root.

Math in Real Queries

-- Order amounts with 15% VAT, rounded to whole taka
SELECT id, amount,
       ROUND(amount * 1.15) AS with_vat,
       amount % 500         AS rem_500,
       CEIL(amount / 500.0) AS boxes_of_500
FROM orders
WHERE amount IS NOT NULL
ORDER BY id
LIMIT 5;

-- Average marks: integer arithmetic vs real arithmetic
SELECT SUM(marks) / COUNT(*)              AS int_average,
       ROUND(SUM(marks) * 1.0 / COUNT(*), 2) AS real_average,
       ROUND(AVG(marks), 2)                AS avg_function
FROM enrollments;

-- Even and odd ids with MOD
SELECT id, name, CASE WHEN id % 2 = 0 THEN 'even' ELSE 'odd' END AS parity
FROM students
WHERE id <= 4;

Output

+----+--------+----------+---------+--------------+
| id | amount | with_vat | rem_500 | boxes_of_500 |
+----+--------+----------+---------+--------------+
| 1  | 1200   | 1380.0   | 200     | 3.0          |
| 2  | 450    | 518.0    | 450     | 1.0          |
| 3  | 800    | 920.0    | 300     | 2.0          |
| 4  | 2300   | 2645.0   | 300     | 5.0          |
| 5  | 650    | 747.0    | 150     | 2.0          |
+----+--------+----------+---------+--------------+
(5 rows)

+-------------+--------------+--------------+
| int_average | real_average | avg_function |
+-------------+--------------+--------------+
| 82          | 82.56        | 82.56        |
+-------------+--------------+--------------+
(1 row)

+----+--------+--------+
| id | name   | parity |
+----+--------+--------+
| 1  | Nusrat | odd    |
| 2  | Arif   | even   |
| 3  | Tania  | odd    |
| 4  | Imran  | even   |
+----+--------+--------+
(4 rows)
  • Order 5 is 650 taka, and 650 × 1.15 is exactly 747.5, yet ROUND gives 747. The reason is that 1.15 cannot be stored exactly as a floating-point number, so the product is really 747.4999…, which rounds down. For money, store amounts as whole paisa or use a DECIMAL type, covered in the data types lesson.
  • amount % 500 shows what is left over after whole blocks of 500, and CEIL(amount / 500.0) counts how many boxes of 500 you need. Note the 500.0; with 500 the integer division would happen before CEIL could round up.
  • SUM(marks) / COUNT(*) divides two integers and gives 82, losing the fraction. Multiplying by 1.0 first, or using AVG, gives the correct 82.56.
  • id % 2 = 0 is the usual way to test for even numbers, here combined with a CASE expression.

Math Functions at a Glance

FunctionExampleResult
ROUND(x, n)ROUND(3.456, 2)3.46
CEIL(x)CEIL(2.1)3
FLOOR(x)FLOOR(-2.1)-3
ABS(x)ABS(-15)15
x % y / MOD(x, y)17 % 52
POWER(x, y)POWER(3, 2)9
SQRT(x)SQRT(16)4

FLOOR(-2.1) is -3, not -2, because rounding down means moving towards negative infinity. SQL Server writes CEILING and uses POWER; SQLite needs a build with math functions enabled, which most current versions have.

Common Mistakes

  1. Dividing two integers and losing the fraction. Make one side a decimal, such as * 1.0.
  2. Comparing floating-point results with =. Round first, or compare the difference with a small tolerance.
  3. Storing money in REAL/FLOAT columns, which leads to rounding surprises.
  4. Forgetting that NULL in arithmetic gives NULL; the order with an unknown amount was filtered out above for this reason.

Practice Exercises

Exercise 1. Show each delivered order’s amount and the 5% discount, rounded down to a whole taka.

Show answer
SELECT id, amount, FLOOR(amount * 0.05) AS discount
FROM orders
WHERE status = 'delivered';

Exercise 2. Show what percentage of students are in each department, to one decimal place.

Show answer
SELECT dept,
       ROUND(COUNT(*) * 100.0 / (SELECT COUNT(*) FROM students), 1) AS pct
FROM students
GROUP BY dept;

The 100.0 makes the division real; with 100 it would be integer division.

Frequently Asked Questions

How does SQL round a value that ends in exactly .5?

Most databases, including SQLite, MySQL and PostgreSQL for decimal values, round half away from zero, so 2.5 becomes 3 and -2.5 becomes -3. Floating-point values may not be exactly .5 internally, so check results for money.

What is the difference between TRUNCATE and FLOOR?

FLOOR rounds towards negative infinity, while truncating simply cuts off the decimals (MySQL TRUNCATE(x, 0), PostgreSQL TRUNC(x)). They differ only for negative numbers: -2.7 floors to -3 but truncates to -2.

Summary

  • ROUND, CEIL and FLOOR control rounding.
  • Integer divided by integer drops the fraction; use a decimal on one side.
  • % gives remainders, useful for even/odd and grouping checks.
  • Floating-point values are approximate; keep money in exact types.

Next: SQL Data Types.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *