Filters and dates
Almost every SQL task in an interview starts with WHERE: which rows count, and for which period. Mistakes here raise no error. The query runs, and the number is a little wrong: the last day of the month is lost, a test purchase is in the revenue, or two Septembers share one group.
The three “paid” filters
Section titled “The three “paid” filters”One row of transactions is one billing period of a subscription. Not every row is a payment. Three columns mark the rows that are not:
| Filter | Removes | Why |
|---|---|---|
NOT is_test | test purchases | never part of a business number |
NOT is_trial | free trial periods | price 0: a trial is not a payment |
channel <> 'promo' | promo access | price 0: nobody paid |
Trials and promo access depend on the question: they are transactions, but not paid ones. When the task says “paid”, apply all three filters. When it says “transactions”, ask whether trials count.
What the last two filters change, on July 2026:
SELECT NOT is_trial AND channel <> 'promo' AS paid, COUNT(*) AS transactions, SUM(charged_usd) AS gross_usdFROM transactionsWHERE NOT is_test AND start_time >= TIMESTAMP '2026-07-01' AND start_time < TIMESTAMP '2026-08-01'GROUP BY 1ORDER BY 1;| paid | transactions | gross_usd |
|---|---|---|
| false | 59 | 0.00 |
| true | 427 | 6876.73 |
The 59 free rows add nothing to the sum. They still change the count (486 against 427) and the average price (14.15 against 16.10). So a forgotten trial filter does not change a revenue total, but it does change a count or an average.
COUNT(*) FILTER (WHERE …) in the traps below counts only the rows that pass its condition. Conditional aggregation explains it in detail.
AND before OR
Section titled “AND before OR”AND binds tighter than OR, in the same way as multiplication binds tighter than addition. a OR b AND c means a OR (b AND c). When a filter mixes the two, write the parentheses, even if you think they are not needed.
Web checkout and North Market, test purchases excluded. Will the two numbers match?
Guess the result first, then run the query. Fix the query, then Check.
Output columns: web_or_north_no_test
Tables, columns and how they connect
transactions — one row = one paid (or trial) period of a subscription
channel— north_market / south_market (partner marketplaces) / web (own checkout) / promo (free access, price 0)is_test— test purchase: exclude it from business numbers
| channel | is_test |
|---|---|
| north_market | false |
| north_market | false |
| north_market | false |
"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.
SELECT COUNT(*) FILTER (WHERE channel = 'web' OR channel = 'north_market' AND NOT is_test) AS no_parens,
COUNT(*) FILTER (WHERE (channel = 'web' OR channel = 'north_market') AND NOT is_test) AS with_parens
FROM transactions;Show answer
No: 5182 against 5158. AND binds tighter than OR, so without parentheses the filter means “web checkout, test purchases included” or “North Market without test purchases”. When you mix AND and OR, add parentheses.
This is what PostgreSQL returns for the query as it is:
| no_parens | with_parens |
|---|---|
| 5182 | 5158 |
Show the fix
SELECT COUNT(*) AS web_or_north_no_testFROM transactionsWHERE (channel = 'web' OR channel = 'north_market') AND NOT is_test;| web_or_north_no_test |
|---|
| 5158 |
Half-open date ranges
Section titled “Half-open date ranges”A period is a half-open interval: it includes its start and excludes its end. [2026-08-01, 2026-09-01) is all of August, up to the last second.
WHERE start_time >= TIMESTAMP '2026-08-01' AND start_time < TIMESTAMP '2026-09-01'The same shape works for a day, a week, a month or a year. The end of one period is the start of the next, so no row is lost and none is counted twice. You never need to know how many days a month has.
BETWEEN includes both ends. On a timestamp column, BETWEEN '2026-07-01' AND '2026-07-31' stops at 31 July 00:00:00 and loses the rest of that day.
July 2026, counted two ways. Will the numbers match?
Guess the result first, then run the query. Fix the query, then Check.
Output columns: july
Tables, columns and how they connect
transactions — one row = one paid (or trial) period of a subscription
start_time— start of the period = time of purchase; "started in …" means this column
| start_time |
|---|
| 2025-01-01 02:08:33 |
| 2025-01-01 04:48:03 |
| 2025-01-01 06:59:58 |
"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.
SELECT COUNT(*) FILTER (WHERE start_time BETWEEN '2026-07-01' AND '2026-07-31') AS with_between,
COUNT(*) FILTER (WHERE start_time >= '2026-07-01' AND start_time < '2026-08-01') AS half_open
FROM transactions;Show answer
No: 490 against 502. BETWEEN '2026-07-01' AND '2026-07-31' ends at 31 July 00:00:00, so the rest of that day is lost. For timestamps, use a half-open range: >= the start and < the start of the next period.
This is what PostgreSQL returns for the query as it is:
| with_between | half_open |
|---|---|
| 490 | 502 |
Show the fix
SELECT COUNT(*) AS julyFROM transactionsWHERE start_time >= TIMESTAMP '2026-07-01' AND start_time < TIMESTAMP '2026-08-01';| july |
|---|
| 502 |
One day is the same pattern with a one-day step.
Purchases on 1 September, counted three ways. What does each one return?
Guess the result first, then run the query.
Tables, columns and how they connect
transactions — one row = one paid (or trial) period of a subscription
start_time— start of the period = time of purchase; "started in …" means this column
| start_time |
|---|
| 2025-01-01 02:08:33 |
| 2025-01-01 04:48:03 |
| 2025-01-01 06:59:58 |
"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.
SELECT COUNT(*) FILTER (WHERE start_time = '2026-09-01') AS a_equals,
COUNT(*) FILTER (WHERE start_time::date = '2026-09-01') AS b_cast,
COUNT(*) FILTER (WHERE start_time >= '2026-09-01' AND start_time < '2026-09-02') AS c_range
FROM transactions;Show answer
0, 20 and 20. start_time = '2026-09-01' means exactly midnight, and no purchase happened at 00:00:00. The cast start_time::date gives the right answer, but a plain index on start_time cannot serve it. The range (c) is right and can use the index.
This is what PostgreSQL returns for the query as it is:
| a_equals | b_cast | c_range |
|---|---|---|
| 0 | 20 | 20 |
Months as a DATE
Section titled “Months as a DATE”A report “per month” needs a month column. Two functions look right:
date_trunc('month', ts)cuts the timestamp down to the first moment of its month:2026-09-15 10:30becomes2026-09-01 00:00:00. The year stays.EXTRACT(MONTH FROM ts)returns only the month number, from 1 to 12. September 2025 and September 2026 both become 9.
The practice data starts in January 2025, so the difference is real:
SELECT CAST(date_trunc('month', start_time) AS DATE) AS month, COUNT(*) AS transactionsFROM transactionsWHERE EXTRACT(MONTH FROM start_time) = 9GROUP BY 1ORDER BY 1;| month | transactions |
|---|---|
| 2025-09-01 | 433 |
| 2026-09-01 | 475 |
Grouped by EXTRACT(MONTH FROM start_time), the same 908 rows would fall into one group called 9.
date_trunc returns a timestamp, not a date. For a clean month column, cast the result: CAST(date_trunc('month', ts) AS DATE).
What type does date_trunc return when you pass it a date?
Guess the result first, then run the query. Fix the query, then Check.
Output columns: m
SELECT date_trunc('month', DATE '2026-09-15') AS m,
pg_typeof(date_trunc('month', DATE '2026-09-15')) AS type;Show answer
timestamp with time zone: 2026-09-01 00:00:00+00, not a date. date_trunc always returns a timestamp. For a date in the output, cast it: CAST(date_trunc('month', x) AS DATE). Check on this site compares values as they are printed, and a timestamp never equals a date, so it catches the wrong type.
This is what PostgreSQL returns for the query as it is:
| m | type |
|---|---|
| 2026-09-01 00:00:00+00 | timestamp with time zone |
Show the fix
SELECT CAST(date_trunc('month', DATE '2026-09-15') AS DATE) AS m;| m |
|---|
| 2026-09-01 |
Typed literals and intervals
Section titled “Typed literals and intervals”A quoted value such as '2026-09-01' has no type at first. PostgreSQL gives it the type of what it meets. Next to a timestamp column it becomes a timestamp, so start_time >= '2026-09-01' works. Next to an interval, it is read as an interval, and the query fails.
A typed literal removes the guesswork: TIMESTAMP '2026-09-01', DATE '2026-09-01', INTERVAL '30 days'. Write the type every time, and the same expression also works in date arithmetic.
Purchases in the last 30 days. Will the query run?
Guess the result first, then run the query. Fix the query, then Check.
Output columns: last_30_days
Tables, columns and how they connect
transactions — one row = one paid (or trial) period of a subscription
start_time— start of the period = time of purchase; "started in …" means this column
| start_time |
|---|
| 2025-01-01 02:08:33 |
| 2025-01-01 04:48:03 |
| 2025-01-01 06:59:58 |
"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.
SELECT COUNT(*) AS last_30_days FROM transactions WHERE start_time >= '2026-09-30' - INTERVAL '30 days' AND start_time < '2026-09-30';
Show answer
No: invalid input syntax for type interval: "2026-09-30". A quoted string has no type at first and takes the type of its neighbour. Next to INTERVAL, PostgreSQL reads it as an interval too. The fix is TIMESTAMP '2026-09-30' - INTERVAL '30 days', which is 2026-08-31 00:00:00; the answer is 483. On the second line the neighbour is the start_time column, so the string becomes a timestamp anyway. Habit: always write TIMESTAMP '…'.
This is what PostgreSQL returns for the query as it is:
Show the fix
SELECT COUNT(*) AS last_30_daysFROM transactionsWHERE start_time >= TIMESTAMP '2026-09-30' - INTERVAL '30 days' AND start_time < TIMESTAMP '2026-09-30';| last_30_days |
|---|
| 483 |
Date arithmetic in one query:
SELECT TIMESTAMP '2026-09-30' - INTERVAL '30 days' AS minus_30_days, TIMESTAMP '2026-01-31' + INTERVAL '1 month' AS plus_1_month, DATE '2026-09-30' - DATE '2026-09-01' AS date_minus_date, TIMESTAMP '2026-09-30 12:00' - TIMESTAMP '2026-09-28' AS ts_minus_ts;| minus_30_days | plus_1_month | date_minus_date | ts_minus_ts |
|---|---|---|---|
| 2026-08-31 00:00:00 | 2026-02-28 00:00:00 | 29 | 2 days 12:00:00 |
- A timestamp plus or minus an interval is a timestamp. Adding a month to 31 January gives the last day of February.
- A date minus a date is a whole number of days.
- A timestamp minus a timestamp is an
interval. For a number, takeEXTRACT(EPOCH FROM …)(seconds) and divide by 86400. For the last column above, this gives2.5000000000000000days.
“Today” is a literal
Section titled ““Today” is a literal”Interview data is static. NOW() and CURRENT_DATE move every day, so “the last 30 days” drifts away from the data and the answer changes from run to run. Ask what today is, then write it as a literal. On this site, today is 2026-09-30. If in doubt, look where the data ends:
SELECT MAX(start_time) AS last_purchaseFROM transactions;| last_purchase |
|---|
| 2026-09-29 23:40:35 |
Then write the window with today as the excluded end, and the agreement as a comment:
-- today = 2026-09-30; last 30 days = [today - 30 days, today)WHERE start_time >= TIMESTAMP '2026-09-30' - INTERVAL '30 days' AND start_time < TIMESTAMP '2026-09-30'Whether today itself counts is a question for the interviewer, not a guess. The same goes for time zones: the timestamps here are UTC, and “per day” for customers in another country may need a different day boundary.
Practice
Section titled “Practice”How many paid transactions started in August 2026? Paid means: not a trial, not a test purchase, not promo.
Output columns: paid_transactions
Tables, columns and how they connect
transactions — one row = one paid (or trial) period of a subscription
channel— north_market / south_market (partner marketplaces) / web (own checkout) / promo (free access, price 0)is_trial— free trial (7 days, price 0)start_time— start of the period = time of purchase; "started in …" means this columnis_test— test purchase: exclude it from business numbers
| channel | is_trial | start_time | is_test |
|---|---|---|---|
| north_market | false | 2025-01-01 04:48:03 | false |
| north_market | false | 2025-01-01 06:59:58 | false |
| north_market | false | 2025-01-01 02:08:33 | false |
"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.
-- your query here
Show answer
Reference
SELECT COUNT(*) AS paid_transactionsFROM transactionsWHERE NOT is_trial AND NOT is_test AND channel <> 'promo' AND start_time >= TIMESTAMP '2026-08-01' AND start_time < TIMESTAMP '2026-09-01';Expected output
| paid_transactions |
|---|
| 485 |
All three “paid” filters, and a half-open range: from the first day of August, up to but not including the first day of September. BETWEEN … '2026-08-31' would lose 31 August after midnight, and BETWEEN … '2026-09-01' would count a sale made exactly at 00:00 on 1 September. The hidden data has both. Next to a column, typed literals are not required, but the habit costs nothing.
Net revenue (revenue_usd) per month for January–September 2026, test purchases excluded. The month as a DATE (first day of the month).
Output columns: month, net_usdOrder: ORDER BY month
Tables, columns and how they connect
transactions — one row = one paid (or trial) period of a subscription
start_time— start of the period = time of purchase; "started in …" means this columnrevenue_usd— revenue net of refunds: 0 if the transaction was refunded (net)is_test— test purchase: exclude it from business numbers
| start_time | revenue_usd | is_test |
|---|---|---|
| 2025-01-01 02:08:33 | 6.99 | false |
| 2025-01-01 04:48:03 | 79.99 | false |
| 2025-01-01 06:59:58 | 6.99 | false |
"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.
-- your query here
Show answer
Reference
SELECT CAST(date_trunc('month', start_time) AS DATE) AS month, SUM(revenue_usd) AS net_usdFROM transactionsWHERE NOT is_test AND start_time >= TIMESTAMP '2026-01-01' AND start_time < TIMESTAMP '2026-10-01'GROUP BY 1ORDER BY 1;Expected output
| month | net_usd |
|---|---|
| 2026-01-01 | 6273.12 |
| 2026-02-01 | 5271.40 |
| 2026-03-01 | 5651.26 |
| 2026-04-01 | 5390.16 |
| 2026-05-01 | 5943.94 |
| 2026-06-01 | 6509.84 |
| 2026-07-01 | 6531.84 |
| 2026-08-01 | 7082.25 |
| 2026-09-01 | 5961.81 |
CAST(date_trunc('month', start_time) AS DATE) keeps the year and gives a clean date. EXTRACT(MONTH …) would merge the same month of different years, and date_trunc alone returns a timestamp. GROUP BY 1 and ORDER BY 1 refer to the first column of SELECT.
For refunded paid transactions, per channel: the average time from start_time to refunded_at in days, 1 decimal. Use the exact elapsed time, fractions of a day included, not the difference of the two dates.
Output columns: channel, avg_days_to_refundOrder: ORDER BY channel
Tables, columns and how they connect
transactions — one row = one paid (or trial) period of a subscription
channel— north_market / south_market (partner marketplaces) / web (own checkout) / promo (free access, price 0)is_trial— free trial (7 days, price 0)start_time— start of the period = time of purchase; "started in …" means this columnrefunded_at— when the money was returned; NULL = no refund; "refunded" = refunded_at IS NOT NULLis_test— test purchase: exclude it from business numbers
| channel | is_trial | start_time | refunded_at | is_test |
|---|---|---|---|---|
| north_market | false | 2025-01-01 04:48:03 | NULL | false |
| north_market | false | 2025-01-01 02:08:33 | NULL | false |
| north_market | false | 2025-01-22 14:37:00 | 2025-02-04 15:18:13 | false |
"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.
-- your query here
Show answer
Reference
SELECT channel, ROUND(AVG(EXTRACT(EPOCH FROM refunded_at - start_time) / 86400)::numeric, 1) AS avg_days_to_refundFROM transactionsWHERE refunded_at IS NOT NULL AND NOT is_trial AND NOT is_test AND channel <> 'promo'GROUP BY channelORDER BY channel;Expected output
| channel | avg_days_to_refund |
|---|---|
| north_market | 11.6 |
| south_market | 10.8 |
| web | 10.2 |
refunded_at - start_time is an interval. EXTRACT(EPOCH FROM …) turns it into seconds; divide by 86400 for days. ROUND(x, 1) needs a numeric. In PostgreSQL 14 and later EXTRACT already returns one, so the cast is a safety net for older versions and other engines. The task asks for the exact time, so do not subtract dates: refunded_at::date - start_time::date counts calendar days, a whole number, and gives 11.7 instead of 11.6 on North Market. EXTRACT(DAY FROM …) is wrong too: it drops the hours.
Further reading
Section titled “Further reading”- Date/Time Functions and Operators — the operator table,
EXTRACTanddate_trunc. - Interval input — how
'30 days'and'1 month'are read. - Constants of other types — typed literals such as
TIMESTAMP '…'. - Operator precedence — why
ANDis applied beforeOR. - Comparison predicates —
BETWEENand its inclusive ends.
Related topics
Section titled “Related topics”- Grouping and counting — the next step: one row per channel or per month.
- PostgreSQL dialect — more on literals, casts and what other databases do differently.
- Calendars and active periods — every day even without data, and “active at a moment”.
- Indexes and EXPLAIN — why a range on the raw column can use an index.
- Practice dataset — what each column of
transactionsmeans.
Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.