← Back to SQL, page 1

sql-0007 · Easy fresher

What does SELECT 7 / 2 return, and how do you get 3.5 instead?

When both operands are integers, SQLite and PostgreSQL perform integer division and return 3, dropping the fraction. Make one side non-integer with 7 / 2.0, or cast with CAST(7 AS REAL) in SQLite or 7::numeric in PostgreSQL. MySQL is the odd one out and returns 3.5000 for 7 / 2.

Full answer

Integer division catches people in averages and percentage columns. In SQLite and PostgreSQL, an integer divided by an integer is an integer, and the fraction is thrown away (truncated toward zero).

SQLite:

sql
SELECT 7 / 2 AS a, -7 / 2 AS b, 7 % 2 AS remainder;
abremainder
3-31

PostgreSQL gives the same values:

sql
SELECT 7 / 2 AS a, -7 / 2 AS b, 7 % 2 AS remainder;
abremainder
3-31

Look at -7 / 2: the result is -3, not -4. The fraction is truncated toward zero, which is not the same as rounding down.

To keep the fraction, make at least one operand non-integer:

sql
SELECT 7 / 2.0 AS a, CAST(7 AS REAL) / 2 AS b, ROUND(100.0 * 2 / 3, 2) AS pct;
abpct
3.53.566.67

A real case: a pass percentage computed as passed * 100 / total with integers returns whole numbers only, and passed / total * 100 returns 0 for every class where not everyone passed, because passed / total is 0 before the multiplication. Multiply first, or write 100.0 * passed / total.

MySQL does not follow this rule. Its / always returns a decimal (7 / 2 is 3.5000) and it has a separate DIV operator for integer division. This was not run here; it comes from the MySQL documentation.

sql
SELECT 7 / 2 AS a, -7 / 2 AS b, 7 % 2 AS remainder;

SELECT 7 / 2.0 AS a, CAST(7 AS REAL) / 2 AS b, ROUND(100.0 * 2 / 3, 2) AS pct;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • Integer / integer is integer division in SQLite and PostgreSQL
  • The fraction is truncated toward zero, so -7 / 2 is -3
  • Use 2.0, CAST, or 100.0 * x / y to keep decimals
  • MySQL's / returns a decimal; DIV is its integer division

Common mistakes

  • Computing passed / total * 100 and getting 0
  • Assuming the same expression behaves the same on MySQL and PostgreSQL

Follow-ups

  • How do you round the result to two decimal places?
  • What does the modulo operator return for negative numbers?

Tips

  • Show the passed / total * 100 bug; it is the version interviewers like
  • Mention truncation toward zero for negative numbers