πŸŽ‰ Use coupon LEARN40 and get 40% OFF on all courses! Limited time β€” don’t miss out! - Use code:

LEANR40

SQL Window Functions

5 min read 5 views 0 comments
SQL Window Functions
SQL Window Functions

βœ… SQL Window Functions

Powerful functions to perform calculations across related rows without collapsing data πŸͺŸπŸ“Š

Window functions perform calculations across a set of rows related to the current row. Unlike GROUP BY, they do not reduce the number of rows returned.

1️⃣ ROW_NUMBER()

Assigns a unique sequential number to each row within a partition.

SELECT name, dept_id,
  ROW_NUMBER() OVER (
    PARTITION BY dept_id
    ORDER BY salary DESC
  ) AS rank
FROM employees;
πŸ“Œ Use Case: Rank employees by salary within each department.

2️⃣ RANK() vs DENSE_RANK()

Both functions rank rows, but they handle ties differently:

  • RANK() β†’ Skips numbers on ties (1, 2, 2, 4)
  • DENSE_RANK() β†’ No gaps in ranking (1, 2, 2, 3)
SELECT name, salary,
  RANK() OVER (ORDER BY salary DESC) AS rnk,
  DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_rnk
FROM employees;

3️⃣ LAG() & LEAD()

These functions allow access to values from previous or next rows.

SELECT name, salary,
  LAG(salary)  OVER (ORDER BY id) AS prev_salary,
  LEAD(salary) OVER (ORDER BY id) AS next_salary
FROM employees;
πŸ“Œ Use Case: Compare current vs previous/next values (e.g., salary changes, stock price movements, daily revenue).

4️⃣ NTILE(n)

Divides rows into n approximately equal buckets.

SELECT name,
  NTILE(4) OVER (ORDER BY salary DESC) AS quartile
FROM employees;
πŸ“Œ Use Case: Quartile analysis, percentiles, performance bands.

5️⃣ Aggregate Functions with OVER()

Allows running totals and partition-based aggregates without grouping rows.

SELECT name, dept_id, salary,
  SUM(salary) OVER (PARTITION BY dept_id) AS dept_total
FROM employees;
πŸ“Œ Use Case: Department-wise totals while retaining individual employee rows.

🧠 Interview Q&A

Q1️⃣ GROUP BY vs OVER()?
  • GROUP BY β†’ Collapses rows (one row per group)
  • OVER() β†’ Keeps all rows and adds calculated columns
Q2️⃣ When to use LAG()?

To compare the current row with previous data (e.g., daily revenue change, previous month balance).

Q3️⃣ What if PARTITION BY is not used?

The window function runs over the entire result set.

Q4️⃣ Can we use ORDER BY inside OVER()?

βœ… Yes. It is required for ranking functions, LAG/LEAD, and running totals.

πŸš€ Tip: Window functions are frequently asked in advanced SQL interviews. Master them to stand out!

Comments (0)

No comments yet

Be the first to share your thoughts!

Leave a Comment

Your email address will not be published.