Percent-of-Total & QUALIFY in SQL
Empty OVER () plus the portable filter-outside
Divide row value by grand-total window SUM() OVER () — decimal-cast first (100.0, not 100). Partitioned variants give group shares with row detail GROUP BY cannot. Windows evaluate in SELECT after WHERE — filtering needs outer query/CTE (portable) or QUALIFY (Snowflake/BigQuery) which filters post-window inline.
Grand share
salary * 100.0 / SUM(salary) OVER () — decimal first, whole result as one window.
Group share twin
OVER (PARTITION BY dept) — per-group shares with row detail intact.
Filter outside
Windows postdate WHERE — wrap in subquery/CTE, filter outside (portable).
QUALIFY shortcut
Snowflake/BigQuery filter post-window inline — same semantics, less nesting.
1SELECT name, salary, salary * 100.0 / SUM(salary) OVER () AS pct FROM employees ORDER BY salary DESC LIMIT 2;
| name | salary | pct |
|---|---|---|
| Cynthia | 91000 | 22.41 |
| Alice | 85000 | 20.94 |
Empty OVER () treats the whole result as one window — grand total 406k. Each row divides by it with decimal math. GROUP BY could total but never keep row detail beside it.
Pay share of payroll
Row detail GROUP BY cannot give.
1SELECT name, salary, salary * 100.0 / SUM(salary) OVER () AS pct FROM employees ORDER BY salary DESC LIMIT 2;
| name | salary | pct |
|---|---|---|
| Cynthia | 91000 | 22.41 |
| Alice | 85000 | 20.94 |
Top-3 per dept (portable vs QUALIFY)
Same filter, two spellings.
1SELECT * FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn FROM employees) t WHERE rn <= 3;2-- QUALIFY twin (Snowflake/BQ):3-- SELECT *, ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn FROM employees QUALIFY rn <= 3;
| department | kept |
|---|---|
| Engineering | 3 |
| Sales | 2 |
| Marketing | 1 |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.