Lesson Description
Use analytical SQL to rank, compare, and calculate trends across partitions without losing row-level detail.
Lesson 3 of 4
Progress: 0/3 exercises solved (0%)
Solve all exercises below to unlock the next lesson.
Lesson Description
Use analytical SQL to rank, compare, and calculate trends across partitions without losing row-level detail.
Easy Project
Mini project: Build a compensation ranking dashboard query with department-level rank and delta from the top earner.
These window functions assign relative positions to rows within an ordered set.
Assigns each row a bucket number from 1 to n. Useful for quartiles, deciles, percentiles.
SELECT
first_name, salary,
NTILE(4) OVER (ORDER BY salary ASC) AS quartile
FROM employees;
NTILE(4) OVER (PARTITION BY department_id ORDER BY salary).PERCENT_RANK = (rank - 1) / (total rows - 1)
SELECT
first_name, salary,
ROUND(PERCENT_RANK() OVER (ORDER BY salary) * 100, 1) AS pct_rank
FROM employees;
A value of 0.90 means the employee earns more than 90% of colleagues.
Similar to PERCENT_RANK but counts the current row in the numerator:
SELECT
first_name, salary,
ROUND(CUME_DIST() OVER (ORDER BY salary) * 100, 1) AS cume_pct
FROM employees;
CUME_DIST is always > 0; PERCENT_RANK of the lowest row is always 0.
WITH quartiled AS (
SELECT first_name, salary,
NTILE(4) OVER (ORDER BY salary ASC) AS quartile
FROM employees
)
SELECT first_name, salary
FROM quartiled
WHERE quartile = 4
ORDER BY salary DESC;
NTILE for segmentation (top/middle/bottom); use PERCENT_RANK for exact relative positioning.NTILE requires an ORDER BY inside OVER().NTILE(100) gives percentiles (1–100).This lesson is part of Window Functions. Focus on the core idea in NTILE and PERCENT_RANK — statistical ranking, then validate with deliberate practice.
What to master
Common mistakes
High-level strategy
Task ladder
Transparent data checks
Retention loop
Logical reasoning for commands
WHERE
Why: Limits rows to only the business-relevant subset.
Memory cue: Filter early to reduce noise.
ORDER BY
Why: Makes output deterministic and reviewable.
Memory cue: No ORDER BY means no guaranteed row order.
AS alias
Why: Makes output columns readable for teams and reports.
Memory cue: If the name is clear, the query is easier to trust.
Concept check
3 quick questions. One at a time. Instant score at the end.
Return first_name, last_name, salary, and quartile (1–4) using NTILE(4) ordered by salary ascending. Quartile 1 = lowest earners. Order by quartile, then salary.
Return first_name, last_name, salary, and pct_rank — the PERCENT_RANK() (multiplied by 100 and rounded to 2 decimal places) of each employee ordered by salary. Order by salary.
Using a CTE with NTILE(4), return only the employees in the top salary quartile (quartile = 4). Show first_name, last_name, and salary, ordered by salary descending.
Lesson 3 of 4
0/3 solved (0%)
Finish this lesson to unlock next.