SQL Practice: Filtering the Longest Web Sessions
Not every question is a GROUP BY. Sometimes you just want the individual standout rows.
Aggregates summarize, but sometimes you want the raw rows themselves. The
specific sessions where a visitor stuck around. That is a plain
WHERE
filter, no grouping involved.
Here "engaged" is defined as a session lasting at least 400 seconds. The
comparison
duration_seconds >= 400
keeps only those rows, and sorting brings the longest to the top.
A stable sort needs a tie-breaker
Two sessions could share the same duration. Adding
session_id
as a second sort key means the ranking is identical on every run. The same
habit that keeps
LIMIT
results deterministic.
select columns
from table_name
where number_column >= threshold
order by number_column desc, tie_breaker Schema · Website Analytics Table · sessions 7 columns · 30 rows
One row per visit. Anonymous visits have a null user_id; organic and direct visits have a null campaign_id.
Return the session id, channel, device, and duration for every session that lasted 400 seconds or longer, longest first. Break ties by session id.
Run your query to inspect the result.
Expected answer
- Columns: session_id, channel, device, duration_seconds.
- Rows: 8 sessions lasting 400 seconds or longer.
- The longest is session 22 (paid, desktop) at 600 seconds.
Related
Comparisons, AND/OR, IN, BETWEEN, and LIKE.
SELECT, WHERE, ORDER BY, and LIMIT at a glance.
Debug filters that match nothing.
Nested SELECTs, IN, EXISTS, and correlation.
UNION, UNION ALL, INTERSECT, and EXCEPT.
A stray NULL drops every row. Use NOT EXISTS.