Second Highest Value

An easy SQL interview practice problem on DataDriven. Write the query and run it against a real database, with instant feedback.

Domain
SQL
Difficulty
easy
Seniority
L3
Asked in
Calix

Problem

Find the second-highest metric value across the entire employee metrics table. Multiple employees might share the top spot; the second-highest is the next unique value below them. Return a single number.

Almost the top. Not quite.

Tables

employee_metrics

Columns: metric_id INTEGER, department TEXT, metric_name TEXT, metric_value REAL, fiscal_quarter TEXT, fiscal_year INTEGER

employee_metrics: 10 of 200 rows
metric_iddepartmentmetric_namemetric_valuefiscal_quarterfiscal_year
141Productattrition_rate7.3Q22025
182Designavg_tenure_months14.6Q32026
223Marketingsatisfaction_score21.9Q42024
264Salestraining_hours29.2Q12025
305HRpromotions36.5Q22026
346Financeopen_positions43.8Q32024
387Legaltime_to_hire_days51.1Q42025
428Operationsdiversity_ratio58.4Q12026
469Dataremote_percentage65.7Q22024
510Engineeringheadcount73Q32025

Expected output

First 1 of 1 rows
metric_value
98.6

Worked solution and explanation

Why this problem exists in real interviews

This challenge asks you to apply DENSE_RANK for gapless ranking to the employee_metrics table, simulating a real analytics workflow. Pay attention to the metric_value column as they drive the aggregation and output.


Break down the requirements

Step 1: Apply the WHERE filter

Filter rows before any aggregation. This ensures only qualifying data enters the computation, keeping the result correct and the scan minimal.

Step 2: Rank results with a window function

DENSE_RANK() assigns consecutive ranks without gaps. Unlike ROW_NUMBER(), tied values share the same rank, which matters when the prompt asks for ties.

Step 3: Use a subquery to find the reference value

The scalar subquery computes a single value (like the maximum) that the outer query filters against. This avoids a self-join.


The solution

Dense-rank for second highest value
SELECT metric_value
FROM (SELECT DISTINCT metric_value, DENSE_RANK() OVER (ORDER BY metric_value DESC) AS rnk FROM employee_metrics) ranked
WHERE rnk = 2

Common follow-up questions