1.54k likes | 3k Views
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
E N D
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_CustomerKeyON 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 B-tree 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
Syntax for Standard Non Clustered Index CREATE NONCLUSTERED INDEX Ix_LastNameON Customer(LastName) The term NONCLUSTERED is optional
Unique, Composite, and Filtered Indexes CREATE UNIQUE INDEX ix_EmailON Customer(CustomerEmail) CREATE INDEX ix_AddressONCustomerAddress(City, State, Zip) CREATE INDEX ix_ApartmentONCustomerAddress(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 WHEREEmployeeName='John Smith' WITH (NOLOCK, INDEX(ix_EmployeeName))
Enabling,Disabling and Dropping Indexes ALTER INDEX ix_EmployeeNameON Employee DISABLE ALTER INDEX ix_EmployeeNameON Employee REBUILD DROP INDEX ix_EmployeeNameON Employee
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