Stored procedure tunning

783 views

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
783
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
43
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Stored procedure tunning

  1. 1. Working withStored Procedure Free Powerpoint Templates @Virendra Yaduvanshi 1
  2. 2. SELECT statements - Try to use only the required number ofcolumns in the SELECT clause instead of using *. Using *returns all columns, which unnecessarily create a fatrecordset.Don’t use the * when selecting dataSELECT * FROM dbo.MyTableExplicitly name each column you want to be returned in yourSELECT statementSELECT Name, Description, DateEntered FROM dbo.MyTableThis allows you to add new columns to your table withoutbreaking your code Minimizes network traffic by only returnsthe columns you need. Free Powerpoint Templates @Virendra Yaduvanshi 2
  3. 3. SQL-92 - Always try to use ANSI 92 syntax. Till now theold syntax is working the old syntax will be deprecatedin the next release of MS SQL server.As an example, for joining, useSELECT * FROM employee e1INNER JOIN employee _dtl e2ON e1.id = e2.idInstead ofSELECT * FROM employee e1, employee_dtl e2WHERE e1.id = e2.id Free Powerpoint Templates @Virendra Yaduvanshi 3
  4. 4. CREATE TABLE vs. SELECT INTO - Select * INTO worksfine for small tables, but when dealing with large record sets orlong-running queries, it creates locks on the system objectswithin the tempdb database. As a result, other queries andprocedures that need to create objects within the tempdbdatabase will have to wait for the long-running query tocomplete. This is because when an object is created, anexclusive lock is taken against thesysobjects, syscolumns, sysindexes tables.Update: This problem has been greatly reduced from the MSSQL 7.0.Also, SELECT INTO not only copies data but also it copiesthe table structure, hence it performs slower. Free Powerpoint Templates @Virendra Yaduvanshi 4
  5. 5. Try to use table variables instead of Temporary Tables -Temp tables can cause stored procedures to recompile. (FromSQL 2005, using temporary table not always causingrecompilations. But adding rows to temporary tables maycause recompilations). But table variables were designedspecifically to guard against stored procedure recompilesduring execution.If the result set is not containing a huge number of recordsthen you should stick to table variable, otherwise temp tablehas its advantages. There is a misconception that temp tablesalways use the tembdb database but table variable do not.Table variables also use tempdb after a certain size Free Powerpoint Templates @Virendra Yaduvanshi 5
  6. 6. Use proper indexes - You can use the help of the datatuning advisor, but it does not gives the proper result allthe time. Index scans and index seeks are much fasterthan table scans. So identify the table scans from theexecution plans. But when a table returns smallernumber rows, then it is better to use a table scan. Free Powerpoint Templates @Virendra Yaduvanshi 6
  7. 7. Subquery vs JOINs - This is a famous debate in manyonline forums. In fact most sub queries can be expressedas an equivalent form of JOIN. I have a good rule ofthumb: subquery is faster when we have to retrieve datafrom large number of tables because it becomes tediousto join more tables. JOIN is faster to retrieve data fromdatabase when we have less number of tables. But try toavoid correlated sub queries because it makes the querymuch slower. Free Powerpoint Templates @Virendra Yaduvanshi 7
  8. 8. Avoid using cursors - Using cursors make the programslower as it works against SET based SQL. Try to usetemporary table/table variables with identity column andthen iterate all the tables using WHILE loop and a loopingcounter, which will map with the identity column. Free Powerpoint Templates @Virendra Yaduvanshi 8
  9. 9. Avoid DISTINCT and ORDER BY - If you dont need theDISTINCT/ORDER BY clause, then try to avoid so.Unnecessary DISTINCT or ORDER BY clauses cause extrawork for the database engine. Hence making performanceslower. (Sometimes ORDER BY helps to speed up theoperation). Free Powerpoint Templates @Virendra Yaduvanshi 9
  10. 10. CAST and CONVERT - Try to use CAST instead ofCONVERT. CAST is ANSI-92 standard but CONVERT worksin MS SQL server only. Also, some CONVERT styles may bedeprecated in future MS SQL releases. It is better to useCONVERT only when you need to format the DATETIMEdatatype with the style option. CAST cannot do this. Free Powerpoint Templates @Virendra Yaduvanshi 10
  11. 11. More WHERE clause hints - Avoid unnecessaryconditions in the WHERE Clause. Also try to avoid afunction in the WHERE clause as it presents SQLengine to do index seek. Even it forces SQL full indexscans or even table scans.Also, try to avoid IN. While checking the existence ofsome values, then use EXISTS instead of IN. IN countsthe NULL values also, but EXISTS not. EXISTS returnsBoolean(Yes/No) but IN returns all values hence resultset for IN is heavier than EXISTS.Here, teacher and student table has 1:M relationshipand I want to find the teachers who have students. Boththe queries have the same result but the second querywill run faster because of EXISTS operator.SELECT name FROM teacherWHERE teacher_id IN (SELECT teacher_id FROM student)SELECT nameFROM teacher WHERE EXISTS (SELECT 1 FROM student whereteacher.teacher_id = student.teacher_id) Free Powerpoint Templates @Virendra Yaduvanshi 11
  12. 12. Capturing Both @@ROWCOUNT and @@ERROR After an UPDATE Statementdeclare @rowcnt int,@error intUPDATE dbo.titles set price = price * 1.10where type = fictionselect @rowcnt = @@ROWCOUNT, @error = @@ERRORif @rowcnt = 0print no rows updatedif @error <> 0raiserror (Update of titles failed, 16, 1)return Free Powerpoint Templates @Virendra Yaduvanshi 12
  13. 13. Variables - Use as few as possiblevariables. It frees spaces in cache. Free Powerpoint Templates @Virendra Yaduvanshi 13
  14. 14. Dynamic Queries - Try to minimize the usage ofdynamic queries. If you are using a dynamic query like:SELECT * FROM mydb.dbo.emp where empid = @eidthen there is no problem. You can supply a value forthe @eid parameter and there is no recompilation of theexecution plan in the database cache. But if you areusing a SQL query likeSELECT * FROM emp where empid = " + @eid andsupply a parameter (say 100), then the cache will keepthe execution plan for the value of 100 only. If the idchanges (to say 101), it will recompile the statement.Hence, this approach is slower than the previous one.(You can get the exact value of the SQL statement fromProfiler) Free Powerpoint Templates @Virendra Yaduvanshi 14
  15. 15. Fully Qualified Names - Always use the fully qualifiedname when calling stored procedures. This would bethe format database_name.schema_name.table_name.For example, use EXEC master.dbo.Your_Proc_nameinstead of EXEC Your_Proc_name This is a verycommon mistake, which causes an extra trip to theprocedure cache to get the execution plan forexecution. Also try to use the schema name whilecreating a procedure. Like: CREATE PROCEDUREdbo.Your_Proc_name instead of CREATE PROCEDUREYour_Proc_name Free Powerpoint Templates @Virendra Yaduvanshi 15
  16. 16. SET NOCOUNT ON - This suppresses the message thatshows number of rows affected by SQL statement.Otherwise this can cause extra network traffic and canhave some serious impact on performance when theprocedure is called frequently.Its recommend to use SET NOCOUNT ON for the shakeof performance unless there is a very good reason forusing it. Free Powerpoint Templates @Virendra Yaduvanshi 16
  17. 17. Naming ProcsDo NOT use sp_xxx as a naming convention.Causes additional searches and added I/O.  SQL Server will scan the procedure cache for Master, no matter what database the procedure was executed from  SQL Server will then acquire an exclusive COMPILE lock to perform a second search in the local database  If a user stored procedure has same name as an sp_xxx stored procedure in MASTER, then the user procedure will NEVER be used. Free Powerpoint Templates @Virendra Yaduvanshi 17
  18. 18. The sp_ prefix - Dont use the "sp_" prefix in a storedprocedure name as the "sp_" prefix is reserved forsystem stored procedures. Any stored procedure thathas the "sp_" prefix will cause an extra lookup in theMASTER database If a stored procedure uses samename in both the user database and a systemdatabase, the stored procedure in the user database willexecute but first it will find the procedure in resourcedatabase and then the user database (for SQL server2005/2008/2012) hence causing an extra burden to theserver. Free Powerpoint Templates @Virendra Yaduvanshi 18
  19. 19. sp_executeSQL and the KEEPFIXED PLAN options- Both sp_executesql andthe KEEPFIXED PLAN option avoid the recompilation of a stored procedure. Ifyou want to provide parameterized dynamic SQL, then go for sp_executesqlinstead of EXEC(proc_name). Here the execution plan for the procedure isstored with the variable name in cache memory. When the variable valuesare supplied, then the values are simply mapped to the query, hence noneed for a recompilation.Update: Keep in mind that recompilations are not always bad. Sometimes,using an old and inefficient plan can make the procedure more slower.Use the OPTION KEEPFIXED PLAN hint while selecting records fromtemporary tables. If the query contains this hint, then its plan is notrecompiledCREATE PROCEDURE my_procASCREATE TABLE #t (a int )SELECT * FROM #tINSERT #t SELECT * from retestSELECT COUNT(*) FROM #t WHERE a = 37OPTION (KEEPFIXED PLAN)As an example of sp_executesql, we can write:sp_executesql NSELECT * FROM mydb.dbo.emp where empid = @eid,N@eid int, @eid=40 Free Powerpoint Templates @Virendra Yaduvanshi 19
  20. 20. Calling ProcsUse stored procedure calls rather than embedded SQLEXEC versus SP_EXECUTESQL  same behavior with regard to batches, the scope of names, and database context  EXEC compiles entire SQL at one time  SP_EXECUTE compiles and executes as an execution plan separate from the execution plan of the batch that called sp_executesql itself.  SP_EXECUTESQL executes a Transact-SQL statement or batch that can be reused many times, or that has been built dynamically, using a single execution plan.  Often better than EXEC. Free Powerpoint Templates @Virendra Yaduvanshi 20
  21. 21. SELECT vs SET - A single SELECT statementcan assign values to different variables and ismuch faster than multiple SET statementsassigning values to multiple different variables.SELECT @Var1 = @Var1 + 1, @Var2 = @Var2 – 1instead ofSET @Var1 = @Var1 + 1SET @Var2 = @Var2 - 1 Free Powerpoint Templates @Virendra Yaduvanshi 21
  22. 22. WHERE clauses - In a WHERE clause, the variousoperators used directly affect how fast a query canrun. Here are the conditional operators used in theWHERE clause, ordered by their precedence.=, >, <, >=, <=, <>, !=, !>, !< Free Powerpoint Templates @Virendra Yaduvanshi 22
  23. 23. Include Column List in INSERT StatementExplicitly name the columns you are going to insertwith your INSERT statement  Do This INSERT INTO A (COLA, COLB) VALUE(‘A’, ’B’);  Don’t do this INSERT INTO A VALUE(‘A’, ’B’)This allows you change the format of your table byadding or removing columns without breaking yourINSERT statement. Free Powerpoint Templates @Virendra Yaduvanshi 23
  24. 24. Avoid using wildcard at the beginning of your search criteria …WHERE LastName LIKE ‘%sen’Doing this causes an index scanPlace a prefix in front of wildcard to SQL can use index seek tofind the records for your search criteria: …WHERE LastName LIKE ‘L%sen’.Might consider implementing full text search if you doing lots ofstring searching Free Powerpoint Templates @Virendra Yaduvanshi 24
  25. 25. Scalar Function Calls in Column List and WHERE clause Don’t execute scalar function in column list in a SELECT statement or WHERE clause, if the scalar value function returns data Doing this causes cursor like performance Function will be called for ever row returned Replace scalar function with:  JOIN logic  inline table value function  view Free Powerpoint Templates @Virendra Yaduvanshi 25
  26. 26. Referencing Column Names in Function Calls Within WHERE Clause Don’t use column names within a function call SELECT * FROM MyTable WHERE DATEADD(DAY,15,MyDate) = ‘05/01/2009’ Column that are used in functions are seen as expressions instead of columns, therefore indexes can not be used Doing this causes SQL Server to do an index scan or table scan Instead move the column name outside the function call if possible SELECT * FROM MyTable WHERE MyDate = DATEADD(DAY,-15,’05/1/2009’) Free Powerpoint Templates @Virendra Yaduvanshi 26
  27. 27. TransactionsAvoid nested transactions. They aren’t truly nested:  COMMIT only saves data from the outermost transaction  ROLLBACK nukes ALL transactions, both innermost and outermostOrphaned Transactions  Errors don’t usually abort a transaction except for deadlocks  Returning from a procedure or batch does NOT commit a transaction. Once a transaction is started, it remains open until:  The transaction is committed  The transaction is rolled back  The connection endsUse @@TRANCOUNT orsys.dm_tran_active_transactions to look fororphaned transactions when entering a new routineKeep transactions as short as possible!Keep transactions explicit!Remember lock escalation! Free Powerpoint Templates @Virendra Yaduvanshi 27
  28. 28. DDL/DML in Stored ProcedureMixing DDL and DML operations causes a recompileCertain operations on temporary tables cause a recompile  Refer to temp tables created locally  Don’t declare cursors that reference a temp table  Don’t create temp tables while in a loop Free Powerpoint Templates @Virendra Yaduvanshi 28
  29. 29. Interleaving DML/DDL StatementsObjects that donts exist at procedure first execution cannotbe optimized until statement execution.Upon execution of a DDL statement the procedure getsrecompiled to recompile the plans for the DML.Dont interleave DDL and DML, Seperate it.All DDL at the beginning of the proc, All DML later.Try not to create tables conditionally ( IF create ... ELSEcreate ...)Use KEEP PLAN on SELECT statement id Data changesmore than 6 times but the plan should not change. Free Powerpoint Templates @Virendra Yaduvanshi 29
  30. 30. Queries with LIKEQueries on production systems should NOT useSELECT * FROM…  Main reason is that any time the underlying table is changed, all query plans stored in the cache must be rebuilt  The SQL tools allow very quick scripting – so no excuses!Queries that use the LIKE clause have two simple rules:  LIKE can use indexes if the pattern starts with a character string, such as WHERE lname LIKE ‘w%’  LIKE cannot use an index if the pattern starts with a leading wildcard, such as WHERE lname LIKE ‘%alton’ Free Powerpoint Templates @Virendra Yaduvanshi 30
  31. 31. Queries with Functions & Calculations in the WHERE clauseAvoid using functions or calculations on the columnin a WHERE clause because it causes SQL Serverto ignore any index on the column:  WHERE qty * 12 > 10000  WHERE ISNULL(ord_date, ‘Jan 01,2001’) > ‘Jan 01, 2002 12:00:00 AM’Instead, move the function or calculation to the SARG:  WHERE qty > 10000/12  WHERE ord_date IS NOT NULL AND ord_date > ‘Jan 01, 2002 12:00:00 AM’ Free Powerpoint Templates @Virendra Yaduvanshi 31
  32. 32. Modifying ProceduresDROP and RECREATE  Loses the dependency chain stored in sysdepends  Loses the permissions already granted  Invalidates all plansALTER PROC  Loses the dependency chain stored in sysdepends  Retains the permissions  Invalidates all plansTo retain the dependency chain you must also ALTER all procedures that depend on the procedure being altered. Free Powerpoint Templates @Virendra Yaduvanshi 32
  33. 33. Temp Table Usage Temp Table can create excessive recompilations for procedures. Consider creating permanent tables (with indexes) and manipulating data there. Consider dropping and re-creating or rebuilding indexes as part of the procedure instead! Try not to create tables conditionally (IF create… ELSE create…) Use Profiler to see if there are significant recompiles Use KEEP PLAN on SELECT statements if data changes more than 6 times but the plan should not change Free Powerpoint Templates @Virendra Yaduvanshi 33
  34. 34. Table Variable UsageScope is limited to the local proceduretransactionDoes not cause excessive recompiles due to local only access  No re-resolution on CREATE/ALTER  Temp Tables need re-resolution for nested proceduresOnly Key Indexes can be created  Definition of Table allows PRIMARY KEY/UNIQUE constraint indexes  Use TEMP TABLES if large volumes of data will be manipulated – create the right indexes for accessPopulation  Does not support INSERT EXEC  Does not support SELECT INTO Free Powerpoint Templates @Virendra Yaduvanshi 34
  35. 35. Community Resources John Theron - Quest Software Patrick OKeeffe - Quest Software Arup Chakraborty - SQLServerCentral.com Victor Isakov Kimberly L. Tripp,Solid Quality Learning – SolidQualityLearning.com /SYSolutions, Inc. – SQLSkills.com Free Powerpoint Templates @Virendra Yaduvanshi 35
  36. 36. Thank You ! Virendra Yaduvanshi http://wikidba.wordpress.com/ Email : yaduvanshi.v@gmail.com Free Powerpoint Templates @Virendra Yaduvanshi 36

×