Create a Session Bar Chart - Problem

Given a Sessions table containing user session data, create a bar chart showing session duration distribution across predefined time bins.

You need to categorize each session into one of four bins based on duration (in seconds):

  • [0-5) - Sessions lasting 0 to 4 minutes
  • [5-10) - Sessions lasting 5 to 9 minutes
  • [10-15) - Sessions lasting 10 to 14 minutes
  • 15 or more - Sessions lasting 15 minutes or longer

Return the count of sessions for each bin in the format (bin, total). The result can be returned in any order.

Table Schema

Sessions
Column Name Type Description
session_id PK int Unique identifier for each session
duration int Session duration in seconds
Primary Key: session_id
Note: Each row represents one user session with its duration in seconds

Input & Output

Example 1 — Mixed Duration Sessions
Input Table:
session_id duration
1 20
2 399
3 462
4 843
5 1000
Output:
bin total
[0-5> 1
[5-10> 2
[10-15> 1
15 or more 1
💡 Note:

Sessions are categorized by duration: 20 seconds (0-5 min), 399 and 462 seconds (5-10 min), 843 seconds (10-15 min), and 1000 seconds (15+ min). Each bin gets counted accordingly.

Example 2 — Edge Case Boundaries
Input Table:
session_id duration
1 299
2 300
3 599
4 600
Output:
bin total
[0-5> 1
[5-10> 2
[10-15> 1
💡 Note:

Tests boundary conditions: 299 seconds is just under 5 minutes ([0-5>), while 300 seconds exactly equals 5 minutes ([5-10>). Similarly, 599 seconds is under 10 minutes, but 600 seconds equals exactly 10 minutes.

Example 3 — Single Bin Distribution
Input Table:
session_id duration
1 45
2 200
3 250
Output:
bin total
[0-5> 3
💡 Note:

All sessions fall within the first bin (under 5 minutes), so only one row is returned. Empty bins are not included in the result.

Constraints

  • 1 ≤ session_id ≤ 10^5
  • 1 ≤ duration ≤ 10^6
  • Duration is measured in seconds

Visualization

Tap to expand
Session Duration Analysis: Creating Time BinsSessions Tablesession_idduration120s2399s3462s4843sCASE WHEN Logicduration < 300 → [0-5>duration < 600 → [5-10>Bar Chart Resultbintotal[0-5>1[5-10>2[10-15>1[0-5>1[5-10>2[10-15>1Session Duration Distribution
Understanding the Visualization
1
Input Data
Sessions with duration in seconds
2
Categorization
CASE WHEN assigns bins based on duration ranges
3
Aggregation
GROUP BY bins and COUNT sessions
Key Takeaway
🎯 Key Insight: CASE WHEN statements are perfect for creating custom data bins and categories in SQL
Asked in
Meta 12 Amazon 8 Google 6
23.4K Views
Medium Frequency
~12 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen