MediumAggregations
Daily Active Workspaces & Action Frequency
Frequently Asked By:MicrosoftGoogleStripe
Interactive In-Browser Workspace
Practice this problem on live schema tables in PostgreSQL 16 WASM with instant row verification and visual EXPLAIN plans.
Problem Statement
Group records in `app_events` by `subscription_tier`.
Calculate:
1. `subscription_tier`
2. `total_events`: Total count of event records
3. `unique_workspaces`: Count of distinct `workspace_id` values
4. `avg_events_per_workspace`: `ROUND(CAST(COUNT(*) AS NUMERIC) / COUNT(DISTINCT workspace_id), 1)`
Order results by `total_events` descending.
Why Technical Interviewers Ask This
Product analytics wants to evaluate engagement depth across organization subscription plans. They need to count how many distinct workspaces are active and determine the average actions performed per active workspace.
Common Pitfalls & Interview Traps
Forgetting required sorting and deterministic tie-breaking.
Not accounting for NULL or zero-value denominators during calculations.
Using inefficient quadratic subqueries instead of single-pass aggregations constructs.
Canonical Modern SQL Solution
PostgreSQL 16 / ANSI SQLSELECT
subscription_tier,
COUNT(*) AS total_events,
COUNT(DISTINCT workspace_id) AS unique_workspaces,
ROUND(CAST(COUNT(*) AS NUMERIC) / COUNT(DISTINCT workspace_id), 1) AS avg_events_per_workspace
FROM app_events
GROUP BY subscription_tier
ORDER BY total_events DESC;Approach Breakdown
This query addresses the problem requirements by filtering and structuring data in Aggregations. It meets the target criteria: Plan tiers showing total events, unique active workspaces, and events per workspace.Edge Cases to Verbally Clarify with Your Interviewer
The dataset contains zero matching records (must return valid empty result without crashing).
Multiple records tie on sorting criteria (must evaluate tie-breaking order deterministically).
Foreign keys or secondary attributes have NULL values.
Frequently Asked Follow-Up Questions
What makes this question a favorite among Microsoft and Google interviewers?
Interviewers use this problem to test whether candidates write defensive, scalable Aggregations queries that run efficiently on multi-million row production databases without excessive memory usage.
How does the query optimizer execute this query?
Using single-pass table scans with index lookups or sort buffers. Running EXPLAIN (ANALYZE, BUFFERS) in the DB Exercises workbench visualizes the execution nodes and buffer hit cache.