SQL Current Month
Filter to rows within the current calendar month โ using DATE_TRUNC to define the boundary cleanly, rather than hardcoding month numbers.
What & Why
A current-month filter uses a lower boundary at the first day and an exclusive upper boundary at the first day of the next month.
The worked Queryflo table fixes those boundaries to March 1 through April 1, 2024 so it consistently returns the March lead row.
See How It Works
BUSINESS QUESTION
Using 2024-03-31 as a fixed report date, Marketing wants all leads created in the March calendar window.
| id | campaign_id | created_at | qualified_at | converted_at | lead_score | source | country | |
|---|---|---|---|---|---|---|---|---|
| 301 | 1 | ana@example.com | 2024-01-21 09:10:00+00 | 2024-01-22 11:00:00+00 | 2024-02-02 10:00:00+00 | 86 | google_ads | US |
| 302 | 1 | ben@example.com | 2024-01-24 12:40:00+00 | NULL | NULL | 52 | google_ads | CA |
| 303 | 2 | chloe@example.com | 2024-02-16 08:30:00+00 | 2024-02-18 14:20:00+00 | NULL | 74 | GB | |
| 304 | 3 | dev@example.com | 2024-03-20 17:15:00+00 | 2024-03-21 09:00:00+00 | 2024-04-04 16:00:00+00 | 91 | US |
Watch calendar-month boundaries classify timestampsExample 1 of 4
as of 2024-03-31 ยท 2024-03-01 <= created_at < 2024-04-01
| id | created_at | current_month_result |
|---|---|---|
| 301 | 2024-01-21 09:10:00+00 | outside March |
| 302 | 2024-01-24 12:40:00+00 | ? |
| 303 | 2024-02-16 08:30:00+00 | ? |
| 304 | 2024-03-20 17:15:00+00 | ? |
Lead 301 was created in January.
EXAMPLE QUERY
SELECT
id AS lead_id,
source,
created_at
FROM marketing.leads
WHERE created_at >= TIMESTAMPTZ '2024-03-01 00:00:00+00'
AND created_at < TIMESTAMPTZ '2024-04-01 00:00:00+00'
ORDER BY created_at, lead_id;Now You Try
Practice this concept
Return leads in the fixed March 2024 teaching month, ordered by creation time and lead id.
Available schema
marketingPrefix tables with marketing.table_name.
lead_idsourcecreated_atmarketing.leads| Column | Type |
|---|---|
| id | integer |
| campaign_id | integer |
| text | |
| created_at | timestamp with time zone |
| qualified_at | timestamp with time zone |
| converted_at | timestamp with time zone |
| lead_score | integer |
| source | text |
| country | text |
| archive_status | text |
query.sql
Sign up free to try it on a real business scenario