Sobes.tech
Junior — Middle

Explain what window functions are in database management systems and how they are used.

sobes.tech AI

Answer from AI

Window functions in database management systems are functions that perform calculations across a set of table rows that are related to the current row, without collapsing the result set into a single row like aggregate functions do.

They allow, for example, to compute moving sums, rank rows, calculate averages over a window of rows, etc., while preserving all the rows in the result.

An example of using a window function in SQL:

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

Here, the salary rank is calculated within each department for each employee, while all employees remain in the result.