Scrivio Interview library

SQL interview problems

33 questions in 11 subtopics.

Nth highest salary

CodingFoundations7 min read
Table employee(id int primary key, name text, dept_id int, salary numeric). Write a query that returns the third highest distinct salary, and returns NULL (one row) when there are fewer than three distinct salaries. Show two different approaches.
DebuggingIntermediate7 min read
A report should show the second highest salary. The query is:
SELECT salary
FROM (SELECT salary, ROW_NUMBER() OVER (ORDER BY salary DESC) rn
FROM employee) t
WHERE rn = 2;
With salaries 100, 100, 90 it returns 100. Explain the bug, fix it, and say how the fixed query behaves on a 50 million row table with an index on salary.
ScenarioAdvanced7 min read
An internal HR analytics API exposes an endpoint that returns the Nth highest salary for any department and N, running the query live on the primary OLTP database. Usage grew, the queries now cause CPU spikes during payroll runs, and security asks who can see salary data. How do you redesign it?
LeadershipPrincipal7 min read
"Find the Nth highest salary" has been a standard SQL interview question for decades. As the leader who owns the engineering interview process for several hundred hires a year, would you keep it? What would you replace it with, and how do you check that SQL rounds actually predict job performance?

Finding and removing duplicates

CodingFoundations7 min read
Table customer(id bigserial primary key, email text, created_at timestamptz). Some customers signed up twice with the same email, sometimes with different letter case. Write SQL to (a) list duplicated emails with their counts and (b) delete the duplicates, keeping the row with the lowest id. Then prevent new duplicates.
ScenarioIntermediate8 min read
A 300 million row events table in PostgreSQL has about 2 percent duplicate rows caused by a producer retry bug. The table takes 4,000 inserts per second around the clock. How do you remove the duplicates and add a unique constraint without an outage?
LeadershipPrincipal7 min read
Your company has duplicate customer records spread across CRM, billing, support and marketing systems. Finance estimates the cost in wrong invoices and double mailings at several million a year, and each team runs its own dedupe scripts. What long-term approach do you set?

Top N per group

CodingFoundations7 min read
Using employee(id, name, dept_id, salary), return the top 3 earners in each department. Explain what your query returns when two people tie for third place, and give a variant for exactly one top earner per department in PostgreSQL.
InternalsIntermediate8 min read
orders(id, customer_id, created_at, total) has 500 million rows and an index on (customer_id, created_at DESC). An API needs the 5 latest orders for each of 10,000 given customers. The ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_at DESC) version takes minutes. Write a faster query and explain why it is faster.
DesignAdvanced7 min read
A product team wants a "top 10 sellers per city" widget on the home page, updated within a minute, for 3,000 cities, reading from an orders table that takes 2,000 writes per second. They plan to run the top N per group query on every page view. What architecture do you propose?

Running totals

CodingFoundations7 min read
Table txn(id bigint, account_id int, tx_time timestamptz, amount numeric). Write a query that shows each transaction with the running balance of its account, and a second column with the sum of the last 7 days of amounts up to that row.
DebuggingIntermediate7 min read
A running total report uses SUM(amount) OVER (PARTITION BY account_id ORDER BY tx_date). On some days the running total jumps by several transactions at once and two rows show the same balance, though the final balance is correct. Explain, fix, and say whether balances should be computed this way at read time for a ledger with 2 billion rows.
DesignAdvanced8 min read
You are designing balance handling for a payments platform. One proposal stores only immutable ledger entries and derives balances with running totals; another keeps a mutable balance column updated in the same transaction. What do you choose for correctness, concurrency and audit, and how do the SQL queries change?

Gaps and islands

CodingFoundations7 min read
Table ticket(id int primary key) should have ids 1 to N with no gaps, but some are missing. Write a query that returns each gap as (gap_start, gap_end), for example (4, 6) when 4, 5 and 6 are missing.
CodingIntermediate7 min read
Table booking(room_id int, start_ts timestamptz, end_ts timestamptz) has overlapping bookings. Write a query that merges overlapping or touching bookings per room into continuous busy intervals. Mention a PostgreSQL-specific alternative.
CodingIntermediate8 min read
Table user_login(user_id int, login_at timestamptz), many logins per day. Return for each user every streak of consecutive login days with start_date, end_date and length in days, and the longest streak per user. Work in UTC.

Consecutive events

CodingFoundations7 min read
Table reading(id int primary key, value int), where id gives the order of readings. Return every value that appears at least three times in a row. Then explain what breaks if ids are not contiguous.
CodingIntermediate6 min read
Table page_view(user_id int, viewed_at timestamptz). Split each user's views into sessions, where a gap of more than 30 minutes starts a new session, and return per session the user, start, end and number of views.
DesignPrincipal6 min read
Fraud and alerting rules in your company are written as SQL over event tables, for example "three failed payments in a row followed by a success from a new device". Some run as batch SQL every hour, some in stream processors, some in a vendor rules engine. How do you decide where such consecutive-event logic should live over the next five years?

Hierarchy and manager chains

CodingFoundations6 min read
Table employee(id int primary key, name text, manager_id int null). Write a query that returns everyone who reports directly or indirectly to employee 7, with their depth below 7 and the path of names from 7 to them.
DebuggingIntermediate7 min read
A recursive CTE that lists the management chain above an employee runs until PostgreSQL is cancelled by statement_timeout, and in MySQL it fails with "Recursive query aborted after 1001 iterations". The data came from an HR import. What is wrong, how do you make the query safe, and how do you prevent bad data?
DesignAdvanced7 min read
An HR platform stores 2 million employees and 50,000 org units. The most frequent queries are "all people under this org unit" and "is X in Y's chain" for authorization, and reorganizations move whole subtrees a few times a month. Compare adjacency list with recursive CTEs, materialized path, nested sets and closure tables, and pick one.
DesignPrincipal6 min read
Your company's ERP, HR and access-control systems each model the organization hierarchy differently, and vendors now pitch a graph database as the single answer. How do you decide whether to keep hierarchies in relational databases, adopt a graph database, or use a dedicated identity and directory service?

Date bucketing and reports

CodingFoundations7 min read
Table orders(id, created_at timestamptz, total numeric). Write a PostgreSQL query that returns revenue per day for the last 30 days in the Europe/Berlin time zone, including days with no orders as 0.
DebuggingIntermediate7 min read
Finance says October revenue in your dashboard is 1.8 percent lower than in their export. The dashboard query is:
SELECT SUM(total)
FROM orders
WHERE created_at BETWEEN '2026-10-01' AND '2026-10-31';
created_at is timestamptz, the business is in New York. Find all the reasons the numbers differ and fix the query.
ScenarioAdvanced7 min read
Teams run daily, weekly and monthly report queries with date bucketing directly against the production PostgreSQL database. The orders table has 1.2 billion rows, reports scan months of data, and p99 latency of the checkout API rises every morning when finance runs them. What do you change, in what order?

Employees earning more than their managers

CodingFoundations5 min read
Table employee(id int primary key, name text, salary numeric, manager_id int null references employee(id)). Return the names of employees who earn more than their direct manager, with both salaries. What happens to employees without a manager or with a NULL salary?
CodingIntermediate7 min read
Using employee(id, name, salary, manager_id), return employees who earn more than every manager above them in their chain, up to the top, not only their direct manager. Explain how your query avoids comparing against people outside the chain.

Second highest value per group

CodingFoundations5 min read
Using employee(id, name, dept_id, salary) and department(id, name), return each department's name and its second highest distinct salary, and show NULL for departments that have fewer than two distinct salaries or no employees.
DebuggingIntermediate6 min read
A developer writes:
SELECT DISTINCT dept_id, NTH_VALUE(salary, 2) OVER (PARTITION BY dept_id
ORDER BY salary DESC) AS second
FROM employee;
It returns two rows for some departments, one with NULL. Explain why and fix it, and compare with a solution based on DENSE_RANK.

Pivot reports

CodingFoundations7 min read
Table sales(product text, sold_on date, amount numeric). Produce one row per product with columns jan, feb and mar holding 2026 sales totals, using portable SQL. Then show the PostgreSQL FILTER form and mention what PostgreSQL offers instead of a PIVOT keyword.
ScenarioIntermediate7 min read
Product managers want a pivot report where columns are product categories, but categories are added every week. A developer proposes building the SQL string dynamically from SELECT DISTINCT category in a Spring service. What are the risks, and what design would you recommend?
LeadershipPrincipal6 min read
Your organization has thousands of hand-written report and pivot queries spread across services, cron jobs and spreadsheets, and two reports rarely agree on the same number. How would you govern reporting SQL over the next few years: who writes it, where it runs and how numbers are defined?