SQL & Databases Asked 10 hours, 59 minutes ago

What are SQL Window Functions and how do they work?

I've heard about SQL Window Functions like RANK and ROW_NUMBER. Can someone explain them with examples?

1 Answer

U
user Answered 10 hours, 7 minutes ago

SQL Window Functions let you perform calculations across a set of rows that are related to the current row, without grouping or removing rows. They use the OVER() clause with PARTITION BY (to group rows) and ORDER BY (to define order).

Example – ranking employees by salary in each department:

SELECT employee_id, department, salary,
RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS dept_rank
FROM employees;

Common uses: ranking, running totals, moving averages, and comparing current rows with previous/next ones.

No comments yet.