01 / 21
.00

Integer Division
in SQL Metrics

Why dividing two integers silently truncates your results, and how to cast your way to accuracy across every SQL dialect.

SQL

What is Integer Division?

In most programming languages and many SQL dialects, when you divide two integers, the engine performs integer division: it divides and then truncates the decimal portion, returning only the whole number.

You Write
\( 7 / 2 \)
→
You Expect
3.5
→
You Get
3

Why It Matters for Metrics

SQL metrics often compute ratios, rates, and averages from integer columns: counts, sums, and totals. Integer division silently corrupts these calculations.

Conversion Rate
purchases / visits truncates to 0 when \( \text{purchases} < \text{visits} \)
Average Order Value
total_revenue / order_count loses cents from every row
Percentage Metrics
passed / total * 100 yields 0 if \( \text{passed} < \text{total} \)

The Type System Behind It

SQL engines follow type promotion rules when evaluating expressions. The result type of a division depends on the types of its operands.

INT / INT → INT Truncated
\( 7/2 = 3 \)
FLOAT / INT → FLOAT Precise
\( 7.0/2 = 3.5 \)
INT / FLOAT → FLOAT Precise
\( 7/2.0 = 3.5 \)
Rule If either operand is FLOAT/DECIMAL, result is FLOAT

The Core Rule

-- Integer division: WRONG SELECT purchases / visits AS conversion_rate -- Fixed: CAST one operand SELECT CAST(purchases AS FLOAT) / visits AS conversion_rate

Dialect Differences

Not all SQL dialects handle integer division the same way. This is one of the most common sources of bugs when migrating queries between databases.

Dialect \( 7 / 2 \) Result Behavior
PostgreSQL 3 Integer division (truncates)
MySQL 3.5000 Auto-promotes to decimal
SQL Server 3 Integer division (truncates)
SQLite 3 Integer division (truncates)
BigQuery 3.5 Auto-promotes to FLOAT64
Snowflake 3.5 Auto-promotes to NUMBER

Truncation vs. Rounding

Integer division truncates (chops off the decimal). It does not round to the nearest integer. This distinction matters because the error is always in one direction.

Truncation
\( 7 / 2 = 3 \) (not 4)
\( -7 / 2 = -3 \) (toward zero)
Rounding
\( \text{ROUND}(3.5) = 4 \)
\( \text{ROUND}(-3.5) = -4 \)

How to Fix It: Step by Step

1
Identify integer columns. Check the schema: INT, BIGINT, SMALLINT types are all integer.
2
Find every division. Search your query for the / operator and any division in computed columns.
3
Cast the numerator. Wrap the numerator in CAST(... AS FLOAT) or multiply by 1.0 to promote it.
4
Verify with known values. Test with simple inputs: SELECT CAST(7 AS FLOAT) / 2 should return 3.5.
5
Check your dialect. Know whether your database truncates or auto-promotes. When in doubt, always cast.

Three Casting Techniques

CAST()
CAST(n AS FLOAT)
Standard SQL. Works everywhere. Most explicit and readable.
Multiply by 1.0
n * 1.0 / d
Quick shorthand. Promotes n to decimal implicitly.
:: Syntax
n::FLOAT / d
PostgreSQL shorthand. Concise but not portable.

Example 1: Conversion Rate

A marketing team wants the purchase conversion rate from a table with purchases (INT) and visits (INT).

-- WRONG: integer division SELECT campaign_name, purchases / visits AS conv_rate FROM campaigns; -- purchases=32, visits=1000 → conv_rate = 0
-- CORRECT: cast numerator SELECT campaign_name, CAST(purchases AS FLOAT) / visits AS conv_rate FROM campaigns; -- purchases=32, visits=1000 → conv_rate = 0.032
Before
0
0% conversion
→
After
0.032
3.2% conversion

Example 2: Average with Rounding

A school wants average test scores. Both total_points (INT) and num_students (INT) are integers.

-- WRONG: truncated average SELECT class_name, total_points / num_students AS avg_score FROM classes; -- total_points=2587, num_students=30 → avg_score = 86
-- CORRECT: precise average, rounded to 1 decimal SELECT class_name, ROUND(total_points * 1.0 / num_students, 1) AS avg_score FROM classes; -- total_points=2587, num_students=30 → avg_score = 86.2

Example 3: Safe Percentage with CASE

Computing a percentage metric that also guards against division by zero: a common companion bug.

-- BEST PRACTICE: cast + zero guard SELECT product_name, CASE WHEN total_orders = 0 THEN NULL ELSE ROUND( CAST(returned_orders AS DECIMAL(10,4)) / total_orders * 100, 2 ) END AS return_pct FROM products;

The Multiplication Order Trap

A subtle variant: multiplying by 100 before vs. after division changes whether integer truncation strikes.

-- WRONG: divides first (integer), then multiplies SELECT (passed / total) * 100 AS pct; -- passed=3, total=10 → (0) * 100 = 0
-- BETTER: multiplies first, then divides SELECT passed * 100 / total AS pct; -- passed=3, total=10 → 300 / 10 = 30
-- BEST: cast for full precision SELECT CAST(passed AS FLOAT) / total * 100 AS pct; -- passed=3, total=10 → 30.0

Aggregate Functions and Division

Functions like SUM() and COUNT() return integers. Dividing their results inherits the same integer division trap.

-- WRONG: both SUM and COUNT return INT SELECT department, SUM(revenue) / COUNT(*) AS avg_rev FROM sales GROUP BY department;
-- CORRECT: cast the aggregate SELECT department, CAST(SUM(revenue) AS FLOAT) / COUNT(*) AS avg_rev FROM sales GROUP BY department;

Common Mistakes

✕ Casting Too Late
Writing CAST(a/b AS FLOAT) casts the already-truncated integer result. Cast before division.
✕ Assuming All Dialects Match
A query working in MySQL may silently break in PostgreSQL. Always test in your target dialect.
✕ Forgetting Aggregates
SUM() and COUNT() return integers. Dividing two aggregates triggers the same trap.

Summary: Fix Patterns

Pattern Buggy Fixed
Simple ratio \( a / b \) \( \text{CAST}(a \text{ AS FLOAT}) / b \)
Percentage \( (a / b) \times 100 \) \( \text{CAST}(a \text{ AS FLOAT}) / b \times 100 \)
Quick cast \( a / b \) \( a \times 1.0 / b \)
PostgreSQL \( a / b \) \( a\text{::FLOAT} / b \)
Aggregate \( \text{SUM}(x) / \text{COUNT}(*) \) \( \text{CAST}(\text{SUM}(x) \text{ AS FLOAT}) / \text{COUNT}(*) \)
Late cast \( \text{CAST}(a/b \text{ AS FLOAT}) \) \( \text{CAST}(a \text{ AS FLOAT}) / b \)

Question 1 of 5

In PostgreSQL, what does SELECT 5 / 2; return?

Question 2 of 5

Which of these fixes integer division correctly?

Question 3 of 5

A query computes SUM(revenue) / COUNT(*) in SQL Server. Both return INT. What does this expression compute?

Question 4 of 5

Which SQL dialect does NOT perform integer division on 7 / 2?

Question 5 of 5

Given passed = 3 and total = 10 (both INT), what does (passed / total) * 100 return in PostgreSQL?