SQL Numeric and Math Functions: ROUND, ABS and Division

Numeric functions calculate or reshape numbers, while input types and rounding rules determine the precision of their results.

Lesson 44 of 102Intermediate10 min read

Numeric functions calculate or reshape numbers, while input types and rounding rules determine the precision of their results.

Calculating a percentage or a rounded display price is more than choosing a mathematical formula. The database must also choose a numeric type, handle missing values and decide how rounding works. Those choices are observable in the final result.

This reference adds detail to the main course. You can read it independently: the small database below supplies every table and row used in the examples. Start with the question each query answers, then compare the returned values with the data rather than memorising a line of syntax.

Set up the practice database

Run this setup once in a new practice database, before the examples. It uses four customers and six sales. Ana has two sales, Ben has one, Cara has two, and Dev has none.

Sale 106 has no customer link; sale 104 has an unknown amount. These deliberate test cases expose missing information and unmatched relationships.

SQL
CREATE TABLE customers (
  id INTEGER PRIMARY KEY,
  name VARCHAR(40) NOT NULL,
  city VARCHAR(40),
  manager_id INTEGER
);
CREATE TABLE sales (
  id INTEGER PRIMARY KEY,
  customer_id INTEGER,
  amount DECIMAL(10,2),
  status VARCHAR(20) NOT NULL,
  created_on DATE NOT NULL
);
INSERT INTO customers (id,name,city,manager_id) VALUES
  (1,'Ana','Leeds',NULL),(2,'Ben','Leeds',1),
  (3,'Cara','Porto',1),(4,'Dev',NULL,2);
INSERT INTO sales (id,customer_id,amount,status,created_on) VALUES
  (101,1,10,'paid','2026-01-01'),
  (102,1,30,'pending','2026-01-02'),
  (103,2,20,'paid','2026-01-02'),
  (104,3,NULL,'pending','2026-02-01'),
  (105,3,20,'paid','2026-02-02'),
  (106,NULL,5,'paid','2026-02-03');

An amount of zero would be a known value. The NULL amount here means the value is unknown. A customer with no matching sale differs from a sale whose customer_id is NULL.

The primary keys identify individual records even when amounts or cities repeat. Dates use year-month-day format. The examples specify sorting whenever order matters; insertion order alone does not guarantee display order.

How SQL numeric and mathematical functions works

ABS returns a number’s magnitude without its sign. ROUND changes a value to a requested precision according to the engine’s numeric rules. FLOOR selects an integer boundary at or below a number, while CEILING selects one at or above it. For negative inputs, truncation towards zero is not the same as FLOOR: floor of minus 1.2 is minus two. Do not interchange these operations simply because they produce the same result for a positive example.

Numeric storage affects the calculation before a display format is applied. DECIMAL or NUMERIC types can represent decimal values exactly in server databases, while floating-point types store approximations. Rounding a floating-point value at a halfway boundary may therefore behave differently from rounding an exact decimal. SQLite’s dynamic type system does not provide fixed-precision decimal arithmetic merely because a column is declared DECIMAL. Choose integer minor units or an approved decimal solution for exact money calculations there.

Integer division and zero denominators

Division requires attention to both operand types and zero denominators. Integer division can truncate fractions in PostgreSQL, SQL Server and SQLite; MySQL’s slash operator has different numeric rules and offers DIV for integer division. Use a decimal operand or explicit cast when a fraction is needed. Wrap the denominator in NULLIF(denominator,0) if a zero denominator should yield an unknown ratio instead of an error or engine-specific result.

Most ordinary numeric functions propagate NULL, preserving an unknown input as unknown output. A report may intentionally apply COALESCE to a missing amount, but that is a business assumption rather than a mathematical identity. Round at the stage required by policy: rounding each line item and then summing can differ from summing exact values and rounding once. POWER, logarithms and trigonometric functions are available in many engines, but SQLite mathematical functions depend on how the library was built. Verify availability before writing portable exercises.

MySQL, PostgreSQL, SQL Server and SQLite

ROUND and ABS are available in all four systems. ROUND parameter options and halfway behaviour differ by type and engine. SQLite FLOOR, CEIL and POWER require the mathematical-function build option in ordinary SQLite; do not promise their availability without checking. SQL Server calls the upward function CEILING; names and aliases vary elsewhere.

Check the engine-specific syntax and version requirements in PostgreSQL mathematical functions, SQLite mathematical functions.

Practice task and worked solution

Return the numeric ratio of paid known revenue to all known revenue, rounded to three decimal places. Avoid a zero denominator.

Try the task before reading its worked solution. The supplied rows make the expected answer checkable by hand.

SQL
SELECT ROUND(
 SUM(CASE WHEN status='paid' THEN amount ELSE 0 END)*1.0
 /NULLIF(SUM(amount),0),3) AS paid_share FROM sales;
Output
paid_share
0.647

The numerator is fifty-five and the denominator is eighty-five. Multiplying by 1.0 requests fractional numeric arithmetic, and NULLIF guards a zero total. The approximate ratio 0.6470588 is rounded to 0.647; it is a fraction, not a percentage label.

Compare integer-looking division with a decimal denominator in the chosen engine. Then evaluate a denominator guarded by NULLIF(0,0) and observe a NULL ratio. Test ROUND on a negative and a fractional value using the exact numeric type your application will use. Do not generalise floating-point halfway results to fixed-decimal calculations, or assume optional SQLite mathematical functions are installed.

SQL Numeric and Math Functions: ROUND, ABS and Division Syntax

SQL numeric and mathematical functions

SELECT id,ROUND(amount/4.0,2) AS quarter_amount
FROM sales WHERE id IN (101,102,106) ORDER BY id;

SQL Numeric and Math Functions: ROUND, ABS and Division Summary

  • ABS, ROUND, FLOOR and CEILING reshape numbers; MOD or % gives a remainder.
  • Dividing two integers truncates in PostgreSQL, SQL Server and SQLite; use a decimal operand such as 4.0 for fractions.
  • FLOOR moves down to the lower integer and CEILING up, so FLOOR(-2.5) is -3.
  • Guard against division by zero with amount / NULLIF(divisor, 0), which returns NULL instead of an error.
  • Rounding of halves differs between exact and floating-point types, so store money as DECIMAL.

SQL Numeric and Math Functions: ROUND, ABS and Division Examples

Each example shows the code, the output it produces and what each part does.

Example 1

A quarter of each amount, rounded

The decimal operand 4.0 expresses a fractional division rather than an integer quotient. The selected amounts divide to 2.5, 7.5 and 1.25. Clients may omit trailing zeros, so compare numeric values rather than requiring identical screen formatting.

SQL
SELECT id,ROUND(amount/4.0,2) AS quarter_amount
FROM sales WHERE id IN (101,102,106) ORDER BY id;
Output
id | quarter_amount
101 | 2.50
102 | 7.50
106 | 1.25

Common SQL Numeric and Math Functions: ROUND, ABS and Division Mistakes

Losing fractions to integer division

Using amount/4 with integer-valued storage can lose a fractional result in engines that perform integer division. A display format cannot recover a fraction already discarded by arithmetic. Choose the intended numeric type before calculating, and distinguish rounding a result from truncating its underlying calculation.

SQL Numeric and Math Functions: ROUND, ABS and Division in Real Projects

Revenue shares with a stated rounding policy

A revenue-share report can divide each known sale by an agreed percentage denominator and round according to a stated payment policy. Keep the raw calculation available for reconciliation. If an input is missing or a denominator is zero, show an explicit unavailable state rather than manufacturing a plausible payment.

State whether a ratio is stored as a fraction or a percentage and label its unit. A paid_share of 0.647 is approximately 64.7 percent, not 0.647 percent. Keep intermediate precision high enough for the calculation and apply the approved final rounding policy, rather than treating a client’s printed digits as the arithmetic specification.

SQL Numeric and Math Functions: ROUND, ABS and Division FAQ

Is ROUND a text formatter?

No. It calculates a numeric result; client display controls trailing zeros and separators, which is why 2.50 may appear as 2.5. To control the displayed text, format it in the application or with a formatting function such as TO_CHAR in PostgreSQL or FORMAT in MySQL.

Does FLOOR truncate negatives towards zero?

No. It goes to the lower integer boundary, so FLOOR(-2.5) is -3, while truncation towards zero gives -2. PostgreSQL's TRUNC and SQL Server's ROUND(x, 0, 1) truncate; casting to an integer type truncates in some engines and rounds in others.

Can I divide safely using a preceding WHERE condition alone?

No. Do not rely on evaluation order, because the database may calculate the division before checking the other condition. A denominator protected directly with NULLIF(quantity, 0) expresses the intended safe calculation for every row.

How do I get the remainder of a division?

Use MOD(a, b) or the % operator: 7 % 3 is 1. With a negative first number, PostgreSQL, MySQL and SQL Server give a negative remainder, MOD(-7, 3) is -1, which matters when you use remainders to assign rows to groups.

How do I calculate a percentage in SQL?

Multiply by a decimal before dividing, 100.0 * paid_count / NULLIF(total_count, 0), so integer division can't truncate the result, then ROUND it for display. Calculate percentages from counts or totals, not by averaging other percentages.

SQL Numeric and Math Functions: ROUND, ABS and Division Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Multiple choicemedium

What quarter_amount is returned for sale 106?

SQL Numeric and Math Functions: ROUND, ABS and Division Quiz

2 questions to check what you learned.

  1. Why use 4.0 rather than 4 in the division example?

    • To force integer division and discard the fraction
    • To make ROUND return a formatted text label
    • To express a fractional numeric calculation
  2. What does NULLIF(total,0) do in a denominator?

    • Changes a zero denominator to NULL
    • Converts every denominator to zero before division
    • Replaces only a NULL denominator with zero