Learn Clustered, Non-Clustered & Composite Indexes
Improve your SQL query performance with indexing. Learn about single-column and composite indexes, clustered vs non-clustered indexes, query optimization, and execution plans. Practice creating indexes and analyzing query performance for faster data retrieval.
1. Introduction
Indexes in SQL are special structures that speed up data retrieval from tables without scanning all rows.
- Essential for large datasets to optimize query performance.
- Proper indexing can drastically reduce query execution time.
Key Points:
- Indexes do not store data separately; they point to table rows.
- Over-indexing can slow down INSERT, UPDATE, DELETE operations.
- Use execution plans to analyze query performance.
2. What is an Index?
- An index is like a table of contents in a book.
- Helps the database engine quickly locate rows without scanning the entire table.
Syntax (Single Column Index):
Example:
3. Types of Indexes
3.1 Single Column Index
- Index on one column.
- Useful when queries filter or sort by a single column.
3.2 Composite Index
- Index on multiple columns.
- Useful when queries filter or sort using multiple columns together.
Example:
4. Clustered vs Non-Clustered Index
| TypeDescriptionNotes | ||
| Clustered Index | Sorts the actual table rows based on the indexed column | Only 1 clustered index per table |
| Non-Clustered Index | Stores pointers to table rows | Can have multiple non-clustered indexes |
Example (Clustered Index in SQL Server):
Example (Non-Clustered Index):
5. Query Optimization and Execution Plan
- Query optimization improves SQL performance.
- Execution plan shows how SQL Server executes a query.
Example:
Tips:
- Look for Index Seek (good) vs Table Scan (slower).
- Add indexes on columns used in WHERE, JOIN, ORDER BY clauses.
6. Practical Exercises
- Create a single-column index on Employee Name.
- Create a composite index on Department and Salary.
- Analyze query performance for filtering employees by Department.
- Compare execution time with and without indexes.
- Identify slow queries using execution plan and optimize them.
7. Tips for Beginners
- Index frequently queried columns for faster SELECTs.
- Avoid indexing columns that rarely appear in queries.
- Regularly maintain indexes in large tables.
- Use EXPLAIN / Execution Plan to identify performance issues.
Next Step: After mastering indexing and performance, the next module is Views in SQL, where you’ll learn to create, update, and use views to simplify queries and enhance security.