MediumCTEs
Departmental Headcount and Compensation Budget Cap
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
Write a query using a CTE `dept_payroll` that computes total payroll and headcount per department from `dept_employees`.
Join the CTE with `dept_budgets` on `dept_id`.
Return:
1. `b.dept_name`
2. `p.headcount`
3. `p.total_payroll`
4. `b.budget_cap`
5. `budget_utilization_pct`: `ROUND(p.total_payroll * 100.0 / b.budget_cap, 1)`
Order results by `budget_utilization_pct` descending, then by `b.dept_name` ascending.
Why Technical Interviewers Ask This
FP&A finance controllers monitor departmental payroll spend against annual operating budget allocations to flag departments nearing compensation caps.
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 ctes constructs.
Canonical Modern SQL Solution
PostgreSQL 16 / ANSI SQLWITH dept_payroll AS (
SELECT
dept_id,
COUNT(*) AS headcount,
SUM(salary) AS total_payroll
FROM dept_employees
GROUP BY dept_id
)
SELECT
b.dept_name,
p.headcount,
p.total_payroll,
b.budget_cap,
ROUND(p.total_payroll * 100.0 / b.budget_cap, 1) AS budget_utilization_pct
FROM dept_payroll p
JOIN dept_budgets b ON p.dept_id = b.dept_id
ORDER BY budget_utilization_pct DESC, b.dept_name ASC;Approach Breakdown
This query addresses the problem requirements by filtering and structuring data in CTEs. It meets the target criteria: Departmental payroll utilization percentages compared against budget caps.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 CTEs 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.