An Idea can change your life.....

Saturday, October 31, 2009

Index Seek VS Index scan

SQL Server can use different data access strategies when retrieving rows from the table. The strategy that will be used depends on the columns of the table, the available indexes, the query, the data in the table, and the statistics. There are 7 basic data access strategies.

SQL Server: Scans and seeks


The most primitive operation in SQL Server is retrieving from a table a set of rows that satisfies a given search predicate. This can be achieved using two basic strategies: scans and seeks.

Scan

Scans can be performed on any structure (index or heap). Scanning a table means that SQL Server reads all the rows in the table. Only the rows satisfying the search predicate are returned. Scans imply sequential reads that are usually faster than reading each page individually, but the cost of this operation is proportional to the size of the table.
In indexes, SQL Server uses the pointers to the next page (or previous) for scanning. In a heap, it uses the IAM pages.
The number of logical reads during this operation is the number of pages read during the scan, plus one logical read at each non-leaf level, in case of an index, in order to locate the first row of the table. This operation counts as a scan in the IO statistics.

Seek

Seeks can only be performed on indexes (clustered or nonclustered). A seek is performed when SQL Server can leverage the ordering of the rows in the index to identify a range of rows in the index that contains all the rows satisfying the search predicate.
The search predicate is divided in two parts:
  • The seek predicate, such as all the rows within this range satisfy the seek predicate, and all the rows outside of that range don't. Seek predicates are usually predicates on the leftmost columns of the key of an index.
  • The residual predicate, such as the search predicate is the conjunction of the seek predicate and the residual predicate. The residual predicate is optional.
source

Index Scan retrieves all the rows from the table. Index Seek retrieves selective rows from the table.

SEEK is better then SCAN

But there are few scenarios where SCAN operator perform better then SEEK specially when large number of rows are expected to return by operation.

sample

No comments: