Dates & Times — Getting Ranges and Boundaries Right
Group by month and keep the year, so June 2023 and June 2024 stay two separate months. Spot partial periods, write date ranges that never count a day twice, anchor recent on the data, subtract dates correctly, and fill the months that have no rows.
This article is part of the Learn SQL hands-on course series.
Prerequisite — this is a hands-on lesson. Reading it is not enough. Run every query yourself in CloudBeaver, against the Northwind Company sample database on PostgreSQL — and solve the koans yourself on DuckDB, the same Northwind Company data.
Not set up yet? It only takes a couple of minutes:
Orders per month: EXTRACT throws the year away
Leo, the manager wants a chart: orders per month. One bar for every month we've been trading.
I can already do that. EXTRACT the month from the order date, group by it — the GROUP BY lesson.
Go on, then. EXTRACT(MONTH FROM "OrderDate"), and group by it.
SELECT EXTRACT(MONTH FROM "OrderDate")
AS "Month",
count(*) AS "Orders"
FROM "Orders"
GROUP BY EXTRACT(MONTH FROM "OrderDate")
ORDER BY "Month";One row per month — ready for the manager's chart.
June had 739 orders. November and December, the busiest. Looks right.
Which June, Leo? We've traded five years, January 2020 to December 2024 — sixty months. Your chart has twelve.
the June bar — five Junes stacked
| Month | Orders |
|---|---|
| June 2020 | 120 |
| June 2021 | 130 |
| June 2022 | 144 |
| June 2023 | 168 |
| June 2024 | 177 |
| The June bar | 739 |
177 — June 2024 on its own
Every bar is five months added up. Next to it, June 2024 looks like a crash.
…Twelve? So my June is every June — 2020 to 2024, added into one bar.
Exactly. EXTRACT kept the month and threw the year away. The manager will read 739 as one June. June 2024 had 177 — next to 739, it looks like a crash that never happened.
So the crash is in my chart, not in the shop. Every bar needs its year — June 2024, not just June.
date_trunc keeps the year
Then use date_trunc. date_trunc('month', …) cuts every date back to the first of its month — and keeps the year. The 5th of June 2024 becomes the 1st of June 2024.
SELECT date_trunc('month', "OrderDate")
AS "Month",
count(*) AS "Orders"
FROM "Orders"
GROUP BY date_trunc('month', "OrderDate")
ORDER BY "Month";So each bar is a real month, not just a month's name.
Sixty real months — every June back in its own year.
the same 60 months, as a chart — the five Junes lit, the line through each year's average month
About 10% more orders every year.
Same orders, sixty groups instead of twelve — and now I can see the company growing.
Weeks, and the edges of the data
date_trunc also takes quarter, year — and week. Orders per week, and this time ask for the first and last order in each week as well.
SELECT date_trunc('week', "OrderDate")
AS "Week",
count(*) AS "Orders",
min("OrderDate") AS "First order",
max("OrderDate") AS "Last order"
FROM "Orders"
GROUP BY date_trunc('week', "OrderDate")
ORDER BY "Week";Why do I need those? The count is the report.
The last week crashed: 60 orders, then 20.
Before you call it a crash, read its last order. The 31st of December — the data ends there. That week has two days in it.
Wait — and the first row says 2019. A week starts on a Monday, the data starts on a Wednesday — five days.
Right, both are partial. A partial period can look like a crash or a record — so ask for the edges, and say so on the report.
BETWEEN counts an edge twice
Now a range. Shipping wants every order that shipped in November 2024.
SELECT count(*) AS "Shipments",
max("ShippedDate") AS "Last shipped"
FROM "Orders"
WHERE "ShippedDate" BETWEEN DATE '2024-11-01'
AND DATE '2024-12-01';BETWEEN the first of November and the first of December — both ends included, so nothing slips out. And the last ship date, to check the edge.
277 shipments. Read the last date.
The 1st of December? Mnemo, that isn't November.
It isn't. BETWEEN includes both ends — and the end you wrote was the 1st of December. So every order shipped that day is in November's report.
And December's report, written the same way, starts on the 1st of December.
SELECT count(*) AS "Shipments",
min("ShippedDate") AS "First shipped"
FROM "Orders"
WHERE "ShippedDate" BETWEEN DATE '2024-12-01'
AND DATE '2025-01-01';1 December, claimed by both reports
| Range | Count | |
|---|---|---|
| November's report | BETWEEN DATE '2024-11-01' AND DATE '2024-12-01' | 277 |
| December's report | BETWEEN DATE '2024-12-01' AND DATE '2025-01-01' | 236 |
1 Dec: 14 shipments — counted in both
277 + 236 = 513 — for the 499 that actually shipped in those two months.
Wait — the 1st of December again? Then those shipments are in November's report and in December's — counted twice.
Half-open ranges
The fix is a habit, not a better end date. On or after the first day — and strictly before the first day of the next month.
SELECT count(*) AS "Shipments",
max("ShippedDate") AS "Last shipped"
FROM "Orders"
WHERE "ShippedDate" >= DATE '2024-11-01'
AND "ShippedDate" < DATE '2024-12-01';the same days — cut once
| Range | Count | |
|---|---|---|
| November's report | >= DATE '2024-11-01' AND < DATE '2024-12-01' | 263 |
| December's report | >= DATE '2024-12-01' AND < DATE '2025-01-01' | 236 |
1 Dec: one cut — the 14 are December's
263 + 236 = 499. Every shipment counted once, in one month.
There — 263. Fourteen fewer, and the last one shipped on the 30th. The 1st of December belongs to December alone.
Or I end the range on the 30th. Then the 1st of December can't get in.
SELECT SUM(CASE WHEN "CreatedAt" BETWEEN DATE '2024-11-01'
AND DATE '2024-11-30'
THEN 1 ELSE 0 END) AS "Ends on the 30th",
SUM(CASE WHEN "CreatedAt" >= DATE '2024-11-01'
AND "CreatedAt" < DATE '2024-12-01'
THEN 1 ELSE 0 END) AS "Half-open"
FROM "Orders";Try it — count it both ways on CreatedAt: your range next to the half-open one. It's when each order was keyed in — unlike the ship date, it has a time of day.
where DATE '2024-11-30' actually falls
| Range | Count | |
|---|---|---|
| Ends on the 30th | BETWEEN DATE '2024-11-01' AND DATE '2024-11-30' | 271 |
| Half-open | >= DATE '2024-11-01' AND < DATE '2024-12-01' | 278 |
30 Nov: 7 orders keyed in on the 30th — outside the first range
A date is midnight at the START of that day. Ending on the 30th ends the range before the 30th happens.
271 against 278? So ending on the 30th means midnight at the start of the 30th — the 7 orders keyed in that day are gone.
Exactly — and it's the same trap with =: "CreatedAt" = DATE '2024-11-30' finds none. Nobody keys an order in at midnight.
Your turn, Leo.
Count the orders placed in May 2024.
Half-open: on or after the first, before the first of June. You should get 181.
▶ Continue once you've run it.
SELECT count(*) AS "Orders"
FROM "Orders"
WHERE "OrderDate" >= ___
AND "OrderDate" < ___;“Recent” on data that has stopped
Now the recent orders: the last 30 days. CURRENT_DATE minus an INTERVAL of 30 days.
SELECT count(*) AS "Orders"
FROM "Orders"
WHERE "OrderDate" >= CURRENT_DATE
- INTERVAL '30 days';Zero.
Zero? Mnemosyne, we have ten thousand orders.
We do — but CURRENT_DATE is today, and this data stops at the end of 2024. The query is right. There just aren't any orders in the 30 days before today.
On live data, CURRENT_DATE is exactly right. On a snapshot like ours, anchor on the data: the last order date, worked out in brackets — the subquery from the first lesson of this series.
SELECT count(*) AS "Orders",
min("OrderDate") AS "From",
max("OrderDate") AS "To"
FROM "Orders"
WHERE "OrderDate" >=
(SELECT max("OrderDate") FROM "Orders")
- INTERVAL '30 days';So 'recent' means recent to the data. And I'll ask for the first and last order, to see the edges.
254 orders, from the 1st to the 31st of December — 30 days back from the last day in the data.
So it starts at midnight on the 1st: a timestamp minus an INTERVAL is still a timestamp. And >= keeps that whole day.
Subtracting dates
Dates subtract, too. Which orders took more than a week to ship?
SELECT count(*) AS "Slow orders"
FROM "Orders"
WHERE "ShippedDate" - "OrderDate" > 7;SQL Error [42883]: ERROR: operator does not exist: interval > integer
Position: 82Shipped date minus order date, greater than 7. …And it won't run: operator does not exist, interval greater than integer?
A timestamp minus a timestamp is an INTERVAL — '4 days', a length of time. It isn't the number 4, so it can't be compared with 7.
So how do I get the number?
Cast both sides to DATE first. A date minus a date is a whole number of days — that's why the lesson on missing values cast both sides.
Cast both sides, and it's days against days. 193 orders took more than a week to ship.
SELECT count(*) AS "Slow orders"
FROM "Orders"
WHERE CAST("ShippedDate" AS DATE)
- CAST("OrderDate" AS DATE) > 7;So I copied those casts without knowing why. Now I know what they were for.
Comparing two timestamps needs no arithmetic at all. "RequiredDate" is when the customer needs the order — which ones shipped after that, in December?
SELECT "OrderID",
"RequiredDate", "ShippedDate"
FROM "Orders"
WHERE "ShippedDate" > "RequiredDate"
AND "ShippedDate" >= DATE '2024-12-01'
AND "ShippedDate" < DATE '2025-01-01'
ORDER BY "ShippedDate", "OrderID";Just three. Order 9696 was needed on the 10th and shipped on the 20th.
The months that have no rows
One more: Bramble Supermarket's orders per month in 2024, for a chart.
SELECT date_trunc('month', "OrderDate") AS "Month",
count(*) AS "Orders"
FROM "Orders"
WHERE "CustomerID" = 'BRAM3'
AND "OrderDate" >= DATE '2024-01-01'
AND "OrderDate" < DATE '2025-01-01'
GROUP BY date_trunc('month', "OrderDate")
ORDER BY "Month";Easy. Four rows — January, May, October and November.
Bramble Supermarket, 2024 — what the query handed back
| Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sep | Oct | Nov | Dec |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 2 | — | — | — | 1 | — | — | — | — | 1 | 2 | — |
And what happened in February?
Nothing — so there's no row. The chart just draws a line from January to May… and eight months nobody can see.
So make the months first. generate_series produces twelve timestamps, one per month — and a LEFT JOIN hangs the orders on them. The customer goes in the ON.
SELECT s.month AS "Month",
count(o."OrderID") AS "Orders"
FROM generate_series(
TIMESTAMP '2024-01-01',
TIMESTAMP '2024-12-01',
INTERVAL '1 month') AS s(month)
LEFT JOIN "Orders" o
ON date_trunc('month', o."OrderDate") = s.month
AND o."CustomerID" = 'BRAM3'
GROUP BY s.month
ORDER BY s.month;the twelve months first — orders hung on them
| Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sep | Oct | Nov | Dec |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 2 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 2 | 0 |
Twelve rows, whatever the orders did. The eight silences come back as eight zeros.
In the ON — because in a WHERE it would drop the empty months again. The LEFT JOIN trap from the lesson on JOINs.
Twelve rows, and the empty months say zero.
A zero is something the chart can draw. A missing row was just a silence.
So Bramble's total for the year is count(*) over the spine.
SELECT count(*) AS "count(*)",
count(o."OrderID") AS "count(OrderID)"
FROM generate_series(
TIMESTAMP '2024-01-01',
TIMESTAMP '2024-12-01',
INTERVAL '1 month') AS s(month)
LEFT JOIN "Orders" o
ON date_trunc('month', o."OrderDate") = s.month
AND o."CustomerID" = 'BRAM3';Is it? Run both — count(*) next to count(o."OrderID").
Fourteen against six? So count(*) counted the 6 order rows and a row for each empty month. The order ID is NULL there, so only the real 6 get counted.
Case file: since when?
Mnemosyne, can I go back to Speedy Express — the courier with the orders marked Shipped but no ship date? Last lesson found them and ended with no explanation, and it has been bothering me since. What I want to know is since when. If it has always been like that, it's how they work. If it started on a particular day, something changed.
SELECT date_trunc('week', "OrderDate") AS "Week",
count(*) AS "Orders",
SUM(CASE WHEN "Status" = 'Shipped'
AND "ShippedDate" IS NULL
THEN 1 ELSE 0 END) AS "No ship date"
FROM "Orders"
WHERE "OrderDate" >= DATE '2024-01-01'
AND "OrderDate" < DATE '2025-01-01'
GROUP BY date_trunc('week', "OrderDate")
ORDER BY "Week";Your manager asked why invoicing fell. Asking when the trouble at Speedy Express started was your own idea — and a good one: when it started is how you trace what caused it. How would you count it?
Week by week, over 2024 — with a CASE count, so the weeks with none come back as zeros, not missing rows.
Zero, zero — then 8 in the week of the 4th of March.
And 3 to 12 every week after it, up to the week of the 26th of August. Then zero again.
So it didn't creep in or build up like a busy season. It started in one week and lasted 26 weeks in a row — six months, March to August.
So that's since when: the week of the 4th of March. Outside those 26 weeks, Northwind Company's whole year has just one more order like that, in October — 178 in all. What we don't know yet is how much this cost.
Then the next question is what those 178 orders are worth. Their prices aren't in "Orders" — they're in "Order Details", one row per product ordered. I'll work out how much money that is.
That's the next lesson, Leo: several tables at once — joining "Orders" to "Order Details". You'll work out that total there.
What to take away, and what is next
Before we stop — four habits, Leo. Truncate the date, keep the year, and check the first and last date. Make every range half-open. Anchor 'recent' on the data. And cast before you subtract — then count the orders, not the rows.
Each habit fixes a wrong number I got today — and every one of them looked right. June at 739 when that was five Junes, the 1st of December counted in two months, zero orders in the last 30 days, and 14 orders that were really 6.
Your turn, Leo.
▶ Walk the path to enlightenment.
cd c:/DataPallas/db/datazeus
.\zeus.bat koans learnsql series2 _10- date_trunc keeps the year: how many months had an invoice
- diagnose: five Marches in one count
- a half-open range: invoices issued in the first quarter of 2024
- …and seven more, ending with two you write yourself
…/learnsql/series2/_10/DatesAndTimesKoans.groovy
That was dates, Leo. Keep the year, make ranges half-open, anchor on the data, cast before you subtract, and count the orders — not the rows. Next lesson: several tables at once — and how much money is on those orders?
That's what I want to find out: what the 178 orders with no ship date are worth.
That's all, folks!
- Subqueries — one query's result inside another
- CASE — SQL's if/then for labels & buckets
- Dates & Times — ranges and boundaries (this lesson)
- Multi-Table JOINs & Grain — rows dropped or multiplied
- CTEs (WITH) — a long query, in named steps
- VIEWs, CREATE TABLE AS & Temp Tables — query or answer
- EXISTS & Correlated Subqueries — and the NOT IN trap
- Self-JOINs & Hierarchies — rows in the same table
- Window Functions I: OVER, PARTITION BY & ROW_NUMBER
- String Functions, LIKE & Regex — clean up messy data
- Window Functions II: LAG/LEAD, Running Totals & Frames
- UNION, INTERSECT, EXCEPT — stack and reconcile lists
- GROUPING SETS, ROLLUP & CUBE — subtotals in one pass
- INSERT, UPDATE, DELETE & Transactions — safely
- UPSERT & MERGE — insert or update, safely re-run
- Median and Percentiles — WITHIN GROUP, not AVG
- Subqueries + CTEs + Window Functions — a real case
Found this to be a little gem? Help others find it too — someone out there is stuck trying to learn SQL right now. The button opens Reddit with the link and title already filled in, so you just pick a community and post.
Share on Reddit