Indexes
Introduction to SQL
Database
SQL Basics
Creating a Database
Using a Database
Creating a Table
Common Data Types
Inserting Data
Selecting Data
WHERE Clause
Comparison Operators
AND, OR, and NOT
ORDER BY Clause
LIMIT Clause
DISTINCT
LIKE Operator
IN, BETWEEN, and IS NULL
Updating Data
Deleting Data
ALTER TABLE
DROP TABLE
PRIMARY KEY and NOT NULL
FOREIGN KEY and Relationships
Aggregate Functions
GROUP BY Clause
HAVING Clause
JOIN Basics
INNER JOIN
LEFT JOIN
Aliases
Subqueries
Indexes
User Permissions and Security
Common Mistakes Beginners Make
Practice Ideas
Indexes
SQL Indexes
Definition: An index is a powerful database object that improves the speed of data retrieval operations on a table. It acts as a performance-tuning tool that allows the database engine to find specific rows much faster than it could by searching every single record.
Simple Idea: Think of a database index exactly like the index at the back of a textbook. Instead of flipping through every page of the book to find a specific topic, you look it up in the index to find the exact page number and jump straight there. SQL indexes provide the same "shortcut" for your data.
Example: Creating an Index
If you frequently search for students by their names, you can create an index on the name column to speed up those specific queries.
CREATE INDEX idx_student_name ON students(name);
How It Works
- Retrieval Speed: When you run a query like
WHERE name = 'Ravi', the database checks theidx_student_namefirst. It finds the location of Ravi's data immediately, rather than performing a "Full Table Scan." - Storage: An index is a separate structure that takes up additional disk space. It stores a sorted version of the column's data along with pointers to the actual rows in the table.
- Automatic Indexes: Most databases automatically create an index for
PRIMARY KEYcolumns, as these are the most frequently searched fields.
Pros and Cons of Indexing
| Feature | Impact |
|---|---|
| Search Speed | Significantly Faster |
| Data Entry (INSERT/UPDATE) | Slightly Slower |
| Storage Space | Uses extra memory/disk space. |
Key Notes
- The Trade-off: While indexes make reading data (SELECT) much faster, they make writing data (INSERT, UPDATE, DELETE) slightly slower because the database has to update the index every time the data changes.
- When to Index: Only create indexes on columns that are used frequently in
WHEREclauses,JOINconditions, orORDER BYstatements. - Unique Indexes: You can create a
UNIQUE INDEXto both speed up searches and ensure that no two rows have the same value in that column (like an email address).