Stored Procedure Optimization Preventing SP Time Out Delay Deadlocking More DiskReads By: Nix.

Slides:



Advertisements
Similar presentations
SQL Server performance tuning basics
Advertisements

Transact-SQL. 1. Declare float = 10 select * from customers where discnt
AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
SQL Performance 2011/12 Joe Chang, SolidQ
EXECUTION PLANS By Nimesh Shah, Amit Bhawnani. Outline  What is execution plan  How are execution plans created  How to get an execution plan  Graphical.
SQL Constraints and Triggers
Query Evaluation. An SQL query and its RA equiv. Employees (sin INT, ename VARCHAR(20), rating INT, age REAL) Maintenances (sin INT, planeId INT, day.
DAY 21: MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Akhila Kondai October 30, 2013.
Convergence /20/2017 © 2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, and other product names are or may be registered trademarks.
Introduction to Databases Chapter 8: Improving Data Access.
Module 12 Handling Errors in T-SQL Code. Module Overview Understanding T-SQL Error Handling Implementing T-SQL Error Handling Implementing Structured.
Mr. Justin “JET” Turner CSCI 3000 – Fall 2015 CRN Section A – TR 9:30-10:45 CRN – Section B – TR 5:30-6:45.
Physical Database Design & Performance. Optimizing for Query Performance For DBs with high retrieval traffic as compared to maintenance traffic, optimizing.
Module 7 Reading SQL Server® 2008 R2 Execution Plans.
Stored Procedures, Transactions, and Error-Handling
Module 9 Designing and Implementing Stored Procedures.
Ashwani Roy Understanding Graphical Execution Plans Level 200.
1 Definition of a subquery Nested subqueries Correlated subqueries The ISNULL function Derived tables The EXISTS operator Mixing data types: CAST & CONVERT.
Copyright © Curt Hill Stored Procedures In Transact-SQL.
Views Lesson 7.
M1G Introduction to Database Development 5. Doing more with queries.
By Shanna Epstein IS 257 September 16, Cnet.com Provides information, tools, and advice to help customers decide what to buy and how to get the.
1 Chapter 10 Joins and Subqueries. 2 Joins & Subqueries Joins – Methods to combine data from multiple tables – Optimizer information can be limited based.
06 | Modifying Data in SQL Server Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
SQL/Lesson 7/Slide 1 of 32 Implementing Indexes Objectives In this lesson, you will learn to: * Create a clustered index * Create a nonclustered index.
Dynamic SQL. 2 home back first prev next last What Will I Learn? Recall the stages through which all SQL statements pass Describe the reasons for using.
Retrieving Data in PL/SQL. 2 home back first prev next last What Will I Learn? In this lesson, you will learn to: –Recognize the SQL statements that can.
Connect with life Nauzad Kapadia Quartz Systems
Learningcomputer.com SQL Server 2008 –Views, Functions and Stored Procedures.
DAT410 SQL Server 2005 Optimizing Procedural Code Kimberly L. Tripp President/Founder, SQLskills.com.
Creating Indexes on Tables An index provides quick access to data in a table, based on the values in specified columns. A table can have more than one.
SQL Server 2012 Session: 1 Session: 12 Triggers Data Management Using Microsoft SQL Server.
Meta Data Cardinality Explored CSSQLUG User Group - June 2009.
Stored Procedures / Session 4/ 1 of 41 Session 4 Module 7: Introducing stored procedures Module 8: More about stored procedures.
IMS 4212: Application Architecture and Intro to Stored Procedures 1 Dr. Lawrence West, Management Dept., University of Central Florida
IMS 4212: Constraints & Triggers 1 Dr. Lawrence West, Management Dept., University of Central Florida Stored Procedures in SQL Server.
Thinking in Sets and SQL Query Logical Processing.
Database Systems, 8 th Edition SQL Performance Tuning Evaluated from client perspective –Most current relational DBMSs perform automatic query optimization.
1 11g NEW FEATURES ByVIJAY. 2 AGENDA  RESULT CACHE  INVISIBLE INDEXES  READ ONLY TABLES  DDL WAIT OPTION  ADDING COLUMN TO A TABLE WITH DEFAULT VALUE.
MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Sravanthi Lakkimsety Mar 14,2016.
SQL Triggers, Functions & Stored Procedures Programming Operations.
Execution Plans Detail From Zero to Hero İsmail Adar.

Dynamic SQL Writing Efficient Queries on the Fly ED POLLACK AUTOTASK CORPORATION DATABASE OPTIMIZATION ENGINEER.
Diving into Query Execution Plans ED POLLACK AUTOTASK CORPORATION DATABASE OPTIMIZATION ENGINEER.
Views / Session 3/ 1 of 40 Session 3 Module 5: Implementing Views Module 6: Managing Views.
SQL Server Statistics and its relationship with Query Optimizer
Trigger used in PosgreSQL
COMP 430 Intro. to Database Systems
Parameter Sniffing in SQL Server Stored Procedures
Tuning Transact-SQL Queries
Query Optimization Techniques
Dynamic SQL Writing Efficient Queries on the Fly
Stored Procedures.
Chapter 6 - Database Implementation and Use
Stored Procedures – Facts and Myths
PROCEDURES, CONDITIONAL LOGIC, EXCEPTION HANDLING, TRIGGERS
Parameter Sniffing in SQL Server Stored Procedures
Dynamic SQL Writing Efficient Queries on the Fly
Database Construction (and Usage)
Error Handling Summary of the next few pages: Error Handling Cursors.
Query Optimization Techniques
Top Tips for Better TSQL Stored Procedures
Transact SQL Performance Tips
Statistics for beginners – In-Memory OLTP
Diving into Query Execution Plans
SQL Server Query Design and Optimization Recommendations
A – Pre Join Indexes.
Query Optimization Techniques
Responding to Data Manipulation Via Triggers
Presentation transcript:

Stored Procedure Optimization Preventing SP Time Out Delay Deadlocking More DiskReads By: Nix

CREATE PROCEDURE [dbo].[pr_get_user_ids] int ) As begin int Select UserId from UserDetail where end Parameter Sniffing This is the most common problem, The workaround is to declare the input params again with different variable name and use the new variable through out the SP. In the In short, parameter sniffing is one exec plan for all parameter combinations. - This option causes the compilation process to ignore the value for the specified variable and use the specified value instead. - Unlike the other workaround (Option(Recompile)), this option avoid the overhead of recompiling the query every time.

Use Local Temp Tables Store the data from large tables such as Product / Customer/ ProductHierarchy into Local temp Tables and Use them when joining – This is will Prevent the joining of heavy tables. SELECT * into #TempProductHierarchy FROM (SELECT ProductHierarchy,ProductHierarchyId,ProductId from ProductHierarchyDetails where ) AS TPH SELECT ProductCodeInterface from masters.Product P inner join #tempProductHierarchy on P.ProductId=#TempProductHierarchy.ProductId Instead of SELECT ProductCodeInterface from masters.Product P inner join masters.ProductHierarchyDetail PHD on P.ProductId=PHD.ProductId where Select only the needed columns for your Transaction operation and put it into a local temp table. Hence on performing joins the tables will be lighter and preventing the use of excess Resource. In the Example We have filtered out few columns from ProductHierarchy table using setupid in where clause and used it to join with Product table. This is Subject to temp Db Size. Consider the temp Db size.

SELECT * into #TempProductHierarchy FROM (SELECT ProductHierarchy,ProductHierarchyId,ProductId from ProductHierarchyDetails where ) AS TPH Create NonClustered Index IDX_TP4 On #TempProductHierarchy(ProductId) Use NON Clustered Index Use Non Clustered Index on temp tables for quicker Execution Once you have created a temp table, set index on the primary key of the table – on which you will be performing the join operation. In the example we have read the Product Hierarchy table into a temp table and we have created a non- clustered index onto the primary key i.e ProductId

Select * from ProductHierarchy WITH(NOLOCK) Use With(NOLOCK) NOLOCK typically (depending on your DB engine) means give me your data, and I don't care what state it is in, and don't bother holding it still while you read from it. It is all at once faster, less resource-intensive Use NOLOCK on master tables and not everywhere. Using NoLock may become dangerous sometimes, so check the query exec plan when in doubt.

Instead Of SELECT * from trans.Promotion P inner join masters.Product PP with(NOLOCK) on PP.SetupId=P.SetupId inner join masters.Customer CC with(NOLOCK) on CC.SetupId=P.SetupId Where SELECT * from trans.Promotion P inner join masters.Product PP with(NOLOCK) on inner join masters.Customer CC with(NOLOCK) on Join On the InputParameter This will reduce the operation size and the disk read Join on input parameter instead of filtering in where condition. As you can see here we have joined on setupid i.e the input parameter instead of joining on the setupid of the other table and then filtering in where condition.

Dont use "SELECT *" in a SQL query Prevent the use of “Select *” Causes Indexing issues and Binding issues

SELECT PromotionId,AmendVersion FROM trans.Promotion WHERE EXISTS (SELECT top 1 PromotionId FROM trans.PromotionExtract WHERE Promotion.SetupId=1099) Use EXISTS To check if any data exists in a particular table, use EXISTS instead of relying on Count its more effective.

SELECT * into #TempProduct FROM(SELECT ProductId,LevelId,ProductCodeInterface,Name from Product where and IsActive=1) AS TP Use Local Temp Tables (#TempTableName) Prevent using Global hash tables (##)

varchar(max) = 'nevermind the promotions' int Use Local Variables to Store the FunctionCall return Prevent calling the string functions or date functions Over and over again, instead store ‘em in local variables if you are going to reuse the value.

BEGIN TRY -- Logic / Query here END TRY BEGIN CATCH VARCHAR(255) -- Error INT -- Error INT -- Error VARCHAR(255) -- Error INT -- Error Line = = = = = ERROR_LINE() RAISERROR ( ) END CATCH END Use Try - Catch

SET NOCOUNT ON Select PromotionId from Promotion Use SET NOCOUNT ON Whenever we write any procedure and execute it a message appears in message window that shows number of rows affected with the statement written in the procedure. When SET NOCOUNT is ON, the count is not returned.

Do not try to use DDL statements inside a stored procedure that will reduces the chance to reuse the execution plan. DDL statements like CREATE,ALTER,DROP,TRUNCATE etc. Prevent Usage of DDL Statements

Use Alias --Wrong Statement SELECT PromotionId, P.VersionedPromotionId, Name, PIE.InvestmentTypeId from Promotion P Inner join PromotionInvestment PIE on PIE.VersionedPromotionId=P.VersionedPromotionId where P.Name='Blah' --Correct Statement SELECT P.PromotionId, P.VersionedPromotionId, P.Name, PIE.InvestmentTypeId from Promotion P Inner join PromotionInvestment PIE on PIE.VersionedPromotionId=P.VersionedPromotionId where P.Name='Blah' If an alias is not present, the engine must resolve which tables own the specified columns. A short alias is parsed more quickly than a long table name or alias. If possible, reduce the alias to a single letter

Don't use UPDATE instead of CASE Take this scenario, for instance: You're inserting data into a temp table and need it to display a certain value if another value exists. Maybe you're pulling from the Customer table and you want anyone with more than $100,000 in orders to be labeled as "Preferred." Thus, you insert the data into the table and run an UPDATE statement to set the CustomerRank column to "Preferred" for anyone who has more than $100,000 in orders. The problem is that the UPDATE statement is logged, which means it has to write twice for every single write to the table. The way around this, of course, is to use an inline CASE statement in the SQL query itself. This tests every row for the order amount condition and sets the "Preferred" label before it's written to the table.

Avoid Functions on RHS Don’t use thisselect * from Promotion where YEAR(StartDate) = 2015 and MONTH(StartDate) = 6 Instead use thisSelect * From Promotion Where StartDate between '6/1/2015' and '6/30/2015'

Specify optimizer hints in SELECT most cases the query optimizer will pick the appropriate index for a particular table based on statistics, sometimes it is better to specify the index name in your SELECT query. Do not use this unless you know what you are doing. SELECT * FROM Promotion WITH ( Index(IdxPromotionId)) WHERE Name = 'blah' and Setupid=1099