0% found this document useful (0 votes)
20 views6 pages

SQL Query Optimization Examples

The document contains a series of SQL examples demonstrating various operations such as selecting data, creating indexes, and optimizing queries within the AdventureWorks and sample databases. It includes examples of high and low selectivity queries, the use of statistics, and the application of query hints. Additionally, it showcases the creation of plan guides and the use of different join types in SQL queries.

Uploaded by

riyasathsafran
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views6 pages

SQL Query Optimization Examples

The document contains a series of SQL examples demonstrating various operations such as selecting data, creating indexes, and optimizing queries within the AdventureWorks and sample databases. It includes examples of high and low selectivity queries, the use of statistics, and the application of query hints. Additionally, it showcases the creation of plan guides and the use of different join types in SQL queries.

Uploaded by

riyasathsafran
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Example 19.

1
SET SHOWPLAN_TEXT ON;

GO

USE AdventureWorks;

SELECT * FROM [Link] e JOIN [Link] a

ON [Link] = [Link]

AND [Link] = 10;

GO

SET SHOWPLAN_TEXT OFF;

Example 19.2
USE sample;
SELECT * into new_addresses
FROM [Link];
GO
CREATE INDEX i_stateprov on new_addresses(StateProvinceID);

Example 19.3
-- high selectivity
USE sample;
SELECT * FROM new_addresses a
WHERE [Link] = 32;

Example 19.4
-- low selectivity

USE sample;

SELECT * FROM new_addresses a

WHERE [Link] = 9;
Example 19.5
USE AdventureWorks;

SELECT * FROM [Link]

WHERE [Link] = 10;

Example 19.6
USE AdventureWorks;

SELECT * FROM [Link] e JOIN

[Link] a

ON [Link] = [Link]

AND [Link] = 10;

Example 19.7
USE AdventureWorks;

SELECT * FROM [Link] a JOIN [Link] s

ON [Link] = [Link];

Example 19.8
USE AdventureWorks;
CREATE INDEX i_unitprice
ON [Link](UnitPrice)
WHERE UnitPrice > 1000;
SELECT SalesOrderDetailID, UnitPrice
FROM [Link]
WHERE UnitPrice > 2000;

Example 19.9
USE master;

SELECT counter, occurrence, value


FROM sys.dm_exec_query_optimizer_info
WHERE value IS NOT NULL
AND counter LIKE 'search 1%';

Example 19.10
SELECT [Link] AS Object_Type ,

(SELECT t. text FROM sys.dm_exec_sql_text(qs.sql_handle) AS t) AS

Adhoc_Batch ,qs. execution_count AS Counts ,

qs. total_worker_time AS Total_Worker_Time ,

(qs.total_physical_reads / qs.execution_count ) AS Avg_Physical_Reads ,

(qs.total_logical_writes / qs.execution_count ) AS Avg_Logical_Writes ,

(qs.total_logical_reads / qs.execution_count ) AS Avg_Logical_Reads ,

qs.total_elapsed_time AS Total_Elapsed_Time,

(qs.total_elapsed_time / qs.execution_count ) AS Avg_Elapsed_Time ,

qs.last_execution_time AS Last_Exec_Time,

qs.creation_time AS Creation_Time

FROM sys.dm_exec_query_stats AS qs

JOIN sys.dm_exec_cached_plans ecp ON qs.plan_handle = ecp.plan_handle

ORDER BY Counts DESC;

Example 19.11

SELECT TOP 5 total_worker_time/execution_count AS [Avg CPU Time],

SUBSTRING([Link], (qs.statement_start_offset/2)+1,

((CASE qs.statement_end_offset
WHEN -1 THEN DATALENGTH([Link])

ELSE qs.statement_end_offset

END - qs.statement_start_offset)/2) + 1) AS statement_text

FROM sys.dm_exec_query_stats AS qs

CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st

ORDER BY total_worker_time/execution_count DESC;

Example 19.12

USE sample;
CREATE TABLE State
(State_ID int IDENTITY PRIMARY KEY,
State_name varchar(120) NOT NULL);
INSERT State (State_name)
VALUES ('Idaho'), ('Iowa'), ('Indiana'), ('Texas');
GO
CREATE STATISTICS State_Stats
ON State (State_Name) ;
GO
SELECT object_id,stats_id,range_high_key,range_rows,equal_rows
FROM sys.dm_db_stats_histogram(OBJECT_ID('State'), 2);

Example 19.13
USE sample;

SELECT * FROM new_addresses a WITH ( INDEX(i_stateprov))

WHERE [Link] = 9;
Example 19.14

SET SHOWPLAN_TEXT ON;


GO

USE AdventureWorks;
SELECT * FROM [Link] a
WITH(INDEX(0))
WHERE [Link] = 32;

GO
SET SHOWPLAN_TEXT OFF;

Example 19.15
USE AdventureWorks;

SELECT [Link], [Link], [Link]

FROM [Link] e, [Link] d,

[Link] h

WHERE [Link] = [Link]

AND [Link] = [Link] AND [Link] IS NOT NULL

OPTION(FORCE ORDER);

Example 19.16
USE AdventureWorks;

SELECT * FROM [Link] a JOIN [Link] s

ON [Link] = [Link] OPTION (MERGE JOIN);

Example 19.17
USE AdventureWorks;
SELECT * FROM [Link] a INNER MERGE JOIN [Link] s
ON [Link] = [Link];
Example 19.18
USE AdventureWorks;

DECLARE @city_name nvarchar(30)


SET @city_name = 'Newark'
SELECT * FROM [Link] WHERE City = @city_name
OPTION ( OPTIMIZE FOR (@city_name = 'Seattle') );

Example 19.19
sp_create_plan_guide @name = N'Example_19_15',
@stmt = N'SELECT * FROM [Link] a JOIN [Link] s
ON [Link] = [Link]',
@type = N'SQL',
@module_or_batch = NULL,
@params = NULL,
@hints = N'OPTION (HASH JOIN)'

Common questions

Powered by AI

Using options like 'MERGE JOIN' or 'HASH JOIN' can provide significant performance benefits when the conditions suit their characteristics. 'MERGE JOIN' is advantageous when both datasets are pre-sorted; it is efficient in terms of CPU and I/O if the join criteria lead to ordered data access. Conversely, 'HASH JOIN' is beneficial in dealing with large datasets with no sorting; it uses a hash table to manage data efficiently. However, disadvantages include increased memory usage in 'HASH JOIN,' which can lead to excessive swapping if memory limits are exceeded, and potential performance degradation in 'MERGE JOIN' if sorting is needed upfront .

High selectivity, where index keys have unique or near-unique values, generally leads to more efficient index use, allowing the optimizer to narrow down results quickly. This results in faster query performance as fewer rows need scanning. Conversely, low selectivity indexes cover non-unique or highly repetitive values, often leading to table scans instead of index seeks, making them less efficient for filtering large datasets. For example, Example 19.3 shows high selectivity with 'StateProvinceID = 32', which would effectively use indexed search, whereas Example 19.4 shows low selectivity with 'StateProvinceID = 9', likely resulting in less efficient query execution .

Specifying 'OPTION(FORCE ORDER)' can be necessary when the natural order of joins affects performance due to specific business logic or data structures. This option enforces the order of joins as specified in the query and can be used when the optimizer's heuristics do not align with the optimal sequence of joins for specific datasets, potentially improving performance or maintaining correctness in cases of nondeterministic plans .

A conditional CREATE INDEX command is beneficial in scenarios where a specific subset of data is queried frequently and needs faster access. For instance, creating an index on 'Sales.SalesOrderDetail(UnitPrice)' with 'UnitPrice > 1000' optimizes queries that retrieve orders where unit prices exceed 1000. The potential benefits include improved query performance for high-value transactions, reduction in resource consumption for unnecessary data scanning, and enhanced efficiency when dealing with large datasets .

To optimize CPU resource usage for SQL queries, several steps can be taken: 1) Identify high CPU-consuming queries using 'sys.dm_exec_query_stats' and order results by 'total_worker_time/execution_count'. 2) Analyze query execution plans with 'SET SHOWPLAN_TEXT' to determine inefficient operations. 3) Consider rewriting complex queries for simplicity and efficiency. 4) Ensure indexes are optimally used by creating or updating them based on query patterns. 5) Utilize query hints to enforce specific strategies when defaults prove suboptimal .

Tracking statistics and their distribution is significant for the SQL query optimizer to make informed decisions about the most efficient query execution plans. Statistical distribution provides insights into data patterns, allowing the optimizer to estimate result set sizes and choose appropriate access methods. The 'sys.dm_db_stats_histogram' function retrieves histogram data from statistics objects, detailing distribution of column values, which assists in understanding table data and optimizing queries appropriately .

The INDEX hint in a SELECT statement explicitly instructs the SQL Server query optimizer to use a specific index when executing the query. This can override the default behavior of the optimizer, which might not choose the best index due to outdated statistics or mis-estimation of the data distribution. By specifying an index, performance can be improved if the hint aligns with how the data is accessed. However, misuse or overuse can lead to suboptimal performance if the chosen index is not appropriate for current data states .

'sys.dm_exec_query_optimizer_info' plays a vital role in query analysis by providing details about the SQL Server query optimizer's performance, including the success and efficiency of optimization phases (e.g., search reattempts). By studying this metadata, administrators can identify trends in query compilation, spot inefficiencies, and adjust strategies to improve optimizer behavior, thus enhancing overall system efficiency and performance .

The 'SET SHOWPLAN_TEXT ON' command is used to display the execution plan of a query without actually executing it. This assists in query optimization by allowing database administrators and developers to analyze how a query will be executed by the SQL Server, including which indexes are utilized, the join order, and the operations performed on the data. By examining the execution plan, inefficiencies can be identified and resolved, leading to improved query performance .

Plan guides are crucial in SQL query optimization as they allow for the influence of optimizer behavior without altering the application code. They are particularly useful for complex queries where the default optimization logic does not yield the best performance. For example, a plan guide can specify join strategies or force the use of specific indexes. In Example 19.19, a plan guide is created to force the use of a 'HASH JOIN' on a query that joins 'Person.Address' and 'Person.StateProvince', potentially optimizing performance by using a hash-based method to handle the dataset efficiently .

You might also like