softwaretips4u Tips that Transform
← Back to Homepage ← Back to Articles

SQL Index Performance Analysis and Query Optimization

🔹 1️⃣ What Are Indexes in SQL?

An index is a database object that keeps column values sorted so the optimizer can locate rows quickly instead of scanning the whole table. Faster reads come with a cost: every INSERT, UPDATE, or DELETE must also update the index.

⚙️ 2️⃣ How Indexes Work

⚙️ 3️⃣ Check Query Performance — EXPLAIN or EXPLAIN ANALYZE

Always compare execution plans before and after indexing to validate improvements.

EXPLAIN SELECT * FROM employees WHERE department_id = 5;

Plan output highlights whether the engine performs a sequential scan or an Index Scan/Index Only Scan.

⚙️ 4️⃣ Creating an Index

CREATE INDEX idx_emp_dept ON employees (department_id);

-- Use indexes on columns that:
-- • Appear in WHERE, JOIN, or ORDER BY clauses
-- • Have high selectivity (many unique values)

⚙️ 5️⃣ Composite (Multi-Column) Index

CREATE INDEX idx_emp_dept_name ON employees (department_id, last_name);
-- Order matters: (department_id, last_name) ≠ (last_name, department_id)
Composite indexes shine when queries filter on the leading column and at least one of the subsequent columns.

⚙️ 6️⃣ Example — With and Without Index

-- Without index (slow)
SELECT * FROM orders WHERE customer_id = 101;

-- Create index
CREATE INDEX idx_orders_custid ON orders (customer_id);

-- Now query becomes faster
SELECT * FROM orders WHERE customer_id = 101;
-- Validate improvement with EXPLAIN

⚙️ 7️⃣ Types of Indexes

Type Description
Clustered IndexReorders table data physically (only one per table).
Non-Clustered IndexSeparate structure storing key-value pointers to rows.
Unique IndexPrevents duplicate values in indexed columns.
Composite IndexIncludes multiple columns; order defines usefulness.
Full-Text IndexOptimized for searching text-heavy fields.
Bitmap IndexGreat for low-cardinality columns in warehouses.

⚙️ 8️⃣ Covering Index (Index-Only Query)

CREATE INDEX idx_emp_cover ON employees (department_id, salary);

SELECT department_id, salary
FROM employees
WHERE department_id = 10;
-- Query runs entirely from the index

When all referenced columns are in the index, the engine can skip table lookups, improving performance.

⚙️ 9️⃣ Dropping and Monitoring Indexes

DROP INDEX idx_emp_dept;
-- Monitor usage:
-- • sys.dm_db_index_usage_stats (SQL Server)
-- • pg_stat_user_indexes (PostgreSQL)
-- • EXPLAIN PLAN (Oracle/MySQL)

Regularly review usage stats to remove unused indexes that slow down write-heavy workloads.

⚙️ 🔟 Best Practices for Index Optimization

Tip Description
Use selective columnsIndex columns with high uniqueness to maximize index effectiveness.
Avoid indexing tiny tablesSequential scans can be faster on small datasets.
Composite order mattersPlace the most selective column first.
Limit total indexesExcessive indexes slow down writes and increase storage.
Rebuild regularlyUse ALTER INDEX REBUILD or VACUUM ANALYZE to fight fragmentation.
Test with EXPLAINCompare plans before vs. after indexing to confirm gains.

🧠 11️⃣ Exampl– Query Optimization Flow

-- Step 1 – Original query
SELECT * FROM sales WHERE region = 'West' AND amount > 5000;

-- Step 2 – Create index
CREATE INDEX idx_sales_region_amt ON sales (region, amount);

-- Step 3 – Check performance
EXPLAIN ANALYZE SELECT * FROM sales WHERE region = 'West' AND amount > 5000;
-- Expect Index Scan instead of Seq Scan

💡 12️⃣ Key Takeaways

Concept Summary
IndexImproves query read performance by enabling seeks.
CostAdds overhead to write operations.
ToolsUse EXPLAIN/EXPLAIN ANALYZE to validate usage.
StrategyIndex high-selectivity columns and common filters.
MaintenanceMonitor usage and rebuild/refresh statistics periodically.

🧠 Interview Tip

“Indexes speed up data retrieval but add write overhead. Always validate index usage with EXPLAIN or ANALYZE, and design composite indexes based on real query patterns.”
← Back to Articles | 🏠 Back to Homepage