SQL traps · SQL
SQL: 5 / 2 = 2?!PRO
Whole number divided by whole number gives a whole number. Add one decimal (2.0) or CAST to REAL.
-- SQL: 5 / 2 = 2 ?! — dividing two whole numbers gives a whole number (the rest is dropped). SELECT 5 / 2; -- 2 ?! SELECT 5 / 2.0; -- 2.5 ✓ one decimal makes it a real division SELECT CAST(5 AS REAL) / 2; -- 2.5 ✓ or cast a column -- It bites averages built by hand: CREATE TABLE votes (yes INTEGER, total INTEGER); INSERT INTO votes VALUES (3, 4); SELECT yes / total AS share FROM votes; -- 0 ?! SELECT yes * 1.0 / total AS share FROM votes; -- 0.75 ✓Open code S2 in Pocket Compiler Download the Pocket Compiler app — free
No app yet? Install it, then open the app and type the code S2 in Code Library.