SQL interview problems
33 questions in 11 subtopics.
Nth highest salary
Tableemployee(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.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;
Finding and removing duplicates
Tablecustomer(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.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?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
Usingemployee(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.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.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
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.A running total report usesSUM(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.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
Tableticket(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.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.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
Tablereading(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.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.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
Tableemployee(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.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?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.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
Tableorders(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.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';
Employees earning more than their managers
Table employee(id int primary key, name text, salary numeric, manager_id int null referencesemployee(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?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
Usingemployee(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.A developer writes:SELECT DISTINCT dept_id, NTH_VALUE(salary, 2) OVER (PARTITION BY dept_id
ORDER BY salary DESC) AS second
FROM employee;
DENSE_RANK.Pivot reports
Tablesales(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.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?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?No question matches these choices.