Day 41 – SQL CREATE INDEX Statement
In SQL, an index is a database object that improves the performance of SQL queries by allowing them to retrieve data more efficiently. An index is created on one or more columns of a table to help the database engine quickly find the rows that match a search condition. The CREATE INDEX statement is used to create an index on one or more columns of a table.
The syntax for creating an index on a table is as follows:
CREATE [UNIQUE] INDEX index_name
ON table_name (column1 [, column2, ...]);
In the above syntax,
index_name is the name of the index,
table_name is the name of the table on which the index is being created,
column2, etc. are the columns on which the index is being created.
If you specify UNIQUE keyword in the CREATE INDEX statement, the index will enforce uniqueness on the specified columns, i.e., it will not allow duplicate values in the indexed columns.
For example, let’s say we have a table named “employees” with columns “id”, “first_name”, “last_name”, and “department”. We want to create an index on the “last_name” column to improve the performance of queries that search for employees by last name. The CREATE INDEX statement for this index would be as follows:
CREATE INDEX idx_last_name
ON employees (last_name);
In the above example, we have created an index named “idx_last_name” on the “last_name” column of the “employees” table.
It is important to note that creating an index may improve the performance of queries that search for data in the indexed column(s), but it may also slow down the performance of queries that update or insert data into the table. Therefore, it is recommended to create indexes on columns that are frequently used in WHERE clauses of SELECT statements and not on columns that are frequently updated.