Skip to content

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.

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:

FilterRemovesWhy
NOT is_testtest purchasesnever part of a business number
NOT is_trialfree trial periodsprice 0: a trial is not a payment
channel <> 'promo'promo accessprice 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_usd
FROM transactions
WHERE NOT is_test
AND start_time >= TIMESTAMP '2026-07-01'
AND start_time < TIMESTAMP '2026-08-01'
GROUP BY 1
ORDER BY 1;
paidtransactionsgross_usd
false590.00
true4276876.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 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.

SQLTrap: what will it return?

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
channelis_test
north_marketfalse
north_marketfalse
north_marketfalse

"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_parenswith_parens
51825158
Show the fix
SELECT COUNT(*) AS web_or_north_no_test
FROM transactions
WHERE (channel = 'web' OR channel = 'north_market') AND NOT is_test;
web_or_north_no_test
5158
1 row

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.

SQLTrap: what will it return?core

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_betweenhalf_open
490502
Show the fix
SELECT COUNT(*) AS july
FROM transactions
WHERE start_time >= TIMESTAMP '2026-07-01' AND start_time < TIMESTAMP '2026-08-01';
july
502
1 row

One day is the same pattern with a one-day step.

SQLTrap: what will it return?

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_equalsb_castc_range
02020

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:30 becomes 2026-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 transactions
FROM transactions
WHERE EXTRACT(MONTH FROM start_time) = 9
GROUP BY 1
ORDER BY 1;
monthtransactions
2025-09-01433
2026-09-01475

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

SQLTrap: what will it return?

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:

mtype
2026-09-01 00:00:00+00timestamp with time zone
Show the fix
SELECT CAST(date_trunc('month', DATE '2026-09-15') AS DATE) AS m;
m
2026-09-01
1 row

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.

SQLTrap: what will it return?core

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:

Error
invalid input syntax for type interval: "2026-09-30"
Show the fix
SELECT COUNT(*) AS last_30_days
FROM transactions
WHERE start_time >= TIMESTAMP '2026-09-30' - INTERVAL '30 days'
AND start_time < TIMESTAMP '2026-09-30';
last_30_days
483
1 row

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_daysplus_1_monthdate_minus_datets_minus_ts
2026-08-31 00:00:002026-02-28 00:00:00292 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, take EXTRACT(EPOCH FROM …) (seconds) and divide by 86400. For the last column above, this gives 2.5000000000000000 days.

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_purchase
FROM 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.

SQLWrite a querycore

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 column
  • is_test — test purchase: exclude it from business numbers
channelis_trialstart_timeis_test
north_marketfalse2025-01-01 04:48:03false
north_marketfalse2025-01-01 06:59:58false
north_marketfalse2025-01-01 02:08:33false

"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_transactions
FROM transactions
WHERE 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
1 row

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.

SQLWrite a querycore

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 column
  • revenue_usd — revenue net of refunds: 0 if the transaction was refunded (net)
  • is_test — test purchase: exclude it from business numbers
start_timerevenue_usdis_test
2025-01-01 02:08:336.99false
2025-01-01 04:48:0379.99false
2025-01-01 06:59:586.99false

"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_usd
FROM transactions
WHERE NOT is_test
AND start_time >= TIMESTAMP '2026-01-01'
AND start_time < TIMESTAMP '2026-10-01'
GROUP BY 1
ORDER BY 1;

Expected output

monthnet_usd
2026-01-016273.12
2026-02-015271.40
2026-03-015651.26
2026-04-015390.16
2026-05-015943.94
2026-06-016509.84
2026-07-016531.84
2026-08-017082.25
2026-09-015961.81
9 rows

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.

SQLWrite a query

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 column
  • refunded_at — when the money was returned; NULL = no refund; "refunded" = refunded_at IS NOT NULL
  • is_test — test purchase: exclude it from business numbers
channelis_trialstart_timerefunded_atis_test
north_marketfalse2025-01-01 04:48:03NULLfalse
north_marketfalse2025-01-01 02:08:33NULLfalse
north_marketfalse2025-01-22 14:37:002025-02-04 15:18:13false

"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_refund
FROM transactions
WHERE refunded_at IS NOT NULL
AND NOT is_trial AND NOT is_test AND channel <> 'promo'
GROUP BY channel
ORDER BY channel;

Expected output

channelavg_days_to_refund
north_market11.6
south_market10.8
web10.2
3 rows

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.

Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.