Wooden card catalog drawers representing database indexes and SQL tables
Photo via Unsplash

SQL Interview Questions for Engineers: 2026 Guide

SQL is the interview topic that candidates underestimate most. Backend, full-stack, data, and even many frontend loops in 2026 include at least one SQL round, either as a live query on a shared editor or as a database design discussion folded into a system design interview. The good news: SQL interview questions repeat a small set of patterns. Learn those patterns and the round becomes one of the most predictable parts of your loop.

This guide covers the SQL concepts interviewers actually test, the six query patterns that show up again and again, the performance questions that separate senior candidates, and a two-week plan to get interview-ready.

Why SQL Interview Questions Still Matter in 2026

ORMs like Hibernate, JPA, and Prisma hide SQL in day-to-day work, which is exactly why interviewers probe it. A candidate who can only express data access through an ORM tends to ship N+1 queries, missing indexes, and accidental full-table scans. Hiring teams use SQL rounds to check three things:

  • Set-based thinking – can you solve a problem with one declarative query instead of a loop in application code?
  • Correctness under edge cases – NULLs, ties, duplicates, and empty groups.
  • Production awareness – indexes, execution plans, transactions, and isolation levels.

Core Concepts Interviewers Expect You to Know Cold

Logical Order of Execution

Most SQL bugs in interviews come from forgetting that a query is not evaluated in the order it is written. The logical order is: FROM → JOIN → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY → LIMIT. That is why you cannot filter on a window function or a SELECT alias inside WHERE, and why aggregate filters belong in HAVING.

JOIN Semantics

Be ready to explain INNER, LEFT, RIGHT, FULL OUTER, CROSS, and self joins, and to predict row counts. A classic trap: putting a filter on the right table of a LEFT JOIN in the WHERE clause silently turns it into an inner join. Move that condition into the ON clause to keep unmatched rows.

NULL Handling

NULL = NULL is not true, COUNT(column) skips NULLs while COUNT(*) does not, and NOT IN returns nothing if the subquery contains a single NULL. Interviewers love these because they expose shallow understanding fast.

Server racks running relational databases queried with SQL
Photo via Unsplash

The 6 SQL Query Patterns That Cover Most Interviews

1. Nth Highest Value

“Find the second highest salary” is the most famous SQL interview question. Use DENSE_RANK so ties are handled correctly and the query generalizes to any N:

SELECT DISTINCT salary
FROM (
  SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
  FROM employees
) t
WHERE rnk = 2;

Mention the follow-up yourself: if no second salary exists, wrap it in a scalar subquery so the result is NULL rather than an empty set.

2. Top N Per Group

“Top three earners in each department” tests window functions with PARTITION BY. Know the difference between ROW_NUMBER (unique ranks, arbitrary tie-break), RANK (gaps after ties), and DENSE_RANK (no gaps), and ask which one the interviewer wants.

SELECT department_id, name, salary
FROM (
  SELECT e.*, DENSE_RANK() OVER (
    PARTITION BY department_id ORDER BY salary DESC) AS rnk
  FROM employees e
) t
WHERE rnk <= 3;

3. Anti-Joins: Rows With No Match

“Customers who never placed an order” can be solved three ways. Prefer NOT EXISTS or a LEFT JOIN ... IS NULL, and explain why NOT IN is dangerous when the subquery column is nullable.

SELECT c.id, c.name
FROM customers c
WHERE NOT EXISTS (
  SELECT 1 FROM orders o WHERE o.customer_id = c.id
);

4. Finding and Removing Duplicates

Detect duplicates with GROUP BY ... HAVING COUNT(*) > 1. To delete all but one copy, number the rows inside each duplicate group and remove everything with a row number above one. This pattern also shows you understand CTEs.

WITH ranked AS (
  SELECT id, ROW_NUMBER() OVER (
    PARTITION BY email ORDER BY created_at) AS rn
  FROM users
)
DELETE FROM users
WHERE id IN (SELECT id FROM ranked WHERE rn > 1);

5. Running Totals and Moving Averages

Product and fintech companies ask for cumulative revenue or seven-day moving averages. Use window frames explicitly so the interviewer sees you know the default frame behavior:

SELECT order_date,
       SUM(amount) OVER (ORDER BY order_date
         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total,
       AVG(amount) OVER (ORDER BY order_date
         ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS moving_avg_7d
FROM daily_revenue;

6. Gaps and Islands (Consecutive Streaks)

“Find users who logged in on three or more consecutive days” is the hardest common pattern. The trick: subtract a row number from the date. Consecutive dates produce the same difference, which becomes a group key.

WITH d AS (
  SELECT user_id, login_date,
         login_date - ROW_NUMBER() OVER (
           PARTITION BY user_id ORDER BY login_date) * INTERVAL '1 day' AS grp
  FROM (SELECT DISTINCT user_id, login_date FROM logins) x
)
SELECT user_id, MIN(login_date) AS streak_start, COUNT(*) AS days
FROM d
GROUP BY user_id, grp
HAVING COUNT(*) >= 3;

Date arithmetic syntax varies between PostgreSQL, MySQL, and SQL Server, so state which dialect you are writing and adapt if asked.

Analytics dashboard built from SQL window function queries
Photo via Unsplash

Performance and Indexing Questions for Senior Roles

Once you clear the query round, senior and tech lead interviews shift toward how queries behave in production. Prepare crisp answers for these:

  • How does a B-tree index work, and when is it not used? Cover functions on indexed columns, leading wildcards in LIKE '%term', implicit type casts, and low-selectivity columns.
  • Composite index column order. Explain the leftmost-prefix rule: an index on (customer_id, created_at) helps queries filtering by customer_id alone, but not by created_at alone.
  • Covering indexes. When every selected column lives in the index, the database can skip the table lookup entirely.
  • Reading an execution plan. Know how to spot a sequential scan, a nested loop over a large table, or a sort spilling to disk using EXPLAIN or EXPLAIN ANALYZE.
  • The N+1 problem. Describe how an ORM triggers one query per parent row and how fetch joins, batch fetching, or a single aggregated query fix it.
  • Pagination at scale. Explain why large OFFSET values get slow and how keyset (seek) pagination using WHERE id > :last_id keeps latency flat.

Transactions and Isolation Levels

Expect at least one question on ACID and concurrency. Be able to define dirty reads, non-repeatable reads, and phantom reads, map them to Read Uncommitted, Read Committed, Repeatable Read, and Serializable, and give a real example such as two requests decrementing the same inventory row. Strong answers compare pessimistic locking (SELECT ... FOR UPDATE) with optimistic locking using a version column, and explain when each fits.

A Two-Week SQL Interview Prep Plan

Days 1–3: Fundamentals. Rewrite each JOIN type by hand, practice GROUP BY with HAVING, and drill NULL behavior until it is automatic.

Days 4–7: Window functions. Solve five problems each for ranking, top-N per group, running totals, and LAG/LEAD comparisons such as month-over-month growth.

Days 8–10: Hard patterns. Work through gaps and islands, recursive CTEs for hierarchies like org charts, and pivoting rows into columns with conditional aggregation.

Days 11–12: Performance. Load a sample dataset into PostgreSQL or MySQL, add and remove indexes, and compare execution plans before and after.

Days 13–14: Mock interviews. Solve timed problems out loud. Interviewers grade your reasoning, not just the final query.

Developer laptop used for SQL interview practice
Photo via Unsplash

Common Mistakes That Cost Candidates the Offer

  • Writing before clarifying. Ask about ties, NULLs, duplicates, and expected output format first.
  • Selecting non-aggregated columns that are not in the GROUP BY. MySQL may allow it in some modes, but most interviewers treat it as a bug.
  • Skipping verification. Walk through your query with a tiny sample table of three or four rows before saying you are done.
  • Ignoring readability. Use CTEs with meaningful names instead of nesting four subqueries deep.
  • Never mentioning scale. A one-line note about which index would support your query signals production experience.

Start Practicing Today

SQL interview questions reward deliberate practice more than almost any other round. The patterns are finite, the edge cases are well known, and every hour you invest shows up directly in your performance. Pick one pattern from this guide today, solve three problems with it, and explain each solution out loud as if an interviewer were listening. Do that every day for two weeks and you will walk into your next SQL round with confidence.

Want structured, realistic interview practice alongside your SQL prep? Explore Niraswa AI and start preparing for your next interview today.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *