NTH_VALUE function in SQL - Time & Space Complexity
We want to understand how the time to run a query using the NTH_VALUE function changes as the data grows.
Specifically, how does the number of rows affect the work done by this function?
Analyze the time complexity of the following SQL query using NTH_VALUE.
SELECT employee_id,
department_id,
salary,
NTH_VALUE(salary, 3) OVER (PARTITION BY department_id ORDER BY salary DESC) AS third_highest_salary
FROM employees;
This query finds the third highest salary in each department for every employee row.
Look for repeated work inside the query.
- Primary operation: For each department, the query orders all salaries and finds the 3rd highest.
- How many times: This ordering and value retrieval happens once per department, but the result is shown for every employee in that department.
As the number of employees grows, the work to order salaries in each department grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Ordering small groups, quick retrieval |
| 100 | More sorting per department, more rows to process |
| 1000 | Sorting larger groups, more repeated retrievals |
Pattern observation: The sorting work grows faster than the number of rows because sorting is more costly than just scanning.
Time Complexity: O(n log n)
This means the time grows a bit faster than the number of rows because sorting is involved.
[X] Wrong: "NTH_VALUE just picks a value directly, so it runs in constant time regardless of data size."
[OK] Correct: The function needs to sort the data within each partition first, which takes more time as data grows.
Understanding how window functions like NTH_VALUE scale helps you explain query performance clearly and shows you know what happens behind the scenes.
What if we changed the PARTITION BY clause to remove it? How would the time complexity change?
Practice
NTH_VALUE(column, n) do when used with an OVER() clause?Solution
Step 1: Understand the function purpose
TheNTH_VALUEfunction is designed to return a value from a specific position (n) in an ordered set of rows.Step 2: Recognize the role of
TheOVER()OVER()clause defines how rows are ordered and grouped, which is essential forNTH_VALUEto pick the correct nth value.Final Answer:
Returns the value at the nth position in the ordered set of rows. -> Option CQuick Check:
NTH_VALUE returns nth value in order [OK]
- Confusing NTH_VALUE with aggregate functions like COUNT or MAX
- Ignoring the ordering inside OVER() clause
- Assuming it returns the nth row without ordering
NTH_VALUE in SQL?Solution
Step 1: Check the function parameters
The correct order isNTH_VALUE(column, n), so salary first, then 3.Step 2: Verify the OVER clause
Ordering by salary descending (ORDER BY salary DESC) ensures the highest salaries come first, so the 3rd highest is the 3rd row.Final Answer:
SELECT NTH_VALUE(salary, 3) OVER (ORDER BY salary DESC) FROM employees; -> Option DQuick Check:
Syntax: NTH_VALUE(column, n) OVER (ORDER BY col DESC) [OK]
- Swapping parameters inside NTH_VALUE
- Missing OVER() clause or ORDER BY inside it
- Using PARTITION BY incorrectly without ORDER BY
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;
Solution
Step 1: Understand the window function without PARTITION
Since there is no PARTITION BY, the entire table is treated as one group ordered by score descending.Step 2: Effect of NTH_VALUE(score, 2) OVER (ORDER BY score DESC)
This returns the 2nd highest score value from the whole table, repeated for every row.Final Answer:
Each row shows the student's score and the 2nd highest score overall repeated. -> Option AQuick Check:
NTH_VALUE without PARTITION repeats nth value for all rows [OK]
- Thinking NTH_VALUE filters rows to nth only
- Assuming PARTITION BY is mandatory
- Confusing NTH_VALUE with ROW_NUMBER or RANK
SELECT employee_id, NTH_VALUE(salary, 1) OVER (PARTITION BY department_id) FROM employees;
Solution
Step 1: Check the OVER() clause requirements
NTH_VALUE requires an ORDER BY clause inside OVER() to define the row order for nth value selection.Step 2: Identify missing ORDER BY
The query uses PARTITION BY but lacks ORDER BY, which causes a syntax error.Final Answer:
Missing ORDER BY clause inside OVER() causes error. -> Option AQuick Check:
NTH_VALUE needs ORDER BY in OVER() [OK]
- Omitting ORDER BY inside OVER()
- Thinking PARTITION BY alone orders rows
- Swapping function parameters
Orders table with columns customer_id and order_date. Which query correctly uses NTH_VALUE to achieve this?Solution
Step 1: Use PARTITION BY to group by customer
To find the 2nd earliest order per customer, partition rows bycustomer_id.Step 2: Order each partition by order_date ascending
Ordering byorder_date ASCensures earliest dates come first.Step 3: Apply NTH_VALUE to get 2nd earliest date
NTH_VALUE with n=2 picks the 2nd row's order_date in each partition.Final Answer:
SELECT customer_id, order_date, NTH_VALUE(order_date, 2) OVER (PARTITION BY customer_id ORDER BY order_date ASC) AS second_earliest FROM Orders; -> Option BQuick Check:
Partition by customer, order by date ASC, NTH_VALUE(2) [OK]
- Missing PARTITION BY to group customers
- Ordering by wrong columns or descending order
- Using NTH_VALUE without OVER() clause
Ready to prove it?
Pass the test and this pattern moves unknown
