⬅ Previous Topic
SQL ViewsNext Topic ⮕
SQL Constraints⬅ Previous Topic
SQL ViewsNext Topic ⮕
SQL ConstraintsImagine you’re trying to find one student’s report from thousands of records. Scanning everything line by line would be slow. What if your database had a smart “table of contents” to jump straight to the relevant entry? That’s what an index does in SQL.
A SQL INDEX
is a performance optimization structure. It allows the database to find and retrieve data faster — similar to how a book index helps locate chapters quickly.
WHERE
clausesJOIN
or ORDER BY
CREATE TABLE students (
roll_no INT PRIMARY KEY,
name VARCHAR(50),
class VARCHAR(10),
city VARCHAR(30)
);
INSERT INTO students VALUES
(1, 'Aarav Sharma', '10A', 'Delhi'),
(2, 'Diya Iyer', '9B', 'Chennai'),
(3, 'Sneha Patil', '10A', 'Pune'),
(4, 'Mehul Agarwal', '9B', 'Delhi'),
(5, 'Saira Bano', '8C', 'Hyderabad');
Let’s create an index on the city
column since we often search students by city:
CREATE INDEX idx_city
ON students(city);
Now, this query becomes faster with the index:
SELECT name, class
FROM students
WHERE city = 'Delhi';
name | class
----------------+-------
Aarav Sharma | 10A
Mehul Agarwal | 9B
Create an index on both class
and city
for combined filters:
CREATE INDEX idx_class_city
ON students(class, city);
This helps with queries like:
SELECT name
FROM students
WHERE class = '9B' AND city = 'Delhi';
name
----------
Mehul Agarwal
Indexes can also enforce uniqueness (aside from primary keys):
CREATE UNIQUE INDEX idx_unique_name
ON students(name);
This prevents duplicate names (useful if names must be unique in your context).
DROP INDEX idx_city;
The school admin needs to quickly list students by city and class — indexing those columns speeds up daily reporting, especially when thousands of students are enrolled.
SQL indexes are the silent speed-boosters of your database. By indexing the right columns — like student names, cities, or class identifiers — you can dramatically improve query performance. Just like a smart librarian, indexes help SQL find answers fast.
Next, we’ll learn about SQL Transactions — ensuring data consistency when multiple queries run together.
CREATE INDEX idx_rollno ON students(roll_no);
⬅ Previous Topic
SQL ViewsNext Topic ⮕
SQL ConstraintsYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.