Index in SQL | Alter Table Add Index- sql - sql tutorial - learn sql

What is an index in a SQL?
- Indexes are used to find rows with specific column values quickly.
- Without an index, MySQL must begin with the first row and then read through the entire table to find the relevant rows.
- Most MySQL indexes (PRIMARY KEY, UNIQUE, INDEX, and FULLTEXT) are stored in B-trees.
- Exceptions: Indexes on spatial data types use R-trees; MEMORY tables also support hash indexes; InnoDB uses inverted lists for FULLTEXT indexes.

What is the use of index in SQL?
- An index is used to speed up the performance of queries. It does this by reducing the number of database data pages that have to be visited/scanned.
- In SQL Server, a clustered index determines the physical order of data in a table.
- There can be only one clustered index per table (the clustered index IS the table)
ADD INDEX IN SQL
- To retrieve data from the database very fast using indexes.
- The users can’t see the indexes, they are just used to speed up searches/queries.
Read Also
Sequence and Nextval in SQL.Pages in Different types and Levels

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.
Architecture of Clustered Index


Architecture of Non Clustered Index

The Difference between the Clustered and Non Clustered Indexes

Read Also
Decode SQL.SQL > ALTER TABLE > Add Index Syntax
- Sometimes after a table has been created in a database.
- we find that it is advantages to add an index to that table to speed up queries involving this table (to understand what an index is and how it can help speed up SQL queries).
- To do this in SQL, we specify that we want to change the table structure via the ALTER TABLE command.
- The ADD INDEX command to tell the RDBMS that we want to add an index as follows.
Syntax for adding an index to an existing table is,
ALTER TABLE "table_name"
ADD INDEX "index_name" (column_name);
For example:
- Assuming our initial point is the Student table created in the CREATE TABLE section:
Table Student
Column Name | Data Type |
---|---|
First_Name | char(50) |
Last_Name | char(50) |
Address | char(50) |
City | char(50) |
Country | char(25) |
Birth_Date | datetime |
- Assume we want to add an index on the "Country" column. To do this, we type in the following:
ALTER TABLE Student ADD INDEX IDX_COUNTRY (Country);
Note:
- Using ALTER TABLE to add an index is supported in MySQL but not in Oracle or SQL Server.