SQL Index
SQL Index
Indexes are used to retrieve data from the database more quickly than otherwise. The users
cannot see the indexes, they are just used to speed up searches/queries.
Note: Updating a table with indexes takes more time than updating a table without (because
the indexes also need an update). So, only create indexes on columns that will be frequently
searched against.
Note: The syntax for creating indexes varies among different databases. Therefore: Check the
syntax for creating indexes in your database.
Example
-- create table
CREATE TABLE Colleges (
college_id INT PRIMARY KEY,
college_code VARCHAR(20) NOT NULL,
college_name VARCHAR(50)
);
-- create index
CREATE INDEX college_index
ON Colleges(college_code);
Run Code
Here, the SQL command creates an index named college_index on the Colleges table using
the college_code column.
Here,
-- create table
CREATE TABLE Colleges (
college_id INT PRIMARY KEY,
college_code VARCHAR(20) NOT NULL,
college_name VARCHAR(50)
);
Here, the SQL command creates a unique index named college_index on the Colleges table
using the college_code column.
Note: Although the index is created for only unique values, the original data in the table
remains unaltered.
Remove Index From Tables
To remove INDEX from a table, we can use the DROP INDEX command. For example,
SQL Server
PostgreSQL, Oracle
MySQL
Here, the SQL command removes an index named college_index from the Colleges table.
Note: Deleting an index in SQL means only the index is deleted. The data in the original
table remains unaltered.