Query OptimizerThe query optimizer in SQL Server is cost-based. It includes:1. Cost for using different resources (CPU and IO)2. Total execution timeIt determines the cost by using:• Cardinality: The total number of rows processed at each level of a query plan with the help of histograms , predicates and constraint• Cost model of the algorithm: To perform various operations like sorting, searching, comparisons etc.
Statistics Analysis• The query optimizer uses statistics to create query plans that improve query performance• A correct statistics will lead to high-quality query plan.• The query optimizer determines when statistics might be out- of-date by counting the number of data modifications since the last statistics update and comparing the number of modifications to a threshold.
Auto create statistics• Default setting of auto create statistics is ON.• It creates when:• Clustered and non clustered Index is created• Select query is executed.• Auto create and updates applies strictly to single-column statistics.
Why query 2 is performing better• If we perform following operations on field of any table in query predicate:1. Using any system function or user defined function2. Scalar operation like addition, multiplication etc.3. Type casting• In this situation sql server query optimizer is not able to estimate correct cardinality using statistics.
To improve cardinality• If possible, simplify expressions with constants in them.• If possible, dont perform any operation on the any field of a table in WHERE Clause, ON Clause, HAVING Clause• Dont use local variables in WHERE Clause, ON Clause, HAVING Clause.• If there is any cross relationship among fields or there is a complex expression in a field in a query predicates, it is better to create a computed column and then create a non-clustered index on it.
To improve cardinality• If possible, dont update the value of parameters of a function or stored procedure before using in sql statement• Use OPTIMIZE FOR clause when you want to optimize a sql query on the basis of specific parameter value.• If you want to update the value parameter of a stored procedure or a function create a similar procedure or function and execute it form base procedure or function by passing the updated value as a parameter.• Create user defined multi column statistics if query predicates have more than one fields of a table.