Design a Video View Counter
You're at a video platform like YouTube. Every time someone watches a video, the view count needs to go up.
The obvious answer is a views column on the videos table that you increment on each play. That works — until product comes back and asks: "How many views did this video get in the last hour?" A single counter can't answer that. You've lost the history.
Design the SQL schema. The judge will run your schema, insert videos and view events, and verify that both total counts and time-windowed counts work correctly.
- Create a
videostable with at leastid INTEGER PRIMARY KEYandtitle TEXT NOT NULL. - Create a
video_viewstable with at leastid INTEGER PRIMARY KEY,video_id INTEGER NOT NULL, andviewed_at INTEGER NOT NULL(unix timestamp in seconds). video_views.video_idmust declareREFERENCES videos(id)so foreign-key integrity is enforced when SQLite hasPRAGMA foreign_keys = ON.- One row in
video_viewsrepresents exactly one view event. Do not store totals in a counter column. - After inserting view events,
SELECT COUNT(*) FROM video_views WHERE video_id = ?must return the total view count for that video. - Time-windowed queries like
SELECT COUNT(*) FROM video_views WHERE video_id = ? AND viewed_at >= ?must return the count within the window.
INSERT INTO videos (id, title) VALUES (1, 'Cat compilation'); INSERT INTO video_views (video_id, viewed_at) VALUES (1, 1700000000), (1, 1700001000), (1, 1700002000); SELECT COUNT(*) FROM video_views WHERE video_id = 1;
3
Total views: three events, three rows.
SELECT COUNT(*) FROM video_views WHERE video_id = 1 AND viewed_at >= 1700001500;
1
Time-windowed: only the third event (timestamp 1700002000) is in the window.
- Do not store a
viewscounter column. Storage must be per-event. - The schema must execute with
conn.executescript(...)— no DML, only DDL.
Per-event storage scales to analytics, but at 10M views/day a `COUNT(*)` query gets slow. How would you keep the event log AND give the homepage a fast lookup for total views?
Keep moving through related backend basics problems and build a stronger search-friendly practice loop around this topic.
View track →