Skip to main content

Command Palette

Search for a command to run...

🚀 Mastering Indexing in SQL

Published
4 min readView as Markdown

🚀 Mastering Indexing in SQL: A Complete Beginner's Guide with Examples

When working with databases, one common challenge is speed — especially when you're querying large tables with thousands or millions of rows. That’s where indexing comes into play.

In this blog, we’ll cover:

  • ✅ What is indexing?

  • ✅ Why and when it is used

  • ✅ How it works internally

  • ✅ Real-world examples with SQL code

  • ✅ Visualization with tables

  • ✅ Downsides of indexing

  • ✅ Summary of best practices


🔍 What is Indexing in SQL?

Indexing is a technique used in SQL to speed up the retrieval of data from a table by creating a special lookup structure (like a book’s index). Instead of scanning every row, the database engine can use the index to jump directly to the needed data.

🎯 Analogy:

Imagine a book with 1,000 pages. If you want to find "Photosynthesis," you wouldn't read every page—you’d use the index at the end to jump straight to it. The same idea applies in SQL.


🛠️ Why Use Indexing?

BenefitsExplanation
🔍 Faster SELECT QueriesIndexes let SQL quickly find rows matching a condition.
🔄 Faster JOINsSpeeds up operations that connect multiple tables.
📊 Efficient GROUP BY/ORDER BYOptimized sorting and grouping with indexed columns.

📋 Table Setup: Real SQL Example

Let’s say we have an Employees table:

CREATE TABLE Employees (
    EmployeeID INT PRIMARY KEY,
    Name VARCHAR(100),
    Department VARCHAR(50),
    Salary INT
);

Now, let’s insert some data:

sqlCopyEditINSERT INTO Employees VALUES 
(1, 'Amit', 'HR', 40000),
(2, 'Priya', 'IT', 60000),
(3, 'Ravi', 'Sales', 45000),
(4, 'Sneha', 'IT', 70000),
(5, 'Karan', 'HR', 42000),
(6, 'Neha', 'Sales', 46000),
(7, 'Vikas', 'IT', 50000),
(8, 'Deepa', 'Finance', 55000),
(9, 'Rohit', 'Sales', 47000),
(10, 'Meera', 'IT', 80000);

❌ Query Without Index (Slow Way)

Now, we want to find all employees from the Sales department:

SELECT * FROM Employees
WHERE Department = 'Sales';

Behind the scenes:

SQL engine will perform a full table scan, checking each row one by one:

RowDepartmentMatch?
1HR
2IT
3Sales
.........

This is fine for 10 rows, but very slow for 1 million rows.


✅ Create an Index (Fast Way)

Let’s create an index on the Department column:

CREATE INDEX idx_department
ON Employees (Department);

Now, SQL builds a separate internal index to make lookups faster.

Index Table (behind the scenes):

DepartmentPoints to Rows
FinanceRow 8
HRRows 1, 5
ITRows 2, 4, 7, 10
SalesRows 3, 6, 9

Query With Index:

SELECT * FROM Employees
WHERE Department = 'Sales';

Now, the system jumps directly to rows 3, 6, 9. ✅ Much faster!


📇 Final Output

EmployeeIDNameDepartmentSalary
3RaviSales45000
6NehaSales46000
9RohitSales47000

📉 Downsides of Indexing

DrawbackWhy it happens
⚠️ Slower INSERT/UPDATE/DELETEIndex also needs to be updated.
💾 Extra Disk SpaceIndexes take up storage.
🧪 Over-indexingToo many indexes can confuse the optimizer and degrade performance.

🧠 Clustered vs Non-Clustered Index (Conceptual)

FeatureClustered IndexNon-Clustered Index
Data StorageSorted by index keyStored separately from table data
Count per TableOnly oneCan have multiple
PerformanceFaster for range queriesFaster for exact match

🔸 Primary keys usually use clustered indexes automatically.


✅ Best Practices for Indexing

  • ✅ Index columns used often in WHERE, JOIN, ORDER BY.

  • ❌ Avoid indexing small tables or columns with few unique values (like Gender).

  • ✅ Use composite indexes when filtering by multiple columns.

  • ⚠️ Don’t over-index — it hurts write performance.


📦 Summary Table

OperationWithout IndexWith Index
SELECT queryFull table scanFast lookup
INSERT/UPDATEFastSlightly slower
Disk usageLowHigher
Use CaseSmall tablesLarge queries

💬 Final Thoughts

Indexing is one of the most powerful tools to optimize database performance. Used correctly, it can dramatically reduce query time, especially on large tables.

But it’s not a magic wand — understand when and where to apply it!

More from this blog

Amit singh's blog

235 posts