Bird
Raised Fist0
SQLquery~20 mins

NTH_VALUE function in SQL - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
NTH_VALUE Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate
2:00remaining
Output of NTH_VALUE with simple partition
Given the table sales with columns region and amount, what is the output of the following query?

SELECT region, amount, NTH_VALUE(amount, 2) OVER (PARTITION BY region ORDER BY amount ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS second_amount FROM sales;
SQL
CREATE TABLE sales (region VARCHAR(10), amount INT);
INSERT INTO sales VALUES
('East', 100), ('East', 200), ('East', 300),
('West', 150), ('West', 250);

SELECT region, amount, NTH_VALUE(amount, 2) OVER (PARTITION BY region ORDER BY amount ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS second_amount FROM sales ORDER BY region, amount;
A[{'region': 'East', 'amount': 100, 'second_amount': 200}, {'region': 'East', 'amount': 200, 'second_amount': 200}, {'region': 'East', 'amount': 300, 'second_amount': 200}, {'region': 'West', 'amount': 150, 'second_amount': 250}, {'region': 'West', 'amount': 250, 'second_amount': 250}]
B[{'region': 'East', 'amount': 100, 'second_amount': 100}, {'region': 'East', 'amount': 200, 'second_amount': 200}, {'region': 'East', 'amount': 300, 'second_amount': 300}, {'region': 'West', 'amount': 150, 'second_amount': 150}, {'region': 'West', 'amount': 250, 'second_amount': 250}]
C[{'region': 'East', 'amount': 100, 'second_amount': 100}, {'region': 'East', 'amount': 200, 'second_amount': 100}, {'region': 'East', 'amount': 300, 'second_amount': 100}, {'region': 'West', 'amount': 150, 'second_amount': 150}, {'region': 'West', 'amount': 250, 'second_amount': 150}]
D[{'region': 'East', 'amount': 100, 'second_amount': null}, {'region': 'East', 'amount': 200, 'second_amount': null}, {'region': 'East', 'amount': 300, 'second_amount': null}, {'region': 'West', 'amount': 150, 'second_amount': null}, {'region': 'West', 'amount': 250, 'second_amount': null}]
Attempts:
2 left
💡 Hint
Remember that NTH_VALUE returns the value of the nth row in the window frame, ordered by the ORDER BY clause.
🧠 Conceptual
intermediate
2:00remaining
Understanding frame specification impact on NTH_VALUE
What happens if you run the query below on a table orders with columns customer_id and order_date? Assume multiple orders per customer.

SELECT customer_id, order_date, NTH_VALUE(order_date, 3) OVER (PARTITION BY customer_id ORDER BY order_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS third_order_date FROM orders;

Which statement is true?
AThe function returns the third earliest order date for each customer for all rows.
BThe function returns the third order date only if the frame includes at least three rows; otherwise, it returns NULL.
CThe function always returns the third order date of the entire table, ignoring partitions.
DThe function returns NULL for the first two orders and the third order date starting from the third row onward per customer.
Attempts:
2 left
💡 Hint
Consider how the frame defined by ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW changes as the window moves.
📝 Syntax
advanced
2:00remaining
Identify the syntax error in NTH_VALUE usage
Which of the following queries will cause a syntax error?
ASELECT NTH_VALUE(salary, 1) OVER (ORDER BY salary) FROM employees;
BSELECT NTH_VALUE(salary, 3) OVER (ORDER BY salary ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) FROM employees;
CSELECT NTH_VALUE(salary, 2) OVER (PARTITION BY department ORDER BY salary) FROM employees;
DSELECT NTH_VALUE(salary, 0) OVER (ORDER BY salary) FROM employees;
Attempts:
2 left
💡 Hint
Check the valid range for the second argument of NTH_VALUE.
❓ optimization
advanced
2:00remaining
Optimizing NTH_VALUE with large datasets
You have a large transactions table with millions of rows. You want to find the 5th highest transaction amount per customer using NTH_VALUE. Which approach is most efficient?
AUse NTH_VALUE(amount, 5) OVER (PARTITION BY customer_id ORDER BY amount DESC) without frame clause.
BUse NTH_VALUE(amount, 5) OVER (PARTITION BY customer_id ORDER BY amount DESC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW).
CUse a subquery with ROW_NUMBER() to filter the 5th row per customer instead of NTH_VALUE.
DUse NTH_VALUE(amount, 5) OVER (ORDER BY amount DESC) without partitioning.
Attempts:
2 left
💡 Hint
Consider performance implications of window functions on large data and alternatives.
🔧 Debug
expert
3:00remaining
Debugging unexpected NULLs from NTH_VALUE
You run this query:

SELECT employee_id, salary, NTH_VALUE(salary, 3) OVER (PARTITION BY department ORDER BY salary) AS third_salary FROM employees;

But you notice that third_salary is NULL for some employees even though their department has more than three employees. What is the most likely cause?
AThe default window frame is ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, so the frame may not include the third row yet.
BNTH_VALUE always returns NULL if the partition has more than 3 rows.
CThe ORDER BY clause is missing in the window function.
DThe salary column contains NULL values causing NTH_VALUE to return NULL.
Attempts:
2 left
💡 Hint
Think about how the default frame affects which rows are visible to the function at each row.

Practice

(1/5)
1. What does the SQL function NTH_VALUE(column, n) do when used with an OVER() clause?
easy
A. Returns the maximum value in the column.
B. Returns the total count of rows in the table.
C. Returns the value at the nth position in the ordered set of rows.
D. Returns the first value in the column without ordering.

Solution

  1. Step 1: Understand the function purpose

    The NTH_VALUE function is designed to return a value from a specific position (n) in an ordered set of rows.
  2. Step 2: Recognize the role of OVER()

    The OVER() clause defines how rows are ordered and grouped, which is essential for NTH_VALUE to pick the correct nth value.
  3. Final Answer:

    Returns the value at the nth position in the ordered set of rows. -> Option C
  4. Quick Check:

    NTH_VALUE returns nth value in order [OK]
Hint: NTH_VALUE picks the nth row's value after ordering [OK]
Common Mistakes:
  • Confusing NTH_VALUE with aggregate functions like COUNT or MAX
  • Ignoring the ordering inside OVER() clause
  • Assuming it returns the nth row without ordering
2. Which of the following is the correct syntax to get the 3rd highest salary using NTH_VALUE in SQL?
easy
A. SELECT NTH_VALUE(salary, 3) OVER (PARTITION BY salary) FROM employees;
B. SELECT NTH_VALUE(salary, 3) FROM employees ORDER BY salary DESC;
C. SELECT NTH_VALUE(3, salary) OVER (ORDER BY salary DESC) FROM employees;
D. SELECT NTH_VALUE(salary, 3) OVER (ORDER BY salary DESC) FROM employees;

Solution

  1. Step 1: Check the function parameters

    The correct order is NTH_VALUE(column, n), so salary first, then 3.
  2. 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.
  3. Final Answer:

    SELECT NTH_VALUE(salary, 3) OVER (ORDER BY salary DESC) FROM employees; -> Option D
  4. Quick Check:

    Syntax: NTH_VALUE(column, n) OVER (ORDER BY col DESC) [OK]
Hint: NTH_VALUE(column, n) needs OVER with ORDER BY for ranking [OK]
Common Mistakes:
  • Swapping parameters inside NTH_VALUE
  • Missing OVER() clause or ORDER BY inside it
  • Using PARTITION BY incorrectly without ORDER BY
3. Given the table 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;
medium
A. Each row shows the student's score and the 2nd highest score overall repeated.
B. Each row shows the student's score and their own 2nd highest score.
C. The query returns only the row with the 2nd highest score.
D. The query returns an error because NTH_VALUE needs PARTITION BY.

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    Each row shows the student's score and the 2nd highest score overall repeated. -> Option A
  4. Quick Check:

    NTH_VALUE without PARTITION repeats nth value for all rows [OK]
Hint: Without PARTITION, NTH_VALUE repeats same nth value for all rows [OK]
Common Mistakes:
  • Thinking NTH_VALUE filters rows to nth only
  • Assuming PARTITION BY is mandatory
  • Confusing NTH_VALUE with ROW_NUMBER or RANK
4. Identify the error in this SQL query:
SELECT employee_id, NTH_VALUE(salary, 1) OVER (PARTITION BY department_id) FROM employees;
medium
A. Missing ORDER BY clause inside OVER() causes error.
B. NTH_VALUE cannot be used with PARTITION BY.
C. The function parameters are in wrong order.
D. No error; query is correct.

Solution

  1. 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.
  2. Step 2: Identify missing ORDER BY

    The query uses PARTITION BY but lacks ORDER BY, which causes a syntax error.
  3. Final Answer:

    Missing ORDER BY clause inside OVER() causes error. -> Option A
  4. Quick Check:

    NTH_VALUE needs ORDER BY in OVER() [OK]
Hint: Always include ORDER BY inside OVER() with NTH_VALUE [OK]
Common Mistakes:
  • Omitting ORDER BY inside OVER()
  • Thinking PARTITION BY alone orders rows
  • Swapping function parameters
5. You want to find the 2nd earliest order date for each customer in the Orders table with columns customer_id and order_date. Which query correctly uses NTH_VALUE to achieve this?
hard
A. SELECT customer_id, order_date, NTH_VALUE(order_date, 2) FROM Orders GROUP BY customer_id;
B. 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;
C. SELECT customer_id, order_date, NTH_VALUE(order_date, 2) OVER (ORDER BY customer_id, order_date ASC) AS second_earliest FROM Orders;
D. SELECT customer_id, NTH_VALUE(order_date, 2) FROM Orders ORDER BY order_date ASC;

Solution

  1. Step 1: Use PARTITION BY to group by customer

    To find the 2nd earliest order per customer, partition rows by customer_id.
  2. Step 2: Order each partition by order_date ascending

    Ordering by order_date ASC ensures earliest dates come first.
  3. 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.
  4. 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 B
  5. Quick Check:

    Partition by customer, order by date ASC, NTH_VALUE(2) [OK]
Hint: Partition by group, order ascending, then NTH_VALUE(n) [OK]
Common Mistakes:
  • Missing PARTITION BY to group customers
  • Ordering by wrong columns or descending order
  • Using NTH_VALUE without OVER() clause
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard