Menu

1 / 5

Like-for-Like Period Comparisons in SQL

DEV Community: django·Lumetric·1 day ago
#3tEd53d2
#devtodjango#devto#dev#month#order_date
Long article (1716 words) — no AI summary yet.
Reading 0:00
15s threshold

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.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.