SQL Tutorial
An index in SQL is used to speed up the retrieval of records on a database table. Essentially, an index in a database is similar to an index in a book - it's a lookup that the database can use to find data.
Indexes can be created on any combination of columns in a database table and are a powerful tool to improve database performance. However, while they speed up query performance, they can slow down data input, such as with UPDATE
and INSERT
statements because the index also needs to be updated.
The SQL command to create an index on a table is CREATE INDEX
.
Syntax:
CREATE INDEX index_name ON table_name (column1, column2, ...);
The CREATE INDEX
statement is used to create indexes in tables.
Example:
CREATE INDEX idx_employee ON Employee (LastName, FirstName);
This example would create an index named idx_employee
on the Employee
table for the columns LastName
and FirstName
.
Note:
Indexes, while powerful for read operations, can decrease performance on write operations (INSERT, UPDATE, DELETE) as indexes need to be maintained and updated.
Indexes can be unique, similar to UNIQUE
constraint, using CREATE UNIQUE INDEX
which ensures that two rows cannot have the same index value.
It's usually best to index columns that have high selectivity, i.e., columns that have many different values.
The syntax for creating indexes varies among different SQL dialects. In some databases, you can't directly create an index with the CREATE INDEX
statement inside a database schema, but you can do so when you create the table with the CREATE TABLE
statement.
As always, it's important to consult the specific SQL dialect documentation for further details and to understand the nuances of the CREATE INDEX
operation.
Creating Indexes in SQL:
CREATE INDEX IndexName ON TableName (ColumnName);
Types of Indexes in Relational Databases:
CREATE INDEX BtreeIndex ON TableName (ColumnName);
SQL UNIQUE Index:
CREATE UNIQUE INDEX UniqueIndex ON TableName (ColumnName);
Composite Indexes in SQL:
CREATE INDEX CompositeIndex ON TableName (Column1, Column2);
SQL INDEX vs PRIMARY KEY:
Description: An index enhances query performance, while a PRIMARY KEY uniquely identifies each record in a table.
Code Example (PRIMARY KEY):
CREATE TABLE TableName ( ID INT PRIMARY KEY, ColumnName VARCHAR(255) );
Code Example (INDEX):
CREATE INDEX IndexName ON TableName (ColumnName);
Dropping Indexes in SQL:
DROP INDEX IndexName ON TableName;