A DATABASE INDEX is a database structure that improves the
speed of data retrieval operations on a database table.
Indexes are used to quickly locate data without having to search
every row in database table every time a database table is
accessed.
Indexes can be created using one or more columns of a
database table, providing the basis for both rapid random
lookups and efficient access of ordered records.
Uses of indexes
1. It supports fast lookup: most database software includes
indexing technology that enables sub-linear time lookup to
improve performance as linear search is inefficient for large
database.
2. It is used to add constrain to database: indexes are used to
add database constraints such as unique, exclusion, primary
key and foreign key.
How to create an index in SQL
Syntax:
CREATE INDEX <index_name>
ON <table_name> (column1, column2…….)
Suppose we have a customer
table like one below. We want
to create an index to speed up
the search by customer name.
Syntax:
CREATE INDEX
ix_customername
ON customer
(Firstname, Lastname)
When executed, it will allow us
to search much faster for data
in the Firstname and Lastname
columns
Types of index
Clustered index
This index sort and store the data rows in the table or
view it based on their key values. These are the columns
included in the index definition.
the purpose of clustered index is to physically store the rows in ASC or DESC order based on the column selected.
Suppose we want
to store data
alphabetically by
first and last
names in our CREATE CLUSTERED INDEX ci_firstname_lastname
database. To ON customer (Firstname ASC, Lastname ASC)
create a clustered
index to do so, we
write the following
query.
The data now sorted by first name and last
name
Bitmap index
This is a special type of index that makes use of
bitmaps. This technique is used to filter huge amount
of database when column is of low cardinality and
this columns are most frequently used in the query.
Imagine our customer
table has not just 5
rows but over 10
million rows. Suppose
we have to filter our
SELECT firstname, lastname,
table for female
email
customer whose last
FROM customer
name is Watson. We
WHERE gender = 2 AND
may write a query like
lastname = “Watson”
the following
CREATE BITMAP INDEX
To speed up the query with
BMP_gender
bitmap index, we create the
ON customer (gender)
following syntax
The bitmap index is ideal here because we have only few distinct
values for gender compared to other columns in the table.