← Back to SQL, page 25

sql-0494 · Easy fresher

A report shows completion rates of 0 for every course, although many students have finished. What is wrong?

Dividing one integer by another in SQLite and PostgreSQL discards the fraction, so 3 / 4 is 0. Make at least one side a decimal before dividing, for example 100.0 * done / total, and round only for display.

Full answer
sql
CREATE TABLE enrolments (course TEXT, student TEXT, finished INTEGER);
INSERT INTO enrolments VALUES
 ('SQL','a',1),('SQL','b',1),('SQL','c',1),('SQL','d',0),
 ('Python','a',1),('Python','b',0),('Python','c',0);

The query as written:

sql
SELECT course, SUM(finished) / COUNT(*) AS completion_rate FROM enrolments GROUP BY course ORDER BY course;
coursecompletion_rate
Python0
SQL0

SQL has 3 of 4 finished and Python 1 of 3, but 3 / 4 and 1 / 3 are integer divisions that truncate to 0.

A corrected version:

sql
SELECT course, ROUND(100.0 * SUM(finished) / COUNT(*), 1) AS completion_pct FROM enrolments GROUP BY course ORDER BY course;
coursecompletion_pct
Python33.3
SQL75.0

Starting the expression with 100.0 forces decimal arithmetic, giving 75.0 and 33.3 percent. PostgreSQL behaves the same way with integers, so the fix is portable; there, SUM(finished)::numeric / COUNT(*) also works. Rounding belongs in the final display step, because rounding early and then averaging compounds the error.

sql
CREATE TABLE enrolments (course TEXT, student TEXT, finished INTEGER);
INSERT INTO enrolments VALUES
 ('SQL','a',1),('SQL','b',1),('SQL','c',1),('SQL','d',0),
 ('Python','a',1),('Python','b',0),('Python','c',0);

SELECT course, SUM(finished) / COUNT(*) AS completion_rate FROM enrolments GROUP BY course ORDER BY course;

SELECT course, ROUND(100.0 * SUM(finished) / COUNT(*), 1) AS completion_pct FROM enrolments GROUP BY course ORDER BY course;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Integer division truncates
  • Use 100.0 or a cast to force decimals
  • Same behaviour in PostgreSQL
  • Round only at the end

Common mistakes

  • Rounding before further arithmetic
  • Assuming the database promotes integers automatically

Follow-ups

  • What does 7 / 2 return in SQLite versus MySQL?
  • How would you handle a course with zero enrolments?

Tips

  • Show both fractions truncating