Interview Problems: Easy

The easy SQL problems that open most interviews: second-highest value, duplicates, rows with no match, day-over-day change, self-joins and top-by-count, each with a runnable answer.

Overview

Easy SQL problems are the warm-up in phone screens and the first minutes of a data or backend interview. The logic is short. What the interviewer watches is whether you pick the right pattern at once, write clean SQL without trial and error, and think about the edge cases on your own: NULLs, ties, gaps and empty results.

Almost every easy problem is one of a handful of patterns, and the wording of the question tells you which one.

  • The Nth highest value: MAX below the max, OFFSET, or DENSE_RANK.
  • Values that repeat: GROUP BY ... HAVING COUNT(*) > 1.
  • Rows with no match in another table: NOT EXISTS, or LEFT JOIN ... IS NULL.
  • Comparing a row with the previous day or row: a self-join on the date, or LAG.
  • Comparing a row with a related row in the same table: a self-join.
  • The entity with the most of something: GROUP BY, then ORDER BY COUNT(*) DESC.
  • A rate or share: AVG(CASE WHEN ... THEN 1 ELSE 0 END).

Once you know the pattern, work every problem the same way.

  • Read the problem and the tables.
  • Name the pattern.
  • Write the simplest query that follows it.
  • Check NULLs, ties, gaps and empty input.
  • Say the answer and its cost.

Step 4 is the one candidates skip. The edge-case check is what turns a query that looks right into one that is right.

The problems below are written in our own words. Each one creates its own tiny tables, so you can run every block in order in PostgreSQL.

Second-highest distinct salary

Given a table of staff with salaries, return the second-highest distinct salary. If there is no such salary, return a single row holding NULL.

It returns 9000. The highest salary is Lena's 9500, and the largest salary below it is Ava's 9000.

An aggregate with no input rows returns NULL, so this answer already handles a table with one salary. For the Nth highest, use DISTINCT with OFFSET, and wrap it in a scalar subquery: a query that finds nothing returns zero rows, but a scalar subquery that finds nothing returns NULL.

It also returns 9000. Two edge cases decide whether a version like this is right.

  • Two people share the top salary: OFFSET 1 without DISTINCT returns the top salary again. Use DISTINCT or DENSE_RANK so equal salaries count once.
  • Only one distinct salary: a plain query returns no row. MAX or a scalar subquery returns NULL instead, which is what the problem asks for.

Sign up free to read the full topic

More Databases & SQL topics

Start free on Cariara · Coding problems · System design studio