An index is a data structure associated with a table that provides fast access to rows in a table based on the values in one or more columns (the index key).
Let's say, you have a customers table in your database and you want to find out all the customers whose names begin with the letter A, using the following statement.
SELECT cust_id, cust_name, address FROM customers
WHERE cust_name LIKE 'A%';
To find such customers, server must scan each row one by one in the customers table and inspect the contents of the name column. While it works fine for a table having few rows, but imagine how long it might take to answer the query if the table contains million of rows. In such situation you can speed things up by applying indexes to the table.
You can create indexes with the CREATE INDEX
statement:
For example, to create an index on the name column in the customers table, you could use:
CREATE INDEX cust_name_idx ON customers (cust_name);
You can also build the indexes that span multiple columns. For example, suppose you've a table in your database named users having the columns first_name and last_name, and you frequently access the user's records using these columns then you can build an index on both the columns together to improve the performance, as follow:
Index should be created with care. Because, every time a row is added, updated or removed from a table, all indexes on that table must be modified. Therefore, the more indexes you have, the more work the server needs to do, which finally leads to slower performance.
Here are some basic guidelines that you can follow while creating index:
Also, small tables do not require indexes, because in the case of small tables, it is usually faster for the server to scan the table rather than look at the index first.
You can drop indexes that are no longer required with the following statement.
The following statement will drop the index cust_name_idx from the customers table.
DROP INDEX cust_name_idx ON customers;