19/30
Part 4 of 5 · Type trapsLearn and do

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_aftercast_beforecast_operand
0.00.40.4

The first column is the trap. * and / have the same precedence and run left to right:

cast_aftercast_before
WrittenCOUNT(promo) / COUNT(*) * 1.01.0 * COUNT(promo) / COUNT(*)
First step2 / 5 * 1.01.0 * 2 / 5
Then0 * 1.02.0 / 5
Result0.00.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_intavg_dollars
1919.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.