runtime
34 / 88

lesson 34 Dates, strings & subqueries · intermediate

Date boundaries & monthly buckets

Define date ranges and monthly groups without boundary mistakes.

the idea

For timestamps, use a half-open interval: >= start and < next boundary. This includes every time on the last day without guessing the final second. SQLite uses strftime/date; PostgreSQL uses DATE_TRUNC and INTERVAL. All teaching timestamps are UTC.

tables in this lesson

The challenges use this data. Each column shows its type underneath; → marks a link to another table.

watch_events5 columns · 26 rows
idinteger · keyviewer_idintegervideo_idintegerwatched_attextwatch_secondsinteger
1112025-01-01 10:00:00300
2122025-01-01 11:00:00450
3212025-01-02 12:00:00600
4332025-01-02 13:00:00120
5142025-01-02 14:00:00700

showing 5 of 26 rows

example

The idea in one query. Press Run to see what it returns; running examples never affects your progress.

example.sql
SELECT id,watched_at
FROM watch_events
WHERE watched_at >= '2025-01-01' AND watched_at < '2025-02-01';

Watch for: BETWEEN with an end date at midnight can omit that date’s later events.

build it step by step

Each step changes one thing. Run them in order and watch the result change.

  1. Bound January with half-open dates. Timestamps need a clear start and end. Use >= month start and < next month start so the boundary stays unambiguous.

    step-1.sql
    SELECT id, watched_at
    FROM watch_events
    WHERE watched_at >= '2025-01-01' AND watched_at < '2025-02-01'
    ORDER BY watched_at
    LIMIT 8;
  2. Select the January window. The half-open range includes midnight on January 1 and excludes midnight on February 1.

    step-2.sql
    SELECT id, watched_at
    FROM watch_events
    WHERE watched_at >= '2025-01-01' AND watched_at < '2025-02-01';

challenge 1

Return id and watched_at for January 2025 watch events, including the full final day and excluding February.

Return idwatched_atany row order

challenge-1.sql
 
To master this lesson, solve both challenges without hints and pass the concept check. 3 of 3 to go.