Window Functions Flashcards
Which clauses can a window function be called in?
The SELECT and ORDER BY clauses
What is the difference between a window function and GROUP BY?
What does this query do?
SELECT first_name, department, salary, LEAD(first_name) OVER (ORDER BY salary ASC) prev_sal_name FROM employees
It returns first_name, department, salary, and the first name of the person with the next highest salary out of all employees.
What does this query do?
SELECT first_name, department, salary, LAG(first_name) OVER (PARTITION BY department ORDER BY salary ASC) prev_salary FROM employees
It returns theIt returns first_name, department, salary, and the first name of the person with the next lowest salary from the employee’s respective department.
What types of functions are LEAD(), LAG(), FIRST_VALUE(),
and LAST_VALUE()
?
Positional functions
What is a critical part of a window function when using positional functions?
ORDER BY, because positional functions are entirely dependent on the order of the values within the window
T/F: using OVER() without any info inside of its parentheses will fail
False, it will run on the entire data set as its partition
What is the purpose of the PARTITION BY clause in this query?
SELECT MAX(salary) OVER (PARTITION BY department) max_salary FROM employees
It specifies the window in which to aggregate the data. In this case, it is specifying ‘department’ as the partition over which to aggregate salary.