SQL Server Indexes

download report

Transcript SQL Server Indexes

SQL Server Indexes
Indexes
Overview
• Indexes are used to help speed search results in a database. A careful use of
indexes can greatly improve search speeds. Over use of indexes, however,
can painfully slow database inserts and updates.
Types of indexes
• Clustered Indexes
• Non Clustered Indexes
•
•
•
•
Standard non clustered
Unique
Filtered
Composite (more than one field)
Clustered Indexes
• A clustered index physically reorders the table contents
• Clustered indexes are usually assigned to a tables primary key
• There can only be one clustered index per table.
CREATE CLUSTERED INDEX ix_CustomerKey ON
Customer(CustomerKey)
Non Clustered Indexes
• Non Clustered indexes form a separate structure called a B-Tree that greatly
speeds searches.
• Instead of going through thousands or millions of rows to find a value, the Btree enables a search using only a very few records.
• Indexes can slow INSERTS, UPDATES and DELETES because the B-Tree
index must be rebuilt each time
B-Tree Structure
Syntax for Standard Non Clustered Index
CREATE NONCLUSTERED INDEX Ix_LastName ON
Customer(LastName)
The term NONCLUSTERED is optional
Unique, Composite, and Filtered Indexes
CREATE UNIQUE INDEX ix_Email ON
Customer(CustomerEmail)
CREATE INDEX ix_Address ON CustomerAddress(City,
State, Zip)
CREATE INDEX ix_Apartment ON
CustomerAddress(Apartment) WHERE Apartment IS NOT
NULL
Columnstore Indexes
• This is a new type of index available only in Enterprise Editions of SQL
Server 2012 or later. Instead of storing the data rows contiguously across
pages it stores the data in columns contiguously across pages.
• These are best used in data warehousing or read only databases
Forcing an index
• The database management system query optimization system will ignore
indexes in tables with few rows. It is more efficient to skip the index with
under 10,000 rows or so, but you can force an index:
SELECT * FROM Employee WHERE EmployeeName='John
Smith' WITH (NOLOCK, INDEX(ix_EmployeeName))
Enabling,Disabling and Dropping Indexes
• ALTER INDEX ix_EmployeeName ON Employee
• ALTER INDEX ix_EmployeeName ON Employee
• DROP INDEX ix_EmployeeName ON Employee
DISABLE
REBUILD
Testing Queries
• SQL Server contains tools for testing and comparing query results
Best Practices
• Indexes should be applied on Columns used often in searches.
• Foreign keys make good candidates for indexes
• It takes careful testing to be sure where to place indexes