SQL — Indexes
What is an index?
Database structure that improves query speed.
Create index
CREATE INDEX idx_users_email ON users(email);
Unique index
CREATE UNIQUE INDEX idx_users_email ON users(email);
Composite index
CREATE INDEX idx_orders_user_date ON orders(user_id, order_date);
Drop index
DROP INDEX idx_users_email;
View indexes
-- MySQL
SHOW INDEX FROM users;
-- PostgreSQL
SELECT * FROM pg_indexes WHERE tablename = 'users';
When to index
- Columns in WHERE clause
- Columns in JOIN conditions
- Columns in ORDER BY
- High-cardinality columns
When NOT to index
- Small tables
- Columns with low cardinality
- Frequently updated columns
- Tables with heavy writes
Performance impact
-- Without index: Full table scan
-- With index: Index scan (faster)
EXPLAIN SELECT * FROM users WHERE email = 'test@example.com';
Mini Practice
- Create an index
- Create composite index
- Check query performance
- Drop unused indexes
Up Next
Continue with Constraints - Table constraints.
Related Topics
Frequently Asked Questions about Indexes
What is Indexes in SQL?
Indexes is a fundamental concept in SQL. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Indexes?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Indexes.
Why is Indexes important in SQL?
Indexes is essential for SQL development. Understanding this concept will help you write better code and solve real-world problems more effectively.