CUME_DIST, NTILE, And PERCENTILE_CONT On Ties
Contrast NTILE bucketing against peer-aware CUME_DIST and interpolated PERCENTILE_CONT thresholds when latency samples share tied values.
Code
CREATE TEMP TABLE latency_samples (
sample_id integer PRIMARY KEY,
latency_ms integer NOT NULL
);
INSERT INTO latency_samples VALUES
(1, 40), (2, 80), (3, 120), (4, 120), (5, 120), (6, 200);
WITH thresholds AS (
SELECT
PERCENTILE_CONT(0.50) WITHIN GROUP (ORDER BY latency_ms) AS p50_cont,
PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY latency_ms) AS p75_cont
FROM latency_samples
)
SELECT
s.sample_id,
s.latency_ms,
-- CUME_DIST gives all tied 120ms rows the identical cumulative share (5/6)
ROUND(CUME_DIST() OVER (ORDER BY s.latency_ms)::numeric, 3) AS cume_dist,
-- NTILE splits the three tied 120ms rows across different quartile buckets
NTILE(4) OVER (ORDER BY s.latency_ms, s.sample_id) AS quartile_bucket,
t.p50_cont,
t.p75_cont
FROM latency_samples s
CROSS JOIN thresholds t
ORDER BY s.latency_ms, s.sample_id;How it works
What runs here is SELECT / INSERT / CREATE — latency_samples and thresholds are the objects involved.
latency_samples spins up self-cleaning session-scoped temporary storage right inside this SQL script so zero persistent database fixtures remain after closing out.
The pieces that do the work: a CTE (WITH … AS) that names an intermediate result before the main query; one JOIN combining rows across tables; a window function (OVER (…)) evaluating aggregates over peer rows while retaining individual records; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
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.
Putting it to use
It carries its own setup: the session-local tables in play (latency_samples) come from the file’s statements — run the entire file against a disposable database.
Core lines
CREATE TEMP TABLE latency_samples (
sample_id integer PRIMARY KEY,
latency_ms integer NOT NULL
);
INSERT INTO latency_samples VALUES
(1, 40), (2, 80), (3, 120), (4, 120), (5, 120), (6, 200);
Interactive Tools for This Topic
FAQ
- Which tables or CTEs does it reference?
- The references are `latency_samples`, `thresholds`, with one join tying the pair together.
Report a problem with this exampleOpens a pre-filled issue on GitHub.