Two type traps: integer division and dates stored as text
In SQLite and PostgreSQL, an integer divided by an integer drops the fraction
The question: what share of orders used a promo?
SELECT COUNT(promo) / COUNT(*) AS promo_share
FROM orders;
| promo_share |
|---|
| 0 |
2 / 5 comes out as 0. In SQLite and PostgreSQL, an integer divided by an integer is an integer, cut toward zero. COUNT returns an integer in both, so every rate built from counts can hit this.
Put the 1.0 before the division, because multiplying after it is too late
Make one operand a real number before the division runs:
SELECT COUNT(promo) / COUNT(*) * 1.0 AS cast_after,
1.0 * COUNT(promo) / COUNT(*) AS cast_before,
CAST(COUNT(promo) AS REAL) / COUNT(*) AS cast_operand
FROM orders;
| cast_after | cast_before | cast_operand |
|---|---|---|
| 0.0 | 0.4 | 0.4 |
The first column is the trap. * and / have the same precedence and run left to right:
| cast_after | cast_before | |
|---|---|---|
| Written | COUNT(promo) / COUNT(*) * 1.0 | 1.0 * COUNT(promo) / COUNT(*) |
| First step | 2 / 5 * 1.0 | 1.0 * 2 / 5 |
| Then | 0 * 1.0 | 2.0 / 5 |
| Result | 0.0 | 0.4 |
On the left, the division runs first and loses the fraction. Multiplying by 1.0 afterwards only turns 0 into 0.0. In PostgreSQL, a ::numeric cast on either operand does the job of the 1.0.
Money in cents hits the same bug. The average order in dollars:
SELECT SUM(total_cents) / COUNT(*) / 100 AS avg_dollars_int,
SUM(total_cents) / COUNT(*) / 100.0 AS avg_dollars
FROM orders;
| avg_dollars_int | avg_dollars |
|---|---|
| 19 | 19.4 |
AVG itself is safe here. SQLite's avg() returns a floating point value even when every input is an integer, and PostgreSQL's avg of an integer column returns numeric.
In the editor, fix PROMO_SHARE: each customer's share of orders with a promo, not just 0 or 1.