Wednesday, December 18, 2024

SQL INDEX Keyword

 In SQL, the INDEX keyword is used to create an index on a table. An index is a data structure that improves the speed of data retrieval operations on a table, at the cost of additional space and potential overhead during insert, update, and delete operations. It can be thought of as a pointer to data in a table, which helps queries find the data more efficiently.

Syntax:

CREATE [UNIQUE] INDEX index_name
ON table_name (column1, column2, ...);
  • UNIQUE (optional): Ensures that no two rows have the same values for the indexed columns.
  • index_name: The name of the index you are creating.
  • table_name: The name of the table on which the index is being created.
  • column1, column2, ...: The columns in the table that will be indexed.

Example:

CREATE INDEX idx_employee_name
ON employees (last_name, first_name);

This creates an index on the last_name and first_name columns in the employees table.

Types of Indexes:

  • Unique Index: Ensures all values in the indexed column are unique.
  • Composite Index: An index on multiple columns (as shown in the example above).
  • Full-text Index: Used for full-text searches in databases like MySQL and PostgreSQL.
  • Clustered Index: The data rows in the table are sorted in the same order as the index.
  • Non-clustered Index: The index is stored separately from the data rows, but a pointer is used to reference the data.

Benefits of Indexes:

  • Faster data retrieval (especially in SELECT queries).
  • Improved performance for queries with WHERE, ORDER BY, and JOIN clauses.

Drawbacks of Indexes:

  • Increased storage requirements.
  • Slightly slower performance on data modification operations (INSERT, UPDATE, DELETE) due to the need to update the index.

Dropping an Index:

You can remove an index using the DROP INDEX statement:

DROP INDEX index_name;

Example:

DROP INDEX idx_employee_name;

Indexes are powerful tools in SQL to improve performance but should be used wisely based on the specific needs of your database and queries.

No comments:

Post a Comment