In SQL, window functions are used to perform calculations across a set of rows that are related to the current row. Window functions are similar to aggregate functions, but they do not group the rows into a single result row. Instead, they perform calculations on a "window" of rows that are specified using the OVER clause.
Here are some of the most common window functions in SQL:
ROW_NUMBER(): The ROW_NUMBER() function assigns a unique number to each row in the result set based on the order specified in the OVER clause. For example, the following query assigns a row number to each row in the employees table based on the hire_date column:
SELECT employee_id, first_name, last_name, hire_date,
ROW_NUMBER() OVER (ORDER BY hire_date) AS row_num
FROM employees;
RANK(): The RANK() function assigns a rank to each row in the result set based on the order specified in the OVER clause. Rows with the same value are assigned the same rank, and the next rank is skipped. For example, the following query assigns a rank to each row in the employees table based on the salary column:
SELECT employee_id, first_name, last_name, salary,
RANK() OVER (ORDER BY salary DESC) AS rank
FROM employees;
DENSE_RANK(): The DENSE_RANK() function is similar to RANK(), but it assigns a rank to each row in the result set based on the order specified in the OVER clause. Rows with the same value are assigned the same rank, and the next rank is not skipped. For example, the following query assigns a dense rank to each row in the employees table based on the salary column:
SELECT employee_id, first_name, last_name, salary,
DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_rank
FROM employees;
There are many other window functions available in SQL, including aggregate functions like SUM(), AVG(), and MAX(), as well as analytical functions like LEAD(), LAG(), and FIRST_VALUE(). By using window functions, you can perform powerful calculations on a set of related rows in a SQL query, making it a valuable tool for data analysis and reporting.