← 30 Days of SQL
Day 26 / 30Patterns

Interview Question Patterns — Find Duplicates, Gaps, Islands

Classic SQL puzzle patterns that interviewers love. These test logical thinking beyond basic syntax.

1
Medium

Find employees with the same salary (all of them).

SQL Answer
SELECT e.*
FROM employees e
WHERE salary IN (
  SELECT salary
  FROM employees
  GROUP BY salary
  HAVING COUNT(*) > 1
)
ORDER BY salary;
💡

Find salaries that appear more than once, then return all employees with those salaries. Different from finding duplicates by ID — here duplicates are by value.

2
Hard

Find gaps in a sequence of order IDs (missing numbers).

SQL Answer
SELECT o1.order_id + 1 AS gap_start
FROM orders o1
WHERE NOT EXISTS (
  SELECT 1 FROM orders o2
  WHERE o2.order_id = o1.order_id + 1
)
AND o1.order_id < (SELECT MAX(order_id) FROM orders);
💡

Find numbers where the next number doesn't exist. Useful for detecting missing invoices, skipped IDs, or gaps in sequences. A classic logic puzzle.

3
Medium

Write a query to swap values in a column (0 → 1 and 1 → 0).

SQL Answer
UPDATE employees
SET is_active = CASE is_active
  WHEN 1 THEN 0
  WHEN 0 THEN 1
END;
💡

Toggle a boolean column. CASE WHEN in UPDATE statements works exactly like in SELECT. This is a classic one-liner interview question.

4
Hard

Find the employee who was hired immediately before and after a specific employee.

SQL Answer
WITH ordered AS (
  SELECT name, hire_date,
         LAG(name)  OVER (ORDER BY hire_date) AS prev_hire,
         LEAD(name) OVER (ORDER BY hire_date) AS next_hire
  FROM employees
)
SELECT prev_hire, name, next_hire
FROM ordered
WHERE name = 'Rahul Sharma';
💡

LAG and LEAD solve "previous/next in sequence" problems elegantly. Without window functions this would require a complex self-join.

5
Medium

Write a query that returns rows as a comma-separated list (GROUP_CONCAT).

SQL Answer
-- MySQL:
SELECT department,
       GROUP_CONCAT(name ORDER BY name SEPARATOR ', ') AS employees
FROM employees
GROUP BY department;

-- PostgreSQL:
SELECT department,
       STRING_AGG(name, ', ' ORDER BY name) AS employees
FROM employees
GROUP BY department;
💡

GROUP_CONCAT / STRING_AGG aggregates strings. Useful for building comma-separated lists in reports. The ORDER BY inside keeps the list sorted.

EVIKA ACADEMY · SQL FOR DATA ANALYTICS

Want to master SQL with live practice?

Join our SQL for Data Analytics course — live classes in Noida and online across India.

Book Free Demo Class →
← PREVIOUSDay 25: Stored Procedures and ViewsNEXT →Day 27: SQL for Data Analyst Interviews — Frequently Asked Questions
Best Data Analytics Course in Noida Delhi NCR | EVIKA ACADEMY