ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

PostgreSQL Advanced Architect Tutorial• 7 min read

Window Functions: ROW_NUMBER, RANK & LAG

Perform advanced analytical calculations across table partitions without collapsing rows: running totals, ranks, and lag values.

The OVER (PARTITION BY ... ORDER BY ...) Clause

Unlike GROUP BY which collapses rows into a single summary, window functions compute values across an active row window while preserving individual row identity.

Leaderboard Ranking by Department
SELECT 
    employee_name,
    department,
    salary,
    ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS dept_rank,
    SUM(salary) OVER (PARTITION BY department) AS dept_total
FROM employees;
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which window function retrieves values from the previous row within the current window partition?