Query Optimization Interview Questions
Master SQL Query Optimization with interview-focused questions covering Query Optimizer, Cost-Based Optimization, SARGable Queries, Predicate Pushdown, Join Optimization, EXISTS vs IN, CTEs, Pagination, Query Rewriting, and production best practices.
Introduction
Query Optimization is the process of writing SQL statements that retrieve data using the least possible CPU, memory, disk I/O, and network bandwidth.
A poorly written query can turn a millisecond operation into several minutes, even on powerful hardware.
Every enterprise application depends on query optimization because databases process
- Banking Transactions
- Payment Systems
- E-Commerce Orders
- Healthcare Records
- ERP Systems
- Analytics
- Reporting
Understanding query optimization is one of the most frequently asked database interview topics.
Query Optimization Architecture
flowchart LR
Application --> SQLQuery --> Parser --> Optimizer --> ExecutionPlan --> StorageEngine --> Result
1. What is Query Optimization?
Answer
Query Optimization is the process of improving SQL queries so they execute faster while consuming fewer resources.
Goals
- Faster Response Time
- Lower CPU
- Less Memory
- Less Disk IO
- Better Scalability
2. Why is Query Optimization important?
Without optimization
Millions of rows
↓
Full Table Scan
↓
Slow Application
With optimization
Indexed Search
↓
Milliseconds
3. What is the Query Optimizer?
The Query Optimizer determines the most efficient execution plan.
It considers
- Available Indexes
- Table Statistics
- Row Count
- Join Order
- Query Cost
Query Optimizer
flowchart LR
SQL --> Optimizer
Optimizer --> ExecutionPlan
4. What is Cost-Based Optimization (CBO)?
The optimizer estimates
- CPU Cost
- IO Cost
- Memory Cost
and chooses the least expensive execution plan.
Modern databases use Cost-Based Optimization.
5. What was Rule-Based Optimization (RBO)?
Older databases used predefined rules.
Example
Always use Index
Modern databases rarely use RBO.
6. What is the SQL Execution Lifecycle?
SQL Query
↓
Parser
↓
Optimizer
↓
Execution Plan
↓
Execution Engine
↓
Storage Engine
↓
Result
SQL Execution Flow
flowchart LR
SQL --> Parser --> Optimizer --> ExecutionPlan --> ExecutionEngine --> Storage
7. What is Predicate Pushdown?
Filtering rows
as early as possible.
Instead of
Read All Rows
↓
Filter
Use
Filter First
↓
Read Less Data
Predicate Pushdown
flowchart LR
StorageEngine --> Filter --> MatchingRows --> Application
8. What is Projection Optimization?
Return only required columns.
Bad
SELECT *
FROM Employee;
Better
SELECT
employee_id,
name
FROM Employee;
9. What is a SARGable Query?
SARGable
Search ARGument Able
Allows indexes to be used efficiently.
Good
WHERE salary > 50000
Bad
WHERE salary + 100 > 50000
10. Why are functions on indexed columns bad?
Example
WHERE
YEAR(order_date)=2025
Index cannot be used efficiently.
Better
WHERE
order_date >= '2025-01-01'
AND
order_date < '2026-01-01'
11. What is Query Rewriting?
Changing SQL without changing results.
Example
Bad
SELECT *
FROM Employee
Better
SELECT
employee_id,
name
12. What is Join Optimization?
Optimizer chooses
- Join Order
- Join Algorithm
- Index Usage
to reduce execution cost.
Join Optimization
flowchart LR
TableA --> Optimizer
TableB --> Optimizer
Optimizer --> JoinPlan
13. What are Join Algorithms?
Common algorithms
- Nested Loop Join
- Hash Join
- Merge Join
14. What is Nested Loop Join?
Outer table
↓
For every row
↓
Search inner table
Efficient for
small datasets.
15. What is Hash Join?
Creates a hash table
then matches rows.
Good for
large datasets.
16. What is Merge Join?
Requires sorted input.
Very efficient
for already sorted data.
Join Comparison
| Join | Best For |
|---|---|
| Nested Loop | Small Tables |
| Hash Join | Large Tables |
| Merge Join | Sorted Data |
17. EXISTS vs IN?
Generally
EXISTS
↓
Large datasets
IN
↓
Small datasets
Optimizer may rewrite them similarly in modern databases.
18. UNION vs UNION ALL?
UNION
↓
Removes duplicates
↓
Slower
UNION ALL
↓
No duplicate removal
↓
Faster
19. DISTINCT vs GROUP BY?
Both remove duplicates.
DISTINCT
↓
Simpler
GROUP BY
↓
Aggregation
20. What are Correlated Subqueries?
Subquery executes
once per outer row.
Often slower.
21. How can correlated subqueries be optimized?
Replace with
- JOIN
- EXISTS
- CTE
when appropriate.
22. What is a CTE?
Common Table Expression
Improves readability.
Example
WITH Sales AS (
SELECT *
FROM Orders
)
SELECT *
FROM Sales;
23. Are CTEs always faster?
No.
Performance depends on
- Database Engine
- Optimizer
- Query Structure
24. What is Pagination Optimization?
Bad
LIMIT 100000,20
Better
Keyset Pagination
WHERE id > 100000
Pagination
flowchart LR
LargeTable --> IndexedColumn --> NextPage
25. What is Batch Processing?
Instead of
1 Million Updates
Execute
1000 Rows
per Batch
Reduces locks
and
memory usage.
26. Why avoid SELECT *?
Problems
- More Network Traffic
- More Memory
- Larger Result Sets
- Poor Cache Efficiency
27. Banking Example
Bad
SELECT *
FROM Transactions
Better
SELECT
transaction_id,
amount
FROM Transactions
WHERE account_id=100;
28. E-Commerce Example
Use
Compound Index
category,
brand
instead of scanning products.
29. HR Example
Search employee
using
Primary Key
instead of
employee name.
30. Logging Example
Filter logs
by
timestamp
before reading
millions of records.
31. Common Query Optimization Mistakes
- SELECT *
- Missing WHERE clause
- Functions on indexed columns
- Missing indexes
- Large OFFSET pagination
- Correlated subqueries
- Returning unnecessary rows
Query Optimization Workflow
flowchart LR
SlowQuery --> Analyze --> Rewrite --> ExplainPlan --> Optimization --> Validation
Enterprise Best Practices
- Return only required columns.
- Filter data as early as possible.
- Use indexes effectively.
- Avoid functions on indexed columns.
- Prefer UNION ALL when duplicates are acceptable.
- Use EXISTS for large existence checks.
- Keep joins simple.
- Avoid correlated subqueries where possible.
- Use keyset pagination for large datasets.
- Validate improvements using EXPLAIN.
Quick Revision
| Topic | Key Point |
|---|---|
| Query Optimizer | Best Execution Plan |
| CBO | Cost-Based Optimization |
| Predicate Pushdown | Filter Early |
| Projection | Return Required Columns |
| SARGable | Index-Friendly Query |
| EXISTS | Large Datasets |
| IN | Small Lists |
| UNION | Removes Duplicates |
| UNION ALL | Faster |
| CTE | Readability |
| Keyset Pagination | Better than OFFSET |
Interview Tips
Interviewers frequently ask
- What is Query Optimization?
- What is Cost-Based Optimization?
- What is a SARGable query?
- Why avoid SELECT *?
- EXISTS vs IN?
- UNION vs UNION ALL?
- What is Predicate Pushdown?
- What are Join Algorithms?
- Why are functions on indexed columns bad?
- How do you optimize a slow SQL query?
A strong production answer is:
- Identify the slow query.
- Analyze the execution plan.
- Verify index usage.
- Rewrite the SQL if necessary.
- Reduce scanned rows.
- Validate the performance improvement.
This demonstrates real production troubleshooting experience.
Summary
Query Optimization is the foundation of high-performance database systems. By understanding how the optimizer works, writing SARGable queries, minimizing scanned data, choosing efficient joins, optimizing pagination, and leveraging indexes correctly, developers can dramatically improve application performance.
Mastering query optimization techniques prepares Backend Developers, Database Engineers, and Solution Architects to design scalable enterprise systems capable of handling millions of transactions efficiently.