Window Functions Questions
Window Functions Questions
Answer:
● Window Function: Performs a calculation across a set of rows that are related to the
current row, without collapsing the result into a single row.
● Aggregate Function: Aggregates multiple rows into a single output (e.g., SUM(),
AVG()).
Example:
Answer:
3. How do RANK() and DENSE_RANK() differ in SQL? When would you use
each one?
Answer:
Window Function in SQL
● RANK(): Assigns a rank with gaps in ranking for ties.
● DENSE_RANK(): Assigns rank without gaps.
Example:
RANK Example
SELECT name, salary, RANK() OVER (ORDER BY salary DESC) AS salary_rank
FROM employees;
DENSE_RANK Example
SELECT name, salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS
salary_rank FROM employees;
Answer:
● PARTITION BY divides the result set into partitions and applies the window function
within each partition.
Example:
5. What is the difference between LAG() and LEAD() functions? How would
you use them in a real-world scenario?
Answer:
6. How can you calculate a running total (cumulative sum) using a window
function in SQL?
Example:
7. Write a query to calculate the moving average of sales over the last 3
months for each product.
Answer:
This calculates a 3-month moving average (current month and 2 preceding months).
8. How would you calculate the percentage of total for each row using a
window function?
Answer:
Answer:
10. What is the difference between OVER() with PARTITION BY and OVER()
with ORDER BY?
Answer:
● PARTITION BY: Groups rows into partitions where the window function is applied
independently.
● ORDER BY: Orders rows within a partition to apply the window function.
Example:
11. How would you calculate the first and last value in a partitioned dataset
using window functions?
Answer: You can use LAG() to compare the current year’s sales with the previous year.
Example:
13. Given a table of employee salaries, how would you rank employees by
salary within each department using window functions?
Answer:
sql
Copy code
SELECT name, department, salary,
RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS
department_rank
FROM employees;
Window Function in SQL
14. What are the performance considerations when using window functions
in large datasets, and how can you optimize them?
Answer:
● Performance Considerations:
○ Window functions can be computationally expensive on large datasets.
○ Sorting large partitions can be costly.
● Optimization:
○ Ensure indexes are on partitioning and ordering columns.
○ Minimize the number of rows in partitions.
○ Use ROWS instead of RANGE when possible for performance gains.
15. How can you use window functions to identify duplicate rows or
records based on specific criteria?
Example:
WITH CTE AS (
SELECT name, salary, ROW_NUMBER() OVER (PARTITION BY name, salary
ORDER BY name) AS row_num
FROM employees
)
SELECT * FROM CTE WHERE row_num > 1;
This identifies duplicate rows based on the name and salary columns.