sqlassert

Simplify and catch SQL bugs before they ship

Fan Trap

Multiple refunds can make the same payment count more than once.

fan-trap.sql

CREATE TABLE orders (id INT PRIMARY KEY);CREATE TABLE payments (id INT PRIMARY KEY, order_id INT, amount INT);CREATE TABLE refunds (id INT PRIMARY KEY, order_id INT); SELECT o.id, SUM(p.amount) AS paidFROM orders oJOIN payments p ON p.order_id = o.idJOIN refunds r ON r.order_id = o.idGROUP BY o.id;

Terminal output excerpt

$ sqlassert suggest fan-trap.sql

Fan trap · line 9

SUM(p.amount) reads rows that JOIN refunds AS r may repeat: the join is not proved to repeat rows of only one input (fan trap), so a value may be counted more than once