This
blog will demonstrates how to improve the SQL query performance by adding index
on SQL tables and will be discuss the scenarios where we should go with
clustered, non-clustered or single index on multiple columns.
Clustered
Index should be created on Column which uniquely identify to each row of tables
and it defines the physical order of table records and then generally table’s
primary key should be have clustered index. Now when you are going to create
other index (Non-clustered) which generally help SQL engine to create execution
plan and quickly filter the records.
If you
creates non-clustered index in very smartly way, then it will be more efficient
and more reusable.
Here
is an example - an order table which contain company huge order records
Table: Order
Table
Columns:
OrderID
|
PK
|
Primary Key
|
OrderDate
|
||
OrderNumber
|
||
State
|
||
City
|
||
Zip
|
On
Order table, mostly we make search by OrderNumber and also search by location
like State, City and Zip.
In
consideration of uniqueness of record, you create clustered index on OrderID
which is primary key of table and one more index (non-clustered) you can create
on Order Number.
If you
are looking search by location query, we are considering three columns (State,
City and Zip)
Then
mostly time we are searching order by State, City and zip combination
And
sometime by state and city and sometime by zip code only.
If you
are going to have single index which covers all columns (state, city and zip)
then it will helps in all scenarios except search by zip; so in this case we
need to have one more index on zip.
So
after considering all above scenarios, table should have below indexes
Index Name
|
Type of Index
|
Columns
|
Inx_OrderOrderID
|
Clustered Index
|
OrderID
|
Inx_OrderOrderNumber
|
Non-Clustred Index
|
OrderNumber
|
Inx_OrderStateCityZip
|
Non-Clustred Index
|
State, City, ZIP
|
Inx_OrderZip
|
Non-Clustred Index
|
ZIP
|
No comments:
Post a Comment