![]() |
VOOZH | about |
The CREATE INDEX statement in SQL is used to create indexes on tables to improve data retrieval speed and enhance query performance.
Example: First, we create a demo SQL database and table, on which we use CREATE INDEX command.
Query:
CREATE INDEX idx_employees_department
ON employees(department);
SELECT emp_name, salary
FROM employees
WHERE department = 'IT';
Output:
The CREATE INDEX command enables us to create an index on a table, improving query performance by providing a faster way to retrieve rows.
Syntax:
CREATE INDEX index_name
ON table_name (column1, column2.....);
Creating a Unique Index:
A unique index ensures that all values in the indexed columns are unique preventing duplicate values.
CREATE UNIQUE INDEX index_name
ON table_name (column1, column2.....);
Letβs look at an example where we use the CREATE INDEX command on a Students table given below
In this example, we will create an index on the name column of the Students table to speed up queries that search by name.
Query:
CREATE INDEX idx ON
Students(NAME);
--Creating a Unique Index
CREATE UNIQUE INDEX idx_student_id ON
Students(student_id);
Explanation:
After creating the index, queries that use the name column in their WHERE clause will benefit from the faster data retrieval provided by the index. The USE INDEX hint directs the query to use the idx_name index to speed up data retrieval.
Query:
SELECT * FROM Students USE INDEX(idx_name);Output:
We can view all the indexes in a database to understand which ones are in use and confirm their structure. In SQL, the following query helps us see the indexes for a given table:
Syntax:
SHOW INDEXES FROM Students;Output: