Introduction
The NTH_VALUE function helps you find the value at a specific position in a list of values, like picking the 3rd item from a sorted list.
NTH_VALUE(expression, n) OVER (PARTITION BY column ORDER BY column [ROWS BETWEEN ...])
SELECT employee_id, salary, NTH_VALUE(salary, 2) OVER (ORDER BY salary DESC ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS second_highest_salary FROM employees;
SELECT department, employee_id, salary, NTH_VALUE(salary, 1) OVER (PARTITION BY department ORDER BY salary DESC ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS highest_salary_in_dept FROM employees;
SELECT order_id, order_date, NTH_VALUE(order_date, 3) OVER (ORDER BY order_date ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS third_order_date FROM orders;
CREATE TABLE employees (employee_id INT, department VARCHAR(20), salary INT); INSERT INTO employees VALUES (1, 'Sales', 5000), (2, 'Sales', 7000), (3, 'Sales', 6000), (4, 'HR', 4500), (5, 'HR', 4800); SELECT employee_id, department, salary, NTH_VALUE(salary, 2) OVER (PARTITION BY department ORDER BY salary DESC ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS second_highest_salary_in_dept FROM employees ORDER BY department, salary DESC;
NTH_VALUE(column, n) do when used with an OVER() clause?NTH_VALUE function is designed to return a value from a specific position (n) in an ordered set of rows.OVER()OVER() clause defines how rows are ordered and grouped, which is essential for NTH_VALUE to pick the correct nth value.NTH_VALUE in SQL?NTH_VALUE(column, n), so salary first, then 3.ORDER BY salary DESC) ensures the highest salaries come first, so the 3rd highest is the 3rd row.Scores with columns student and score, what will this query return?SELECT student, score, NTH_VALUE(score, 2) OVER (ORDER BY score DESC) AS second_highest FROM Scores;
SELECT employee_id, NTH_VALUE(salary, 1) OVER (PARTITION BY department_id) FROM employees;
Orders table with columns customer_id and order_date. Which query correctly uses NTH_VALUE to achieve this?customer_id.order_date ASC ensures earliest dates come first.Pass the test and this pattern moves unknown