TGViewer
SQL Programming Resources SQL Programming Resources @sqlanalyst ยท 76.7K subscribers
Post #2233 3.56K
โœ… SQL Window Functions ๐Ÿง ๐ŸชŸ

Window functions perform calculations across rows that are related to the current row โ€” without collapsing the result like GROUP BY.

1๏ธโƒฃ ROW_NUMBER() โ€“ Assigns a unique row number per partition
SELECT name, department,
ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rank
FROM employees;

โžค Gives ranking within each department

2๏ธโƒฃ RANK() & DENSE_RANK() โ€“ Ranking with gaps (RANK) or without gaps (DENSE_RANK)
SELECT name, salary,
RANK() OVER (ORDER BY salary DESC) AS rank
FROM employees;


3๏ธโƒฃ LAG() & LEAD() โ€“ Access previous or next row value
SELECT name, salary,
LAG(salary) OVER (ORDER BY salary) AS prev_salary,
LEAD(salary) OVER (ORDER BY salary) AS next_salary
FROM employees;

โžค Compare salary trends row-wise

4๏ธโƒฃ SUM(), AVG(), COUNT() OVER() โ€“ Running totals, moving averages, etc.
SELECT department, salary,
SUM(salary) OVER (PARTITION BY department) AS dept_total
FROM employees;


5๏ธโƒฃ NTILE(n) โ€“ Divides rows into n equal buckets
SELECT name, salary,
NTILE(4) OVER (ORDER BY salary DESC) AS quartile
FROM employees;


๐Ÿ’ก Why Use Window Functions:
โ€ข Perform row-wise calculations
โ€ข Avoid GROUP BY limitations
โ€ข Enable advanced analytics (ranking, trends, etc.)

๐Ÿงช Practice Task:
Write a query to find the top 2 earners in each department using ROW_NUMBER().

๐Ÿ’ฌ Tap โค๏ธ for more!
  • โค 6
More from @sqlanalyst
  1. Oct 13, 2026SQL Interview Series โ€” Part 8 ๐Ÿ“Œ Question 8: Find Customers Who Have Never Placed an Orderโ€ฆ
  2. Oct 13, 2026๐—ง๐—ข๐—ฃ ๐—™๐—ฅ๐—˜๐—˜ ๐—–๐—ข๐—จ๐—ฅ๐—ฆ๐—˜๐—ฆ ๐—ง๐—ข ๐—•๐—ข๐—ข๐—ฆ๐—ง ๐—ฌ๐—ข๐—จ๐—ฅ ๐—ฆ๐—ž๐—œ๐—Ÿ๐—Ÿ๐—ฆ ๐—œ๐—ก ๐Ÿฎ๐Ÿฌ๐Ÿฎ๐Ÿฒ! Explorโ€ฆ
  3. Oct 12, 2026SQL Interview Series โ€” Part 6 ๐Ÿ“Œ Question 6: Find the Top 2 Highest-Paid Employees in Eachโ€ฆ
  4. Oct 12, 2026๐Ÿš€ ๐—ช๐—ต๐—ถ๐—ฐ๐—ต ๐—ง๐—ฒ๐—ฐ๐—ต ๐—ฆ๐—ธ๐—ถ๐—น๐—น ๐—ช๐—ถ๐—น๐—น ๐—ฌ๐—ผ๐˜‚ ๐— ๐—ฎ๐˜€๐˜๐—ฒ๐—ฟ ๐—ถ๐—ป ๐Ÿฎ๐Ÿฌ๐Ÿฎ๐Ÿฒ? Want to builโ€ฆ
  5. Oct 9, 2026SQL Interview Series โ€” Part 5 ๐Ÿ“Œ Question 5: Find Employees Who Earn More Than Their Managโ€ฆ
  6. Oct 9, 2026๐Ÿ‡ฎ๐Ÿ‡ณ ๐—š๐—ข๐—ฉ๐—˜๐—ฅ๐—ก๐— ๐—˜๐—ก๐—ง ๐—ข๐—™ ๐—œ๐—ก๐——๐—œ๐—” โ€” ๐—”๐—œ๐—–๐—ง๐—˜ ๐—œ๐—ก๐—ง๐—˜๐—ฅ๐—ก๐—ฆ๐—›๐—œ๐—ฃ๐—ฆ ๐Ÿฎ๐Ÿฌ๐Ÿฎ๐Ÿฒ ๐Ÿš€โ€ฆ
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook โ†’Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 โ†’