MediumAggregations
Departmental Salary Compression & Range Spread
Frequently Asked By:GoogleMetaMicrosoft
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 `payroll_records` by `department`.
Calculate:
1. `department`
2. `headcount`: Total employees in that department
3. `min_salary`: Minimum `base_salary`
4. `max_salary`: Maximum `base_salary`
5. `avg_salary`: Average `base_salary` rounded to 2 decimal places
6. `salary_spread`: The difference between `max_salary` and `min_salary` (`MAX(base_salary) - MIN(base_salary)`)
Order results by `salary_spread` in **descending** order.
Why Technical Interviewers Ask This
Executive leadership and the HR Compensation Board are conducting an annual pay equity audit to identify departments with extreme wage inequality or salary compression.
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
department,
COUNT(*) AS headcount,
MIN(base_salary) AS min_salary,
MAX(base_salary) AS max_salary,
ROUND(AVG(base_salary), 2) AS avg_salary,
(MAX(base_salary) - MIN(base_salary)) AS salary_spread
FROM payroll_records
GROUP BY department
ORDER BY salary_spread DESC;Approach Breakdown
This query addresses the problem requirements by filtering and structuring data in Aggregations. It meets the target criteria: Department compensation metrics including min, max, avg, and wage spread, sorted by spread descending.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 Google and Meta 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.