Every finance dashboard eventually gets the same bug report: "Sales are down 45% this month!" It is the 14th. The query compared fourteen days of this month with all thirty-one days of the same month last year.
A like for like comparison in SQL means comparing windows that genuinely match: same length, same position in the calendar, same rules for what counts. This post walks through the patterns I reach for in PostgreSQL, plus a Django version, and the edge cases that break naive year over year SQL.
All examples assume a simple table:
CREATE TABLE sales ( id bigserial PRIMARY KEY , order_date date NOT NULL , amount numeric ( 12 , 2 ) NOT NULL ) ; CREATE INDEX ON sales ( order_date ) ;
Enter fullscreen mode
Exit fullscreen mode
The three rules of like-for-like windows
Half-open ranges. Use >= start AND < end . It works the same for date and timestamp columns and never double-counts midnight.
Shift both ends.…