Home Interview SQL Optimization and Performance Interview: Advanced Guide
Advanced 3 min · July 13, 2026

SQL Optimization and Performance Interview: Advanced Guide

Master SQL optimization for interviews.

N
Naren Founder & Principal Engineer

20+ years shipping production code across the stack, with years spent interviewing engineers. Drawn from code that ran under real load.

Follow
Production
production tested
July 13, 2026
last updated
2,165
articles · all by Naren
Before you start⏱ 20-25 min read
  • Basic knowledge of SQL syntax (SELECT, JOIN, GROUP BY).
  • Understanding of database concepts like tables, indexes, and execution plans.
  • Familiarity with at least one relational database (PostgreSQL, MySQL, etc.).
 ● Production Incident 🔎 Debug Guide ⚙ Triage Commands
Quick Answer
  • Understand execution plans and use EXPLAIN ANALYZE.
  • Indexing strategies: B-tree, composite, covering indexes.
  • Avoid SELECT *, use EXISTS vs IN wisely.
  • Optimize JOINs: prefer INNER JOIN over subqueries.
  • Use LIMIT and pagination efficiently with keyset pagination.
✦ Definition~90s read
What is SQL Optimization and Performance Interview?

SQL optimization is the process of improving the performance of SQL queries by analyzing execution plans, indexing, and rewriting queries to reduce resource consumption and response time.

Think of SQL optimization like organizing a library.
Plain-English First

Think of SQL optimization like organizing a library. Without an index (card catalog), finding a book requires scanning every shelf (full table scan). With a good index, you go directly to the right section. Query tuning is like choosing the shortest path to find books: instead of checking every book (SELECT *), you only grab the ones you need (specific columns).

In the world of data-driven applications, SQL performance can make or break your system. A poorly written query can bring a production database to its knees, causing timeouts and frustrated users. That's why SQL optimization is a favorite topic in technical interviews, especially for backend and data engineering roles. Interviewers want to see not just that you can write SQL, but that you understand how databases execute queries and how to make them fast.

This guide covers the most common SQL optimization interview questions, from indexing strategies to query rewriting techniques. You'll learn how to read execution plans, avoid common pitfalls like N+1 queries and unnecessary full table scans, and apply best practices like covering indexes and keyset pagination. Each section includes a real interview question with a step-by-step solution, complexity analysis, and tips for explaining your reasoning during an interview.

Whether you're preparing for a FAANG interview or a senior developer role, mastering these concepts will set you apart. Let's dive into the advanced world of SQL performance.

Understanding Execution Plans

An execution plan shows how the database engine will execute your query. It's the first thing you should check when optimizing. Use EXPLAIN (or EXPLAIN ANALYZE in PostgreSQL) to see the plan. Look for sequential scans (Seq Scan) which indicate full table scans, and note the estimated rows vs actual rows. A large discrepancy suggests outdated statistics.

Example: For a query filtering on a non-indexed column, you'll see a Seq Scan. Adding an index changes it to an Index Scan. In an interview, explain that you always start with EXPLAIN to identify bottlenecks.

explain_example.sqlSQL
1
EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 123;
Output
Seq Scan on orders (cost=0.00..1000.00 rows=1 width=100) (actual time=0.5..500.0 rows=1 loops=1)
Filter: (customer_id = 123)
Rows Removed by Filter: 999999
Planning Time: 0.1 ms
Execution Time: 500.1 ms
💡Interview Tip
📊 Production Insight
In production, use auto_explain module in PostgreSQL to log slow queries with their plans automatically.
🎯 Key Takeaway
Execution plans reveal how the database processes your query; always analyze them before optimizing.

Indexing Strategies

Indexes are the most powerful tool for SQL performance. Understand different types: B-tree (default), Hash, GiST, GIN, and BRIN. For typical equality and range queries, B-tree is best. Composite indexes (multiple columns) are useful for queries filtering on multiple columns. The order of columns matters: put the most selective column first.

Covering indexes include all columns needed by a query, allowing index-only scans. Partial indexes (WHERE clause) are great for frequently filtered subsets. In an interview, be ready to design an index for a given query pattern.

Example: For a query like SELECT name, email FROM users WHERE status = 'active' ORDER BY created_at DESC, a composite index on (status, created_at) INCLUDING (name, email) would be ideal.

create_index.sqlSQL
1
CREATE INDEX idx_users_status_created ON users (status, created_at DESC) INCLUDE (name, email);
🔥Index Overhead
📊 Production Insight
Monitor unused indexes with pg_stat_user_indexes and remove them to reduce write overhead.
🎯 Key Takeaway
Choose index types and column order based on query patterns; covering indexes eliminate table lookups.

Query Rewriting Techniques

Sometimes rewriting a query yields dramatic improvements. Common techniques: - Replace subqueries with JOINs when possible (but not always). - Use EXISTS instead of IN for large subquery results. - Avoid SELECT *; specify only needed columns. - Use UNION ALL instead of UNION if duplicates are acceptable. - Use aggregate functions with GROUP BY instead of multiple subqueries.

Example: Instead of SELECT FROM orders WHERE customer_id IN (SELECT id FROM customers WHERE status = 'vip'), use a JOIN: SELECT o. FROM orders o JOIN customers c ON o.customer_id = c.id WHERE c.status = 'vip'. This allows the optimizer to use indexes more effectively.

rewrite.sqlSQL
1
2
3
4
5
-- Slow subquery
SELECT * FROM orders WHERE customer_id IN (SELECT id FROM customers WHERE status = 'vip');

-- Faster JOIN
SELECT o.* FROM orders o JOIN customers c ON o.customer_id = c.id WHERE c.status = 'vip';
⚠ Not Always Faster
📊 Production Insight
In production, use query rewriting as a last resort after indexing; it's easier to maintain.
🎯 Key Takeaway
Rewrite queries to leverage indexes and reduce data processed; always test with EXPLAIN.

Pagination Optimization

Traditional pagination using OFFSET and LIMIT becomes slow for large offsets because the database still scans all rows up to the offset. Keyset pagination (also called seek method) uses a WHERE clause on a unique column to skip rows.

Example: Instead of SELECT FROM orders ORDER BY id LIMIT 10 OFFSET 100000, use SELECT FROM orders WHERE id > 100000 ORDER BY id LIMIT 10. This uses an index on id and is constant time regardless of page number.

In an interview, explain that keyset pagination is preferred for large datasets, but requires a unique sort column.

pagination.sqlSQL
1
2
3
4
5
-- Slow: OFFSET pagination
SELECT * FROM orders ORDER BY id LIMIT 10 OFFSET 100000;

-- Fast: Keyset pagination
SELECT * FROM orders WHERE id > 100000 ORDER BY id LIMIT 10;
💡Interview Tip
📊 Production Insight
Keyset pagination is not suitable for arbitrary page jumps; use it for infinite scroll or 'load more' patterns.
🎯 Key Takeaway
Use keyset pagination instead of OFFSET for large datasets to maintain constant performance.

Handling N+1 Queries

The N+1 query problem occurs when an application executes one query to fetch a list of items, then for each item executes another query. This is common in ORMs like Hibernate or Django ORM. The solution is to use eager loading (JOINs) or batch queries.

Example: Fetching all customers and their orders. Instead of looping over customers and querying orders for each, use a single JOIN: SELECT c., o. FROM customers c LEFT JOIN orders o ON c.id = o.customer_id. Or use two queries: one for customers, another for orders with WHERE customer_id IN (...).

In an interview, recognize N+1 as a performance anti-pattern and propose solutions.

n_plus_one.sqlSQL
1
2
3
4
5
6
-- N+1: One query for customers, then N queries for orders
SELECT * FROM customers; -- 1 query
-- For each customer: SELECT * FROM orders WHERE customer_id = ?; -- N queries

-- Solution: JOIN
SELECT c.*, o.* FROM customers c LEFT JOIN orders o ON c.id = o.customer_id;
🔥ORM Pitfall
📊 Production Insight
Use database query logging to detect N+1 patterns in development before they hit production.
🎯 Key Takeaway
Avoid N+1 queries by using JOINs or batch queries; be aware of ORM lazy loading behavior.

Common Pitfalls and Anti-Patterns

Several common mistakes degrade SQL performance
  • Using functions on indexed columns in WHERE clauses (e.g., WHERE YEAR(date) = 2023) prevents index usage.
  • Using SELECT * returns unnecessary columns and prevents covering indexes.
  • Over-indexing: too many indexes slow down writes and confuse the optimizer.
  • Not using EXPLAIN before optimization.
  • Ignoring data types: implicit conversions can cause index scans to become seq scans.

In an interview, demonstrate awareness of these pitfalls and how to avoid them.

pitfalls.sqlSQL
1
2
3
4
5
-- Bad: function on column prevents index
SELECT * FROM orders WHERE YEAR(created_at) = 2023;

-- Good: range query uses index
SELECT * FROM orders WHERE created_at >= '2023-01-01' AND created_at < '2024-01-01';
⚠ Implicit Conversion
📊 Production Insight
Set up a query review process to catch anti-patterns before deployment.
🎯 Key Takeaway
Avoid functions on indexed columns, SELECT *, and over-indexing; use EXPLAIN to verify.
● Production incidentPOST-MORTEMseverity: high

The Slow Dashboard That Took Down the App

Symptom
Users reported the dashboard page taking over 30 seconds to load, and the database CPU hit 100%.
Assumption
The developer assumed the query was fast because it worked fine on the small test database.
Root cause
Missing index on the foreign key column used in JOIN, causing a full table scan on a 10-million-row table.
Fix
Added a B-tree index on the foreign key column, reducing query time from 30 seconds to 200ms.
Key lesson
  • Always index foreign keys used in JOINs.
  • Test queries on production-sized data or use EXPLAIN ANALYZE.
  • Monitor slow query logs and set up alerts.
  • Use covering indexes to avoid table lookups.
  • Consider composite indexes for multi-column filters.
Production debug guideSymptom to Action4 entries
Symptom · 01
Query takes too long
Fix
Run EXPLAIN ANALYZE to identify full table scans or missing indexes.
Symptom · 02
High CPU usage
Fix
Check for heavy sorts, hash joins, or Cartesian products.
Symptom · 03
Slow pagination with OFFSET
Fix
Switch to keyset pagination using WHERE and LIMIT.
Symptom · 04
N+1 queries in application
Fix
Use JOIN or batch queries to reduce round trips.
★ Quick Debug Cheat SheetImmediate actions for common SQL performance issues.
Slow query
Immediate action
Run EXPLAIN ANALYZE
Commands
EXPLAIN ANALYZE SELECT ...
SHOW INDEX FROM table
Fix now
Add missing index or rewrite query
High CPU+
Immediate action
Check for full table scans
Commands
EXPLAIN SELECT ...
SHOW PROCESSLIST
Fix now
Add WHERE clause or index
Slow pagination+
Immediate action
Replace OFFSET with keyset
Commands
SELECT * FROM t WHERE id > last_id LIMIT 10
EXPLAIN that query
Fix now
Use keyset pagination
TechniqueWhen to UseProsCons
B-tree indexEquality and range queriesFast lookups, supports sortingNot good for full-text search
Composite indexMulti-column filtersEfficient for combined conditionsColumn order matters
Covering indexQueries with few columnsIndex-only scans, no table accessLarger index size
Partial indexFrequent filtered subsetSmaller index, faster writesOnly useful for specific queries
⚙ Quick Reference
6 commands from this guide
FileCommand / CodePurpose
explain_example.sqlEXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 123;Understanding Execution Plans
create_index.sqlCREATE INDEX idx_users_status_created ON users (status, created_at DESC) INCLUDE...Indexing Strategies
rewrite.sqlSELECT * FROM orders WHERE customer_id IN (SELECT id FROM customers WHERE status...Query Rewriting Techniques
pagination.sqlSELECT * FROM orders ORDER BY id LIMIT 10 OFFSET 100000;Pagination Optimization
n_plus_one.sqlSELECT * FROM customers; -- 1 queryHandling N+1 Queries
pitfalls.sqlSELECT * FROM orders WHERE YEAR(created_at) = 2023;Common Pitfalls and Anti-Patterns

Key takeaways

1
Always start optimization with EXPLAIN ANALYZE to understand the execution plan.
2
Index wisely
use composite and covering indexes based on query patterns.
3
Avoid common anti-patterns like SELECT *, functions on columns, and N+1 queries.
4
Use keyset pagination for large datasets instead of OFFSET.
5
Balance read performance with write overhead when adding indexes.

Common mistakes to avoid

3 patterns
×

Using SELECT * in production queries

×

Applying functions to indexed columns in WHERE

×

Over-indexing without monitoring

INTERVIEW PREP · PRACTICE MODE

Interview Questions on This Topic

Q01SENIOR
How would you optimize a slow query that joins three large tables?
Q02SENIOR
Explain the difference between IN and EXISTS. When would you use each?
Q03SENIOR
How do you handle pagination for a table with millions of rows?
Q01 of 03SENIOR

How would you optimize a slow query that joins three large tables?

ANSWER
First, run EXPLAIN to see the execution plan. Check for missing indexes on join columns and WHERE filters. Consider rewriting the query to reduce the result set early, maybe using subqueries to filter before joining. Also, ensure statistics are up to date. If possible, denormalize or use materialized views.
FAQ · 3 QUESTIONS

Frequently Asked Questions

01
What is the difference between clustered and non-clustered indexes?
02
How do you optimize a query with multiple JOINs?
03
What is a covering index?
N
Naren Founder & Principal Engineer

20+ years shipping production code across the stack, with years spent interviewing engineers. Drawn from code that ran under real load.

Follow
Verified
production tested
July 13, 2026
last updated
2,165
articles · all by Naren
🔥

That's Database Interview. Mark it forged?

3 min read · try the examples if you haven't

Previous
MongoDB Interview Questions
7 / 7 · Database Interview
Next
Common HR Interview Questions