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 = 1 is the maximum, n = 2 is the second largest unique value, and so on).
  • Ignore None (NULL in SQL) entries, while treating 0 as a valid numeric salary.
  • Return None (or a single NULL row in SQL) whenever n < 1 or fewer than n distinct non-null salaries exist.

Conceptual & Practical Discussion Topics

In an interview walkthrough, also be prepared to cover:

  1. Aggregate functions: How COUNT, SUM, AVG, MIN, and MAX behave—especially around NULL entries and empty groups.
  2. Relational joins: How INNER, LEFT, RIGHT, and FULL OUTER joins match rows, with one realistic business scenario per join type.
  3. Set stacking: How UNION and UNION ALL differ in duplicate handling and runtime cost, and when each is appropriate.
  4. Windowed calculations: What OVER (...) window functions compute and how they differ from GROUP BY aggregations.
  5. Views vs. base tables: Storage, freshness, security, and performance trade-offs between virtual views and physical tables.
  6. Duplicate handling: How to suppress duplicate records in a SELECT output without altering stored data, versus how to delete duplicate rows permanently from a table.
  7. SQL performance tuning: Concrete indexing and query-writing habits that eliminate unnecessary table scans and sorts.
  8. DataFrame combining in pandas: How pd.merge, DataFrame.join, and pd.concat align 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 salaries are non-negative integers (0 is valid) or None (NULL).
  • -10^5 <= n <= 10^5; any n < 1 or n exceeding the count of distinct non-null salaries returns None.

Step-by-step walkthrough

  1. 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 the employees table for N = 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: - salaries is a list of compensation figures (where None represents a SQL NULL). - n is a 1-based rank (n = 1 asks for the top salary, n = 2 for the 2nd highest, and so on). - We must return the n-th highest distinct non-NULL salary, or None (NULL in SQL) if n < 1 or fewer than n distinct salaries exist.

    Why does distinct matter? Look at Example 4 ([500, 800, 800, 650] with n = 2): - Rank 1 (highest): 800 (shared by two employees) - Rank 2 (2nd highest): 650

    So the 2nd highest distinct salary is 650, not the second copy of 800.

  2. Why naive sorting or pairwise counting falls short

    Two first-instinct approaches run into trouble:

    1. Sorting the raw list without deduplicating: If we sort [500, 800, 800, 650] in descending order ([800, 800, 650, 500]) and read index n - 1 = 1, we get 800 instead of 650 because duplicate values push lower ranks further right.
    2. 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 - 1 distinct 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 of m employees takes O(m^2) work (10^10 comparisons for 100,000 rows).
  3. Python solution: deduplicate, guard bounds, and sort

    Once we collapse duplicate salaries first, the problem shrinks to sorting unique numbers:

    1. Guard n < 1: there is no 0th or negative rank. Without this check, n = 0 would compute highest_first[0 - 1] = highest_first[-1], which in Python silently wraps around to the lowest salary instead of returning None!
    2. Insert every non-None salary into a hash set distinct_salaries. Use salary is not None rather than if salary: so a legitimate salary of 0 is not discarded.
    3. Guard n > len(distinct_salaries): if fewer than n unique salaries exist, return None before indexing.
    4. Sort distinct_salaries in descending order (reverse=True) and return highest_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 650
    
    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]
    
  4. SQL solution for Nth Highest Salary

    In SQL, the exact same "deduplicate, sort descending, skip N - 1 rows, take 1" idea translates cleanly using DISTINCT, ORDER BY, LIMIT, and OFFSET (shown below for N = 2, so OFFSET 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 in MAX(salary) guarantees a single NULL row when no row has salary_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's OFFSET accepts an integer constant or local variable rather than an arithmetic expression like N - 1, so run SET N = N - 1; first and then LIMIT 1 OFFSET N.

  5. 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 row Owen with salary = 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(*) and COUNT(salary) return 0, whereas SUM, AVG, MIN, and MAX all return NULL.

  6. SQL joins and UNION vs UNION ALL

    Suppose we also have a contractor Priya whose dept_id is NULL, while department 3 (Legal) currently has zero employees. Joining employees e to departments d ON e.dept_id = d.id behaves 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 with LEFT JOIN combined via UNION ALL with the unmatched right rows FROM 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, UNION and UNION ALL stack compatible result sets vertically: - UNION ALL appends all rows from query B beneath query A with no extra work. Prefer UNION ALL whenever inputs are disjoint (such as stacking Q1 and Q2 partition tables) or when duplicate rows carry real meaning. - UNION appends the rows and then hashes or sorts the full output to eliminate duplicates. Prefer UNION only when you need unique rows across overlapping sources (such as unique user IDs who either filed a claim or called support).

  7. 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. Compare GROUP BY against a window function on employees:

    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 SELECT definition 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 direct INSERT/UPDATE writes. - 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.)

  8. 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 using ROW_NUMBER() in a subquery (window functions cannot sit directly inside WHERE):

    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 id per (name, salary, dept_id) group and delete all other copies (GROUP BY groups NULL values together, and id is a non-NULL primary key so NOT IN never sees NULL), then enforce a UNIQUE constraint:

    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 ANALYZE to 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 in WHERE, JOIN ON, and ORDER BY. - Keep predicates index-friendly (sargable): write WHERE hire_date >= '2025-01-01' AND hire_date < '2026-01-01' instead of WHERE YEAR(hire_date) = 2025, because wrapping a column in a function prevents index range seeks. - Project only required columns rather than SELECT *, filter rows before joining large tables, and choose UNION ALL over UNION when deduplication is unnecessary.

    4. pandas merge vs join vs concat:

    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)
    
  9. 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 all m entries once and perform an O(1) average hash-set insertion for each non-None salary (O(m) total), then sort only the d unique values in O(d log d) time and read highest_first[n - 1] in O(1) time. In SQL, SELECT DISTINCT salary ... ORDER BY salary DESC LIMIT 1 OFFSET N-1 similarly hashes/sorts in O(m log m) time, or reads the top N distinct entries directly in O(N) distinct-key hops when backed by a B-tree index on employees(salary).
  • Space: O(d) — Both distinct_salaries and highest_first store at most d unique 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] with n = 2 returns 650 because both 800s collapse into rank 1.
  • Fewer than n distinct salaries (or empty input []): [60000, 85000] with n = 3 has only 2 distinct salaries, returning None in Python and a single row containing NULL in SQL.
  • Non-positive rank (n <= 0): Guarding if n < 1: return None prevents highest_first[n - 1] from evaluating highest_first[-1] when n = 0 and falsely returning the minimum salary.
  • None / NULL salaries: Ignored completely during ranking. In SQL engines such as PostgreSQL and Oracle where ORDER BY salary DESC places NULLs first by default, WHERE salary IS NOT NULL prevents NULL from stealing rank 1.
  • Zero salary (0): 0 is a valid numeric salary, so checking if salary is not None: (rather than if salary:) preserves it, and callers must check result is None.
  • n equal to total distinct count: Cleanly returns the minimum non-None salary at highest_first[-1].

Common mistakes

  • Forgetting DISTINCT before ORDER BY / OFFSET: SELECT salary FROM employees ORDER BY salary DESC LIMIT 1 OFFSET 1 fails whenever multiple employees share the top salary.
  • Confusing ROW_NUMBER(), RANK(), and DENSE_RANK(): On [800, 800, 650], ROW_NUMBER() assigns 1, 2, 3 (returning 800 for rank 2), and RANK() assigns 1, 1, 3 (leaving rank 2 completely empty and returning NULL!). Only DENSE_RANK() assigns 1, 1, 2.
  • Returning zero rows instead of one NULL row in SQL: A bare SELECT DISTINCT salary ... LIMIT 1 OFFSET 1 returns an empty result set when fewer than 2 distinct salaries exist; wrap it in an outer SELECT (...) AS nth_highest_salary or aggregate MAX(salary) so one NULL row is always emitted.
  • Misunderstanding AVG(col) vs COUNT(*) with NULLs: AVG(salary) divides SUM(salary) by COUNT(salary) (non-NULL rows), not by COUNT(*) (all rows).
  • Using NOT IN with a nullable column when deleting duplicates: In SQL, x NOT IN (1, 2, NULL) evaluates to UNKNOWN for every x and deletes nothing; always filter or target a non-NULL primary key id.

Follow-up questions

  • How would you return the 2nd highest distinct salary inside every department alongside the department name? Partition DENSE_RANK() by dept_id (DENSE_RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS salary_rank over non-NULL salaries) so each department gets its own gap-free podium 1, 2, 3, .... If every department must appear even when it has fewer than two distinct salaries, start from departments d and LEFT JOIN that ranked subquery r on d.id = r.dept_id AND r.salary_rank = 2, selecting d.id, d.dept_name, MAX(r.salary) AS second_highest_salary grouped by d.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 numbers 1, 2, 3 (breaking ties arbitrarily unless a tie-breaker column is in ORDER BY), RANK() gives 1, 1, 3 (skipping rank 2 because two rows tied ahead), and DENSE_RANK() gives 1, 1, 2 (never skipping numbers). Use ROW_NUMBER() for deduplicating copies, RANK() for competition standings with gaps, and DENSE_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 in O(log n) time) holding at most the n largest distinct salaries seen so far, paired with a set of those n heap elements to ignore duplicates in O(1) time. Each streamed salary takes O(1) if ignored or O(log n) if inserted, giving O(m log n) total time and just O(n) memory, with the root of the size-n min-heap holding the exact n-th highest salary at the end.

Follow-up questions

Similar questions

More Fannie Mae interview questions

All 3 Fannie Mae questions →