114 SQL CREATE INDEX
Summary of the W3Schools SQL CREATE INDEX Statement Page:
- The
CREATE INDEXstatement in SQL is used to create indexes on tables. - Indexes speed up data retrieval from a table, making searches and queries faster. Indexes are not visible to users.
- Updating a table with indexes takes more time because the indexes themselves must also be updated. It's advised to create indexes only on columns often searched.
- Syntax:
- Basic Index (allows duplicates):
CREATE INDEX index_name ON table_name (column1, column2, ...);- Unique Index (no duplicates allowed):
CREATE UNIQUE INDEX index_name ON table_name (column1, column2, ...); - Examples:
- Index on one column:
CREATE INDEX idx_lastname ON Persons (LastName);- Index on multiple columns:
CREATE INDEX idx_pname ON Persons (LastName, FirstName); - The
DROP INDEXstatement deletes indexes:- Syntax varies by SQL dialect (MS Access, SQL Server, DB2/Oracle, MySQL).
- Key point: Indexes are critical for performance in large databases but can slow down updates and inserts; use them wisely.[1]
SQL CREATE INDEX Statement
The CREATE INDEX statement is used to create indexes in tables.
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.
CREATE INDEX Syntax
Creates an index on a table. Duplicate values are allowed:
CREATE INDEX index_name
ON table_name (column1, column2, ...);
CREATE UNIQUE INDEX Syntax
Creates a unique index on a table. Duplicate values are not allowed:
CREATE UNIQUE INDEX index_name
ON table_name (column1, column2, ...);
Note: The syntax for creating indexes varies among different databases. Therefore: Check the syntax for creating indexes in your database.
CREATE INDEX Example
The SQL statement below creates an index named "idx_lastname" on the "LastName" column in the "Persons" table:
CREATE INDEX idx_lastname
ON Persons (LastName);
If you want to create an index on a combination of columns, you can list the column names within the parentheses, separated by commas:
CREATE INDEX idx_pname
ON Persons (LastName, FirstName);
DROP INDEX Statement
The DROP INDEX statement is used to delete an index in a table.
MS Access:
DROP INDEX index_name ON table_name;
SQL Server:
DROP INDEX table_name.index_name;
DB2/Oracle:
DROP INDEX index_name;
MySQL:
ALTER TABLE table_name
DROP INDEX index_name;