70-466 · Question #28
You execute the following code: CREATE TABLE dbo.Customers ( id int PRIMARY KEY, CustomerName char(10) ) You create a nonclustered index named IX_CustomerName on the CustomerName column. You execute t
The correct answer is A. Replace LEFT(CustomerName,1) = 'a' with CustomerName LIKE 'a%'.. Wrapping a column in a function like LEFT() prevents the query optimizer from using an index seek (non-sargable predicate). Rewriting the predicate as a LIKE with a trailing wildcard makes it sargable, enabling the nonclustered index on CustomerName to be used.
Question
Exhibit
Options
- AReplace LEFT(CustomerName,1) = 'a' with CustomerName LIKE 'a%'.
- BPartition the table and use the CustomerName column for the partition scheme.
- CReplace LEFT(CustomerName,1) = 'a' with SUBSTRING(CustomerName,1,1) = 'a'.
- DReplace IX_CustomerName with a clustered index.
How the community answered
(30 responses)- A90% (27)
- B7% (2)
- D3% (1)
Why each option
Wrapping a column in a function like LEFT() prevents the query optimizer from using an index seek (non-sargable predicate). Rewriting the predicate as a LIKE with a trailing wildcard makes it sargable, enabling the nonclustered index on CustomerName to be used.
Using LIKE 'a%' is a sargable predicate because SQL Server can perform an index seek on the leading characters of the CustomerName column using the existing nonclustered index IX_CustomerName. The LEFT() function wraps the column and forces a full scan, but LIKE with a trailing wildcard allows the optimizer to scan only the relevant range of index entries, directly reducing query execution time.
Partitioning the table on CustomerName adds management overhead and does not make the predicate sargable, so the index still cannot be used for an efficient seek.
SUBSTRING() is also a scalar function applied to the column, making the predicate non-sargable just like LEFT(), so the optimizer cannot use the index for a seek.
Replacing the nonclustered index with a clustered index changes physical storage order but does not make the LEFT() predicate sargable; the query would still cause a full index scan.
Concept tested: Sargable predicates and nonclustered index seeks
Source: https://learn.microsoft.com/en-us/sql/relational-databases/query-processing-architecture-guide
Topics
Community Discussion
No community discussion yet for this question.
