MediumAggregations
Hospital Formulary Drug Dispensation & Expenditure
Frequently Asked By:AppleGoogleAmazon
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 `pharmacy_dispensations` by `drug_category`.
Calculate:
1. `drug_category`
2. `distinct_patients`: Count of unique `patient_id` recipients
3. `total_units_dispensed`: Sum of `units_dispensed`
4. `total_expenditure`: Sum of (`units_dispensed * unit_cost`)
Order results by `total_expenditure` descending.
Why Technical Interviewers Ask This
Hospital pharmacy leadership is auditing pharmaceutical procurement costs across inpatient units. They need to aggregate expenditures per drug classification to pinpoint medications driving high clinical costs.
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
drug_category,
COUNT(DISTINCT patient_id) AS distinct_patients,
SUM(units_dispensed) AS total_units_dispensed,
SUM(units_dispensed * unit_cost) AS total_expenditure
FROM pharmacy_dispensations
GROUP BY drug_category
ORDER BY total_expenditure DESC;Approach Breakdown
This query addresses the problem requirements by filtering and structuring data in Aggregations. It meets the target criteria: Summary of pharmaceutical spending per drug category sorted by total cost.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 Apple 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.