SQL Aggregations, Joins, Pandas Combines, and Nth Highest Salary
Medium · Data Manipulation (SQL/Python) · Data Scientist · Onsite
Problem Statement
Consider two relational tables used for workforce analytics alongside pandas DataFrames in Python:
employees
| Column | Type | Description |
|---|---|---|
id |
INTEGER |
Primary key identifying each employee |
name |
VARCHAR |
Employee display name |
salary |
INTEGER |
Annual compensation (nullable) |
dept_id |
INTEGER |
Foreign key referencing departments.id (nullable) |
departments
| Column | Type | Description |
|---|---|---|
id |
INTEGER |
Primary key identifying each department |
dept_name |
VARCHAR |
Department name |
Sample table contents:
employees departments
+----+------+--------+---------+ +----+-------------+
| id | name | salary | dept_id | | id | dept_name |
+----+------+--------+---------+ +----+-------------+
| 1 | Maya | 95000 | 1 | | 1 | Engineering |
| 2 | Liam | 120000 | 2 | | 2 | Analytics |
| 3 | Nora | 105000 | 1 | | 3 | Legal |
+----+------+--------+---------+ +----+-------------+
Graded Coding Deliverable
Implement nth_highest_salary(salaries: List[int], n: int) -> Optional[int] in Python (and write the equivalent SQL query returning a single row and single column nth_highest_salary for rank N, such as N = 2 on employees):
- Return the
n-th largest distinct non-null salary (n = 1is the maximum,n = 2is the second largest unique value, and so on). - Ignore
None(NULLin SQL) entries, while treating0as a valid numeric salary. - Return
None(or a singleNULLrow in SQL) whenevern < 1or fewer thanndistinct non-null salaries exist.
Conceptual & Practical Discussion Topics
In an interview walkthrough, also be prepared to cover:
- Aggregate functions: How
COUNT,SUM,AVG,MIN, andMAXbehave—especially aroundNULLentries and empty groups. - Relational joins: How
INNER,LEFT,RIGHT, andFULL OUTERjoins match rows, with one realistic business scenario per join type. - Set stacking: How
UNIONandUNION ALLdiffer in duplicate handling and runtime cost, and when each is appropriate. - Windowed calculations: What
OVER (...)window functions compute and how they differ fromGROUP BYaggregations. - Views vs. base tables: Storage, freshness, security, and performance trade-offs between virtual views and physical tables.
- Duplicate handling: How to suppress duplicate records in a
SELECToutput without altering stored data, versus how to delete duplicate rows permanently from a table. - SQL performance tuning: Concrete indexing and query-writing habits that eliminate unnecessary table scans and sorts.
- DataFrame combining in pandas: How
pd.merge,DataFrame.join, andpd.concatalign rows or columns and when to reach for each.
Examples
Example 1
Input: salaries = [95000, 120000, 105000], n = 1
Output: 120000
Explanation: Ordered from highest to lowest, the unique salaries are [120000, 105000, 95000]. Rank 1 is 120000.
Example 2
Input: salaries = [95000, 120000, 105000], n = 2
Output: 105000
Explanation: Among [120000, 105000, 95000], the second highest distinct salary (matching the SQL query with N = 2 on the sample employees table above) is 105000.
Example 3
Input: salaries = [60000, 85000], n = 3
Output: None
Explanation: Only 2 distinct salaries are present, so no 3rd highest distinct value exists.
Example 4
Input: salaries = [500, 800, 800, 650], n = 2
Output: 650
Explanation: Both copies of 800 share rank 1. Collapsing duplicates leaves [800, 650, 500], making 650 the 2nd highest distinct salary.
Constraints
0 <= len(salaries) <= 10^5- Elements of
salariesare non-negative integers (0is valid) orNone(NULL). -10^5 <= n <= 10^5; anyn < 1ornexceeding the count of distinct non-null salaries returnsNone.
Step-by-step walkthrough
Understand the scenario and the graded deliverable
This interview prompt pairs a comprehensive walkthrough of relational SQL and pandas operations with a graded coding deliverable: computing the Nth highest distinct salary (tested in Python via
nth_highest_salary(salaries, n)and in SQL on theemployeestable forN = 2).Let us start with the two sample tables from the problem:
employees departments +----+------+--------+---------+ +----+-------------+ | id | name | salary | dept_id | | id | dept_name | +----+------+--------+---------+ +----+-------------+ | 1 | Maya | 95000 | 1 | | 1 | Engineering | | 2 | Liam | 120000 | 2 | | 2 | Analytics | | 3 | Nora | 105000 | 1 | | 3 | Legal | +----+------+--------+---------+ +----+-------------+For the graded
nth_highest_salary(salaries, n)task: -salariesis a list of compensation figures (whereNonerepresents a SQLNULL). -nis a 1-based rank (n = 1asks for the top salary,n = 2for the 2nd highest, and so on). - We must return then-th highest distinct non-NULLsalary, orNone(NULLin SQL) ifn < 1or fewer thanndistinct salaries exist.Why does distinct matter? Look at
Example 4([500, 800, 800, 650]withn = 2): - Rank 1 (highest):800(shared by two employees) - Rank 2 (2nd highest):650So the 2nd highest distinct salary is
650, not the second copy of800.Why naive sorting or pairwise counting falls short
Two first-instinct approaches run into trouble:
- Sorting the raw list without deduplicating: If we sort
[500, 800, 800, 650]in descending order ([800, 800, 650, 500]) and read indexn - 1 = 1, we get800instead of650because duplicate values push lower ranks further right. - Counting higher salaries for every row: We can test each candidate salary by scanning the whole list and counting how many distinct salaries are strictly greater than it (the candidate with
n - 1distinct salaries above it wins). In SQL, this is called a correlated subquery — an inner query that re-executes once for every row of the outer query. While correct, comparing every pair ofmemployees takesO(m^2)work (10^10comparisons for100,000rows).
- Sorting the raw list without deduplicating: If we sort
Python solution: deduplicate, guard bounds, and sort
Once we collapse duplicate salaries first, the problem shrinks to sorting unique numbers:
- Guard
n < 1: there is no 0th or negative rank. Without this check,n = 0would computehighest_first[0 - 1] = highest_first[-1], which in Python silently wraps around to the lowest salary instead of returningNone! - Insert every non-
Nonesalary into a hash setdistinct_salaries. Usesalary is not Nonerather thanif salary:so a legitimate salary of0is not discarded. - Guard
n > len(distinct_salaries): if fewer thannunique salaries exist, returnNonebefore indexing. - Sort
distinct_salariesin descending order (reverse=True) and returnhighest_first[n - 1].
Trace on Example 4: salaries = [500, 800, 800, 650], n = 2 1. n = 2 >= 1 -> valid rank 2. distinct_salaries = {500, 650, 800} (both 800s collapse into one) 3. n = 2 <= len(distinct_salaries)=3 -> enough distinct values 4. highest_first = [800, 650, 500] 5. highest_first[2 - 1] = 650 -> returns 650def nth_highest_salary(salaries: List[int], n: int) -> Optional[int]: # Guard invalid ranks: ranks are 1-based, and n <= 0 would make (n - 1) negative, # causing Python list indexing to wrap around to the tail of the sorted list. if n < 1: return None # Phase 1: Collect unique non-NULL salaries. # distinct_salaries: set of unique ints, e.g. {95000, 105000, 120000}. # Check 'is not None' (not truthiness) so a valid salary of 0 is kept. distinct_salaries: Set[int] = set() for salary in salaries: if salary is not None: distinct_salaries.add(salary) # Guard missing rank: fewer than n distinct salaries means no n-th highest exists. if n > len(distinct_salaries): return None # Phase 2: Sort unique salaries from highest to lowest; 1-based rank n sits at index n - 1. highest_first: List[int] = sorted(distinct_salaries, reverse=True) return highest_first[n - 1]- Guard
SQL solution for Nth Highest Salary
In SQL, the exact same "deduplicate, sort descending, skip
N - 1rows, take 1" idea translates cleanly usingDISTINCT,ORDER BY,LIMIT, andOFFSET(shown below forN = 2, soOFFSET 1):-- Outer SELECT wraps a scalar subquery (a subquery returning at most 1 row and 1 column) -- so that when fewer than 2 distinct salaries exist, SQL returns one NULL row instead of 0 rows. SELECT ( SELECT DISTINCT salary FROM employees -- Filter NULLs explicitly: PostgreSQL and Oracle sort NULL first on DESC by default. WHERE salary IS NOT NULL ORDER BY salary DESC LIMIT 1 OFFSET 1 ) AS nth_highest_salary;You can also solve this with
DENSE_RANK(), which assigns consecutive ranks (1, 2, 3, ...) with no gaps after ties. Wrapping the result inMAX(salary)guarantees a singleNULLrow when no row hassalary_rank = 2:SELECT MAX(salary) AS nth_highest_salary FROM ( SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS salary_rank FROM employees WHERE salary IS NOT NULL ) AS ranked_salaries WHERE salary_rank = 2;When writing a parameterized MySQL function
getNthHighestSalary(N INT), remember that MySQL'sOFFSETaccepts an integer constant or local variable rather than an arithmetic expression likeN - 1, so runSET N = N - 1;first and thenLIMIT 1 OFFSET N.SQL aggregations: COUNT, SUM, AVG, MIN, and MAX
Aggregate functions summarize multiple rows into one value per group. Their key subtlety is how they treat
NULL(missing) values. Suppose we add a fourth rowOwenwithsalary = NULL:+----+------+--------+ Aggregate result across all 4 rows: | id | name | salary | ----------------------------------- +----+------+--------+ COUNT(*) = 4 (counts every row, NULLs included) | 1 | Maya | 95000 | COUNT(salary) = 3 (counts non-NULL values only) | 2 | Liam | 120000 | SUM(salary) = 320000 (95000 + 120000 + 105000; skips NULL) | 3 | Nora | 105000 | AVG(salary) = 106666.67 (SUM / COUNT(salary) = 320000 / 3, NOT / 4!) | 4 | Owen | NULL | MIN(salary) = 95000 (smallest non-NULL; also works on dates/text) +----+------+--------+ MAX(salary) = 120000 (largest non-NULL; also works on dates/text)Also remember empty-input behavior: on zero matching rows,
COUNT(*)andCOUNT(salary)return0, whereasSUM,AVG,MIN, andMAXall returnNULL.SQL joins and UNION vs UNION ALL
Suppose we also have a contractor
Priyawhosedept_idisNULL, while department3 (Legal)currently has zero employees. Joiningemployees etodepartments d ON e.dept_id = d.idbehaves four ways:Join type Rows kept Typical business scenario ---------------- ------------------------------------------------ ------------------------------------------------ INNER JOIN Maya (Eng), Liam (Analytics), Nora (Eng) Reports needing only staff with assigned depts LEFT JOIN INNER rows + (Priya, NULL) Audit unassigned staff (WHERE d.id IS NULL) RIGHT JOIN INNER rows + (NULL, Legal) List every department, even with 0 headcount FULL OUTER JOIN INNER rows + (Priya, NULL) + (NULL, Legal) Reconcile records across two source systems(Note: MySQL lacks
FULL OUTER JOIN; emulate it withLEFT JOINcombined viaUNION ALLwith the unmatched right rowsFROM departments d LEFT JOIN employees e ON d.id = e.dept_id WHERE e.id IS NULL.)Whereas joins combine columns horizontally by matching keys,
UNIONandUNION ALLstack compatible result sets vertically: -UNION ALLappends all rows from query B beneath query A with no extra work. PreferUNION ALLwhenever inputs are disjoint (such as stacking Q1 and Q2 partition tables) or when duplicate rows carry real meaning. -UNIONappends the rows and then hashes or sorts the full output to eliminate duplicates. PreferUNIONonly when you need unique rows across overlapping sources (such as unique user IDs who either filed a claim or called support).Window functions vs GROUP BY, and views vs physical tables
A window function computes an aggregate or ranking across related rows defined by
OVER (PARTITION BY ... ORDER BY ...)without collapsing the individual rows. CompareGROUP BYagainst a window function onemployees:GROUP BY dept_id (collapses to 1 row/dept) AVG(salary) OVER (PARTITION BY dept_id) (keeps all rows) +---------+------------+ +------+---------+--------+----------+ | dept_id | avg_salary | | name | dept_id | salary | dept_avg | +---------+------------+ +------+---------+--------+----------+ | 1 | 100000 | | Maya | 1 | 95000 | 100000 | | 2 | 120000 | | Nora | 1 | 105000 | 100000 | +---------+------------+ | Liam | 2 | 120000 | 120000 | +------+---------+--------+----------+Comparing SQL views and physical tables: - A view is a saved
SELECTdefinition rather than stored rows on disk. Pros: always reflects current base-table data, uses virtually zero storage, encapsulates complex joins, and restricts column/row visibility for security. Cons: re-runs the underlying query on every read (costly for heavy aggregations) and multi-table views generally cannot take directINSERT/UPDATEwrites. - A physical table stores materialized rows on disk. Pros: fast reads, supports indexes, primary keys, and foreign-key constraints. Cons: consumes disk space and requires ETL jobs or triggers to keep derived tables fresh. (A materialized view caches a query's output on disk and refreshes on schedule.)Duplicates, SQL query tuning, and pandas combines
1. Suppress duplicates without deleting: Project
SELECT DISTINCT col1, col2 ...over business columns, or keep one full row per duplicate group usingROW_NUMBER()in a subquery (window functions cannot sit directly insideWHERE):SELECT id, name, salary, dept_id FROM ( SELECT id, name, salary, dept_id, ROW_NUMBER() OVER (PARTITION BY name, salary, dept_id ORDER BY id) AS copy_num FROM employees ) AS numbered WHERE copy_num = 1;2. Permanently delete duplicates: Retain the smallest primary-key
idper(name, salary, dept_id)group and delete all other copies (GROUP BYgroupsNULLvalues together, andidis a non-NULLprimary key soNOT INnever seesNULL), then enforce aUNIQUEconstraint:DELETE FROM employees WHERE id NOT IN ( SELECT keep_id FROM ( SELECT MIN(id) AS keep_id FROM employees GROUP BY name, salary, dept_id ) AS rows_to_keep );3. Practical SQL performance habits: - Read query plans with
EXPLAIN/EXPLAIN ANALYZEto locate full scans and heavy sorts. - Create indexes (sorted lookup structures that jump straight to matching keys instead of scanning every row) on columns referenced inWHERE,JOIN ON, andORDER BY. - Keep predicates index-friendly (sargable): writeWHERE hire_date >= '2025-01-01' AND hire_date < '2026-01-01'instead ofWHERE YEAR(hire_date) = 2025, because wrapping a column in a function prevents index range seeks. - Project only required columns rather thanSELECT *, filter rows before joining large tables, and chooseUNION ALLoverUNIONwhen deduplication is unnecessary.4. pandas
mergevsjoinvsconcat:Operation How it aligns data When to choose it -------------------------- ------------------------------------------- --------------------------------------------- pd.merge(df1, df2, ...) Arbitrary key columns/indexes (how="inner") SQL-style relational joins (employees + depts) df1.join(df2, ...) Right DataFrame index (default how="left") Convenient lookups keyed on DataFrame indexes pd.concat([df1, df2], ...) Stacks rows (axis=0) or columns (axis=1) Appending batch files (like SQL UNION ALL)Complete solution
Here is the complete Python implementation verified by the judge:
from typing import Any, Dict, List, Optional, Set, Tuple def nth_highest_salary(salaries: List[int], n: int) -> Optional[int]: # Guard invalid ranks: ranks are 1-based, and n <= 0 would make (n - 1) negative, # causing Python list indexing to wrap around to the tail of the sorted list. if n < 1: return None # Phase 1: Collect unique non-NULL salaries. # distinct_salaries: set of unique ints, e.g. {95000, 105000, 120000}. # Check 'is not None' (not truthiness) so a valid salary of 0 is kept. distinct_salaries: Set[int] = set() for salary in salaries: if salary is not None: distinct_salaries.add(salary) # Guard missing rank: fewer than n distinct salaries means no n-th highest exists. if n > len(distinct_salaries): return None # Phase 2: Sort unique salaries from highest to lowest; 1-based rank n sits at index n - 1. highest_first: List[int] = sorted(distinct_salaries, reverse=True) return highest_first[n - 1]✅ Submit now — all tests should pass.
Intuition & how it works
Imagine awarding medals on a competition leaderboard where tied competitors stand together on the same step of the podium. Asking for the n-th highest distinct salary is asking for the score written on step n of that podium: first ignore anyone without a recorded score (None / SQL NULL), collapse everyone who tied onto a single step, order the occupied steps from highest to lowest, and read off step n (or return None / NULL if fewer than n steps are occupied).
Two obvious approaches fail here. If you simply sort all raw salaries in descending order and pick index n - 1, ties at the top shift everything right — on [500, 800, 800, 650] with n = 2, sorting gives [800, 800, 650, 500] and index 1 returns 800 again instead of 650. Conversely, if you check every employee one by one by scanning the entire list to count how many unique salaries exceed theirs, you perform O(m^2) comparisons for m employees, which crawls on large tables.
Walk through salaries = [500, 800, None, 800, 650] with n = 2:
1. n = 2 is at least 1, so the requested rank is valid.
2. Scanning the list skips None and inserts numbers into a hash set (a collection that stores each unique item once with O(1) average lookup/insert), yielding distinct_salaries = {500, 650, 800}.
3. There are 3 distinct salaries and n = 2 <= 3, so a 2nd highest salary exists.
4. Sorting descending gives highest_first = [800, 650, 500], and reading index n - 1 = 1 returns 650.
Complexity
Let m be the total number of input rows (len(salaries)) and d be the number of distinct non-NULL salaries (d <= m).
- Time:
O(m + d log d)(O(m log m)in the worst case) — We scan allmentries once and perform anO(1)average hash-set insertion for each non-Nonesalary (O(m)total), then sort only thedunique values inO(d log d)time and readhighest_first[n - 1]inO(1)time. In SQL,SELECT DISTINCT salary ... ORDER BY salary DESC LIMIT 1 OFFSET N-1similarly hashes/sorts inO(m log m)time, or reads the topNdistinct entries directly inO(N)distinct-key hops when backed by a B-tree index onemployees(salary). - Space:
O(d)— Bothdistinct_salariesandhighest_firststore at mostdunique integers (O(m)in the worst case when every employee has a different salary).
Edge cases
- Ties at or above rank
n:[500, 800, 800, 650]withn = 2returns650because both800s collapse into rank1. - Fewer than
ndistinct salaries (or empty input[]):[60000, 85000]withn = 3has only2distinct salaries, returningNonein Python and a single row containingNULLin SQL. - Non-positive rank (
n <= 0): Guardingif n < 1: return Nonepreventshighest_first[n - 1]from evaluatinghighest_first[-1]whenn = 0and falsely returning the minimum salary. None/NULLsalaries: Ignored completely during ranking. In SQL engines such as PostgreSQL and Oracle whereORDER BY salary DESCplacesNULLs first by default,WHERE salary IS NOT NULLpreventsNULLfrom stealing rank1.- Zero salary (
0):0is a valid numeric salary, so checkingif salary is not None:(rather thanif salary:) preserves it, and callers must checkresult is None. nequal to total distinct count: Cleanly returns the minimum non-Nonesalary athighest_first[-1].
Common mistakes
- Forgetting
DISTINCTbeforeORDER BY/OFFSET:SELECT salary FROM employees ORDER BY salary DESC LIMIT 1 OFFSET 1fails whenever multiple employees share the top salary. - Confusing
ROW_NUMBER(),RANK(), andDENSE_RANK(): On[800, 800, 650],ROW_NUMBER()assigns1, 2, 3(returning800for rank2), andRANK()assigns1, 1, 3(leaving rank2completely empty and returningNULL!). OnlyDENSE_RANK()assigns1, 1, 2. - Returning zero rows instead of one
NULLrow in SQL: A bareSELECT DISTINCT salary ... LIMIT 1 OFFSET 1returns an empty result set when fewer than2distinct salaries exist; wrap it in an outerSELECT (...) AS nth_highest_salaryor aggregateMAX(salary)so oneNULLrow is always emitted. - Misunderstanding
AVG(col)vsCOUNT(*)withNULLs:AVG(salary)dividesSUM(salary)byCOUNT(salary)(non-NULLrows), not byCOUNT(*)(all rows). - Using
NOT INwith a nullable column when deleting duplicates: In SQL,x NOT IN (1, 2, NULL)evaluates toUNKNOWNfor everyxand deletes nothing; always filter or target a non-NULLprimary keyid.
Follow-up questions
-
How would you return the 2nd highest distinct salary inside every department alongside the department name? Partition
DENSE_RANK()bydept_id(DENSE_RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS salary_rankover non-NULLsalaries) so each department gets its own gap-free podium1, 2, 3, .... If every department must appear even when it has fewer than two distinct salaries, start fromdepartments dandLEFT JOINthat ranked subqueryrond.id = r.dept_id AND r.salary_rank = 2, selectingd.id, d.dept_name, MAX(r.salary) AS second_highest_salarygrouped byd.id, d.dept_name. -
How do ROW_NUMBER(), RANK(), and DENSE_RANK() differ when multiple rows share the same salary? All three are window functions (functions that compute a per-row rank over an ordered partition without collapsing rows), differing only on ties: on
[800, 800, 650],ROW_NUMBER()gives unique sequential numbers1, 2, 3(breaking ties arbitrarily unless a tie-breaker column is inORDER BY),RANK()gives1, 1, 3(skipping rank2because two rows tied ahead), andDENSE_RANK()gives1, 1, 2(never skipping numbers). UseROW_NUMBER()for deduplicating copies,RANK()for competition standings with gaps, andDENSE_RANK()for the N-th highest distinct value. -
How would you find the n-th highest distinct salary over 100 million streamed records when n is small? Sorting all distinct values uses
O(d)memory, which may not fit in RAM. Instead, maintain a min-heap (a binary tree structure that keeps its smallest element at the root and supports insert/pop inO(log n)time) holding at most thenlargest distinct salaries seen so far, paired with asetof thosenheap elements to ignore duplicates inO(1)time. Each streamed salary takesO(1)if ignored orO(log n)if inserted, givingO(m log n)total time and justO(n)memory, with the root of the size-nmin-heap holding the exactn-th highest salary at the end.
Follow-up questions
- How would you return the 2nd highest distinct salary inside every department alongside the department name?
- How do ROW_NUMBER(), RANK(), and DENSE_RANK() differ when multiple rows share the same salary?
- How would you find the n-th highest distinct salary over 100 million streamed records when n is small?
Similar questions
- Per-Customer Order Aggregates with Null Amounts
- Fannie Mae Mission, Testing Layers, and Validating UI Updates
- Job Posting Engagement Metrics Excluding Non-Viewing Applicants
- Compute 7-Day DAU, D1 Retention, and Revenue Cohorts
- Class-Level 2024 Exam Summary with Zero-Filled Averages
- Summarizing Imaging Claims Spend and Fiscal Months