Percentile Discrete Median Per Group
Compute the exact median per group using the percentile_disc window function with a 0.5 fraction parameter.
Code
SELECT DISTINCT
department,
PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY salary)
OVER (PARTITION BY department) AS median_salary
FROM employees
ORDER BY department;How the snippet works
At its core this is a single SELECT statement against employees.
Concretely, the SQL combines: a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order; a DISTINCT qualifier that collapses duplicate rows.
What to watch for
- Window functions evaluate after
WHERE/GROUP BY, so filtering on their output in the same-levelWHEREwill not work — use an outer query or a CTE.
Applying it
Run the statement against the employees table.
Statements that matter
SELECT DISTINCT
department,
PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY salary)
OVER (PARTITION BY department) AS median_salary
FROM employees
ORDER BY department;
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables or CTEs does it reference?
- `employees`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.