SQL Indexing¶
๐ง What is an Index?¶
An index in SQL is a special data structure that improves the speed of data retrieval from a table.
Think of a book:
- Without index โ you read every page to find a topic
- With index โ you directly jump to page number
Database index works exactly like that.
It helps database find rows faster instead of scanning the full table.
๐๏ธ Why Index is Important?¶
Without index:
Database checks every row (full table scan).
With index: Database jumps directly to matching rows.
Result:
- Faster queries
- Better performance
- Essential for large tables
๐ When to Use Index?¶
Use index on:
- Columns used in WHERE clause
- JOIN columns
- ORDER BY columns
- PRIMARY KEY
- Frequently searched columns
Example:
๐งพ Basic Syntax¶
Create index¶
Example:
๐ Check existing indexes¶
โ Delete index¶
๐งช Example with employees table¶
Without index:
Create index:
Now search becomes very fast.
๐ง Types of Indexes¶
1. Single Column Index¶
2. Composite Index (multiple columns)¶
Used when query has both columns:
3. Unique Index¶
Prevents duplicate values.
Now duplicate email cannot be inserted.
โก Primary Key = Index¶
When you create primary key:
PostgreSQL automatically creates index.
๐ How index improves performance¶
Without index:
With index:
Huge difference in big tables.
โ ๏ธ When NOT to use index¶
Avoid too many indexes because:
- Slows INSERT/UPDATE
- Takes storage
- Extra maintenance
Do NOT index:
- very small tables
- columns rarely used
- columns with few unique values (gender)
๐ Real-world usage¶
Used in:
- Banking apps
- E-commerce search
- Login systems
- Large analytics queries
- Production databases
Every big company relies on indexing.
๐งช Practice tasks¶
- Create index on employee name
- Create index on salary
- Create composite index (dept_id, salary)
- Drop index
- Check indexes in table
๐ง Interview Questions¶
Q1: What is index? โ Improves query performance
Q2: Does index store data? โ Stores pointer to data
Q3: Can too many indexes slow DB? โ Yes (insert/update slow)
Q4: Primary key creates index? โ Yes automatically
๐ฏ Summary¶
Index is:
- performance booster
- used for fast search
- essential in real production DB
- must be used wisely
Without index โ slow queries With index โ fast database
๐ Next Topics to Learn¶
After indexing:
- Window functions
- CTE
- Query optimization
- Execution plan
- Advanced joins
These make you strong SQL developer.