SQL PERCENT_RANK function
Returns the relative rank of a row: (RANK - 1) / (partition rows - 1), a fraction between 0 and 1 where the first row is always 0.
- Catégorie
- Fenêtre
- Returns
double precision / float- In this category
- 9 of 79
Syntaxe
PERCENT_RANK() OVER (PARTITION BY g ORDER BY x)
Prise en charge des moteurs
| Moteur | Support | Notes |
|---|---|---|
| SQL Server | Oui | Supported under this name. |
| PostgreSQL | Oui | Supported under this name. |
| MySQL | Oui | MySQL 8.0+ |
| SQLite | Oui | SQLite 3.25+ |
| Oracle | Oui | Supported under this name. |
Exemples
Any engine
SELECT name, points,
PERCENT_RANK() OVER (ORDER BY points DESC) AS pct
FROM players;
Any engine
-- top 10% by spend within each region WITH r AS ( SELECT c.*, PERCENT_RANK() OVER (PARTITION BY region ORDER BY spend DESC) AS pct FROM customers c ) SELECT * FROM r WHERE pct <= 0.1;
Bon à savoir
- The first row in every partition is exactly 0, and the last row's value depends on partition size: with 4 rows the fractions are 0, 0.333, 0.667, 1.
- Tied ORDER BY values share the same PERCENT_RANK because they share the same RANK; use ROW_NUMBER when ties must break differently.
- A single-row partition returns 0, not a division-by-zero error: the denominator (rows - 1) is guarded.
Questions about PERCENT_RANK
What is the difference between PERCENT_RANK and CUME_DIST?
PERCENT_RANK is (RANK - 1) / (rows - 1): the first row is 0. CUME_DIST is peers-at-or-below / total rows: the first row is above 0 and the last is exactly 1. For cutoffs like 'top 10%', both work, but CUME_DIST counts ties together.
Does PERCENT_RANK return 0 or 1 for the best row?
0 for the first row in ORDER BY direction, 1 for the last. If you want the leader to be 1, use 1 - PERCENT_RANK() or order ascending.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.