Numeric Functions
Perform mathematical calculations using ROUND, TRUNC, CEIL, FLOOR, ABS, MOD, and POWER.
In this lesson, you will learn
- ✓Understand how numeric functions transform numbers in SQL
- ✓Round decimal values using ROUND
- ✓Remove decimal digits using TRUNC without rounding
- ✓Calculate upper and lower integer bounds using CEIL and FLOOR
- ✓Calculate absolute values and remainders using ABS and MOD
- ✓Perform exponentiation using POWER
- ✓Handle NULL values and understand numeric precision
- ✓Apply numeric functions in pricing, reporting, and data analysis queries
1. Introduction to Numeric Functions
Numeric functions allow SQL to perform mathematical operations directly inside a query. Instead of retrieving raw values and performing every calculation in your application, you can calculate, round, or transform numbers in the database.
For example, an online store may need to calculate discounted prices, a reporting system may need to round averages, and an analytics application may need to calculate remainders or powers.
This lesson uses PostgreSQL syntax. Some numeric functions exist in other database systems too, but their supported argument types and exact behavior can differ.
The main functions in this lesson are:
- ROUND: rounds a number to a specified precision.
- TRUNC: removes digits beyond a specified precision without rounding.
- CEIL: returns the smallest integer greater than or equal to a number.
- FLOOR: returns the largest integer less than or equal to a number.
- ABS: returns the absolute value.
- MOD: returns the remainder of division.
- POWER: raises a number to an exponent.
2. ROUND: Rounding Numbers
ROUND rounds a numeric value to the nearest value at the requested precision.
Syntax:
ROUND(number)
ROUND(number, decimal_places)
The second argument is optional for numeric values. If omitted, the result is rounded to zero decimal places.
Examples:
Using ROUND
ROUND returns 12.35 at two decimal places, 12.3 at one decimal place, and 12 when rounded to a whole number. The numeric cast makes the example's decimal behavior explicit.
3. Understanding ROUND with Positive and Negative Precision
The second argument of ROUND controls the position at which rounding occurs.
- ROUND(value, 2): rounds to two digits after the decimal point.
- ROUND(value, 1): rounds to one digit after the decimal point.
- ROUND(value, 0): rounds to a whole number.
- ROUND(value, -1): rounds to the nearest ten.
- ROUND(value, -2): rounds to the nearest hundred.
Example:
Rounding to Tens and Hundreds
A negative precision rounds digits to the left of the decimal point. PostgreSQL's ROUND behavior for NUMERIC is used here.
4. TRUNC: Removing Decimal Digits
TRUNC removes digits beyond a specified decimal position without rounding the remaining digits.
Syntax:
TRUNC(number)
TRUNC(number, decimal_places)
Compare ROUND(8.789, 2) with TRUNC(8.789, 2):
- ROUND produces 8.79.
- TRUNC produces 8.78.
TRUNC is useful when the requirement is to discard extra decimal digits rather than round the value.
ROUND Versus TRUNC
TRUNC removes digits after the requested precision. For negative numbers, it truncates toward zero rather than rounding toward negative infinity.
5. ROUND and TRUNC with Negative Precision
ROUND and TRUNC can also operate on digits to the left of the decimal point.
For example:
- ROUND(146, -1) rounds to the nearest ten.
- TRUNC(146, -1) removes the ones digit.
- ROUND(146, -2) rounds to the nearest hundred.
- TRUNC(146, -2) removes the tens and ones digits.
Example:
Negative Precision
TRUNC discards the specified digits. ROUND considers the next digit when determining the rounded result.
6. CEIL: Rounding Up to an Integer
CEIL, also written CEILING, returns the smallest integer greater than or equal to the input.
Syntax:
CEIL(number)
CEILING(number)
Examples:
- CEIL(4.2) returns 5.
- CEIL(4.0) returns 4.
- CEIL(-4.2) returns -4.
Important: CEIL does not simply increase every number by one. If the input is already an integer, it remains unchanged.
Using CEIL
CEIL returns the smallest integer that is not less than the input value.
7. FLOOR: Rounding Down to an Integer
FLOOR returns the largest integer less than or equal to the input.
Syntax:
FLOOR(number)
Examples:
- FLOOR(4.8) returns 4.
- FLOOR(4.0) returns 4.
- FLOOR(-4.2) returns -5.
A common misunderstanding is that FLOOR always removes the decimal part. That is not correct for negative values. FLOOR moves toward negative infinity, while TRUNC moves toward zero.
FLOOR Versus TRUNC
For negative non-integers, FLOOR and TRUNC produce different results because they follow different rules.
8. CEIL Versus FLOOR
CEIL and FLOOR are useful when converting a fractional quantity into an integer bound.
| Input | CEIL | FLOOR |
|---:|---:|---:|
| 3.2 | 4 | 3 |
| 3.0 | 3 | 3 |
| -3.2 | -3 | -4 |
| -3.0 | -3 | -3 |
Example: If 23 people need transport and each vehicle can carry 5 people, CEIL(23.0 / 5) returns 5 vehicles. FLOOR(23.0 / 5) returns 4, which is not enough for everyone.
Use CEIL when every partial group needs a full unit. Use FLOOR when only complete units count.
Calculating Required Vehicles
Five vehicles are required because four vehicles can carry only 20 people.
9. ABS: Absolute Value
ABS returns the absolute value of a number. The absolute value represents the number's distance from zero and is never negative.
Syntax:
ABS(number)
Examples:
- ABS(7) returns 7.
- ABS(-7) returns 7.
- ABS(0) returns 0.
ABS is useful for calculating the size of a difference without caring about its sign, such as the difference between an expected amount and an actual amount.
Using ABS
ABS converts a negative number to its non-negative magnitude. It does not change an already non-negative value.
10. Practical Example: Finding Large Differences
Suppose an inventory system stores expected and actual stock counts. ABS can calculate the magnitude of the discrepancy.
The following query assumes an inventory table with expected_stock and actual_stock columns.
Inventory Discrepancy
The query calculates the absolute difference for each product and sorts the largest discrepancies first. The output is illustrative; the inventory table must exist with the referenced columns.
11. MOD: Finding the Remainder
MOD returns the remainder after dividing one number by another.
Syntax:
MOD(dividend, divisor)
For example, MOD(10, 3) returns 1 because 10 divided by 3 leaves a remainder of 1.
Common uses include:
- Checking whether an integer is even or odd.
- Assigning records to repeating groups.
- Finding the remainder after division.
A divisor of zero causes a division-by-zero error. Do not use zero as the second argument.
Using MOD
A zero remainder means the dividend is evenly divisible by the divisor.
12. Practical Example: Even and Odd Numbers
For integers, MOD(number, 2) returns zero when the number is even and a non-zero remainder when it is odd.
This example assumes a table named numbers with an integer column named value.
Classifying Numbers
CASE selects the label based on the remainder. This example assumes the value column contains integers and is not NULL.
13. POWER: Exponentiation
POWER raises a number to a specified exponent.
Syntax:
POWER(base, exponent)
Examples:
- POWER(2, 3) returns 8 because 2 × 2 × 2 = 8.
- POWER(5, 2) returns 25.
- POWER(9, 0.5) returns approximately 3.
POWER is useful for mathematical models, growth calculations, and scientific data processing.
The result type and valid input combinations depend on the argument types. Negative bases with non-integer exponents do not produce ordinary real-valued results in PostgreSQL.
Using POWER
POWER calculates the base raised to the exponent. The square-root result is mathematically 3; the displayed representation may depend on the result type and client.
14. Combining Numeric Functions
You can nest numeric functions to perform multiple operations in one expression.
For example:
ROUND(ABS(-12.678), 2)
Step by step:
1. ABS(-12.678) returns 12.678.
2. ROUND(12.678, 2) returns 12.68.
SQL evaluates the inner expression to produce the argument for the outer function.
Combining ABS and ROUND
ABS removes the negative sign, and ROUND limits the result to two decimal places.
15. Real-World Example: Product Pricing
An online store may store product prices and discount percentages. Numeric expressions can calculate the discount amount and final price.
This example assumes a products table with product_id, price, and discount_percent columns. It uses NUMERIC values for decimal arithmetic.
Calculating Discounted Prices
The query calculates the discount and final price. The results are illustrative. For financial systems, define a consistent rounding policy and store monetary values using an appropriate exact numeric type.
16. NULL Values and Numeric Functions
NULL represents a missing or unknown value. Numeric functions generally return NULL when a required numeric argument is NULL.
Examples:
- ROUND(NULL::numeric, 2) returns NULL.
- ABS(NULL::numeric) returns NULL.
- POWER(NULL::numeric, 2) returns NULL.
- MOD(10, NULL::integer) returns NULL.
A NULL result is different from zero. Zero is a known numeric value, while NULL means the value is missing or unknown.
Use COALESCE only when replacing missing data with a specific default is logically correct. Do not automatically convert every NULL to zero.
Handling NULL
The first two expressions remain NULL. COALESCE explicitly substitutes zero in the third expression; use this only if zero is a valid business default.
17. Numeric Precision and Financial Calculations
PostgreSQL provides several numeric types, and their behavior matters when performing calculations.
NUMERIC / DECIMAL:
- Exact decimal arithmetic within the type's precision limits.
- Often appropriate for financial amounts.
REAL / DOUBLE PRECISION:
- Approximate floating-point types.
- Some decimal fractions cannot be represented exactly in binary floating-point.
INTEGER / BIGINT:
- Whole-number types.
- Useful for counts and other integral values.
Example:
SELECT ROUND(2.675::numeric, 2);
For NUMERIC, this returns 2.68 in PostgreSQL.
Do not assume that every floating-point expression produces the same result as an exact NUMERIC expression. Casting an already approximate value to NUMERIC cannot restore precision that was previously lost.
Rounding policy also matters: decide whether to round each line item, each tax component, or only the final total. These choices can produce different totals.
18. Numeric Functions and WHERE Clauses
Numeric functions can appear in WHERE conditions, but applying a function to an indexed column can sometimes prevent a regular index on that column from being used efficiently.
For example, if price has a normal index, this expression may be less index-friendly:
WHERE ROUND(price, 0) = 100
If the requirement is to find prices in a range, consider expressing the condition as a range when that is logically equivalent.
For exact equivalence, be careful: rounding rules and boundary values affect which rows match. Always verify the rewritten condition before using it.
Filter by a Price Range
This query filters by a range rather than applying ROUND to each price. The example assumes the desired business rule is the specified range; it is not universally equivalent to ROUND(price, 0) = 100.
19. Common Numeric Function Patterns
| Requirement | Function or expression | Example |
|---|---|---|
| Round to two decimal places | ROUND | ROUND(12.345::numeric, 2) |
| Remove extra decimal digits | TRUNC | TRUNC(12.345::numeric, 2) |
| Round upward to an integer bound | CEIL | CEIL(4.2) |
| Round downward to an integer bound | FLOOR | FLOOR(4.8) |
| Remove a negative sign | ABS | ABS(-15) |
| Find a remainder | MOD | MOD(10, 3) |
| Calculate an exponent | POWER | POWER(2, 3) |
| Replace a missing result deliberately | COALESCE | COALESCE(ROUND(value, 2), 0) |
Choose the function that matches the actual business rule. Similar-looking functions can produce different results, particularly for negative values and rounding boundaries.
20. Practice: Predict the Output
Try to predict each result before checking the answers.
Question 1:
SELECT ROUND(7.846::numeric, 2);
Question 2:
SELECT TRUNC(7.846::numeric, 2);
Question 3:
SELECT CEIL(-2.1);
Question 4:
SELECT FLOOR(-2.1);
Question 5:
SELECT ABS(-19);
Question 6:
SELECT MOD(17, 5);
Question 7:
SELECT POWER(3, 3);
Question 8:
SELECT ROUND(149::numeric, -1);
Question 9:
SELECT TRUNC(149::numeric, -1);
Question 10:
SELECT ROUND(NULL::numeric, 2);
21. Practice Answers and Explanations
1. ROUND(7.846::numeric, 2) returns 7.85.
The third decimal digit is 6, so the second decimal digit rounds upward.
2. TRUNC(7.846::numeric, 2) returns 7.84.
TRUNC removes the remaining decimal digits without rounding.
3. CEIL(-2.1) returns -2.
-2 is the smallest integer greater than or equal to -2.1.
4. FLOOR(-2.1) returns -3.
-3 is the largest integer less than or equal to -2.1.
5. ABS(-19) returns 19.
6. MOD(17, 5) returns 2.
7. POWER(3, 3) returns 27.
8. ROUND(149::numeric, -1) returns 150.
9. TRUNC(149::numeric, -1) returns 140.
10. ROUND(NULL::numeric, 2) returns NULL.
22. Guided Exercise: Calculate Package Counts
Scenario:
A warehouse has 127 items. Each box can hold 12 items. Every item must be packed.
Task:
Write a query that calculates how many boxes are required.
Hint:
Divide the total number of items by the capacity of each box, then use CEIL.
Expected approach:
CEIL(127.0 / 12)
Try writing the query yourself before viewing the solution.
23. Guided Exercise Solution
Solution:
SELECT CEIL(127.0 / 12) AS boxes_required;
Result: 11
Explanation:
10 boxes hold 120 items, leaving 7 items. An additional box is required, so the total is 11 boxes.
Using FLOOR would return 10 and would not provide enough capacity.
24. Multiple-Choice Quiz
Choose the best answer for each question. The answers and explanations are included below.
25. Interview Questions and Answers
Q1. What are numeric functions in SQL?
Answer: Functions that perform mathematical calculations or transformations on numeric values.
Q2. What is ROUND used for?
Answer: ROUND rounds a numeric value to a specified decimal precision.
Q3. What is the difference between ROUND and TRUNC?
Answer: ROUND applies rounding rules, while TRUNC removes digits beyond the requested precision without rounding.
Q4. What does CEIL return?
Answer: The smallest integer greater than or equal to its input.
Q5. What does FLOOR return?
Answer: The largest integer less than or equal to its input.
Q6. How do FLOOR and TRUNC differ for negative values?
Answer: FLOOR moves toward negative infinity; TRUNC moves toward zero. For example, FLOOR(-2.7) is -3, while TRUNC(-2.7) is -2.
Q7. What does ABS do?
Answer: It returns the absolute value of a number.
Q8. What does MOD do?
Answer: It returns the remainder after division.
Q9. How can MOD help identify even integers?
Answer: An integer is even when MOD(value, 2) = 0.
Q10. What does POWER do?
Answer: It raises a base value to an exponent.
Q11. Can ROUND use a negative precision in PostgreSQL?
Answer: Yes. A negative precision rounds digits to the left of the decimal point for NUMERIC values.
Q12. Can TRUNC use a negative precision in PostgreSQL?
Answer: Yes. It removes digits to the left of the decimal point according to the specified precision.
Q13. What happens when a numeric function receives NULL?
Answer: Numeric functions generally return NULL when a required numeric argument is NULL.
Q14. Why is NUMERIC often used for financial calculations?
Answer: It provides exact decimal arithmetic within the chosen precision, unlike approximate floating-point types.
Q15. Why might floating-point calculations surprise developers?
Answer: Some decimal fractions cannot be represented exactly in binary floating-point, which can lead to small representation differences.
Q16. What is the difference between CEIL(4.2) and FLOOR(4.2)?
Answer: CEIL returns 5; FLOOR returns 4.
Q17. Why should MOD not use zero as its divisor?
Answer: Division by zero raises an error.
Q18. Can numeric functions be used inside SELECT?
Answer: Yes. They can transform values directly in a SELECT expression.
Q19. Can a numeric function be used in WHERE?
Answer: Yes, but applying a function to an indexed column can affect index usage. Check the execution plan and consider equivalent range conditions where appropriate.
Q20. Does using a numeric function guarantee a faster query?
Answer: No. Query performance depends on the query, data distribution, indexes, and execution plan.
Q21. How would you calculate the number of boxes needed for 127 items if each box holds 12?
Answer: CEIL(127.0 / 12), which returns 11.
Q22. What is the difference between ROUND(149::numeric, -1) and TRUNC(149::numeric, -1)?
Answer: ROUND returns 150, while TRUNC returns 140.
Q23. Is ROUND always the right choice for monetary calculations?
Answer: Not automatically. The correct rounding stage and policy depend on the application's financial rules.
Q24. Can POWER produce a fractional result?
Answer: Yes. For example, POWER(9, 0.5) calculates the square root of 9.
Q25. What should you check before deploying a numeric calculation?
Answer: Input types, NULL handling, division-by-zero cases, precision, rounding policy, expected boundaries, and query performance where relevant.
26. Lesson Summary
In this lesson, you learned how to use PostgreSQL numeric functions:
- ROUND rounds a number to a requested precision.
- TRUNC removes digits without rounding.
- CEIL returns the smallest integer greater than or equal to a number.
- FLOOR returns the largest integer less than or equal to a number.
- ABS returns the absolute value.
- MOD returns a remainder.
- POWER calculates an exponent.
- NULL inputs generally produce NULL results.
- NUMERIC is useful for exact decimal financial calculations.
- Numeric functions can be combined inside SELECT expressions and other SQL clauses.
The most important distinction to remember is that ROUND, TRUNC, CEIL, and FLOOR do different jobs. Test positive values, negative values, integers, decimal boundaries, and NULLs to understand their behavior.
27. Common Mistakes
Avoid these frequent errors when using numeric functions.
Ready for hands-on challenges?
Test your skills with shuffled coding challenges in the Practice Arena.
Key takeaways
- ROUND changes a value to the requested decimal precision using rounding.
- TRUNC removes digits beyond the requested precision without rounding.
- CEIL returns the smallest integer greater than or equal to a number.
- FLOOR returns the largest integer less than or equal to a number.
- ABS returns the absolute value, MOD returns a remainder, and POWER calculates an exponent.
- Numeric functions generally return NULL when their numeric argument is NULL.
- Use NUMERIC for exact decimal calculations such as financial amounts.
- Test edge cases and verify the behavior of numeric expressions before using them in production.