<p>When you have a query or stored procedure that needs performance tuning, what are some of the first things you try?</p>

[{'answer_id': 18792, 'author': 'Mike', 'author_id': 1573, 'author_profile': 'https://Stackoverflow.com/users/1573', 'pm_score': 2, 'selected': False, 'text': '<p>Look at the where clause - verify use of indexes / verify nothing silly is being done</p>\n\n<pre><code>where SomeComplicatedFunctionOf(table.Column) = @param --silly\n</code></pre>\n'}, {'answer_id': 18793, 'author': 'davidmytton', 'author_id': 2183, 'author_profile': 'https://Stackoverflow.com/users/2183', 'pm_score': 3, 'selected': False, 'text': '<p>Assuming MySQL here, use EXPLAIN to find out what is going on with the query, make sure that the indexes are being used as efficiently as possible and try to eliminate file sorts. <a href="http://www.amazon.co.uk/High-Performance-MySQL-Optimization-Replication/dp/0596101716/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1219265253&amp;sr=8-1" rel="noreferrer">High Performance MySQL: Optimization, Backups, Replication, and More</a> is a great book on this topic as is <a href="http://www.mysqlperformanceblog.com/" rel="noreferrer">MySQL Performance Blog</a>.</p>\n'}, {'answer_id': 18797, 'author': 'Seibar', 'author_id': 357, 'author_profile': 'https://Stackoverflow.com/users/357', 'pm_score': 2, 'selected': False, 'text': '<p>@<a href="https://stackoverflow.com/questions/18783/sql-what-are-your-favorite-performance-tricks#18793">DavidM</a></p>\n\n<blockquote>\n  <p>Assuming MySQL here, use EXPLAIN to find out what is going on with the query, make sure that the indexes are being used as efficiently as possible...</p>\n</blockquote>\n\n<p>In SQL Server, execution plan gets you the same thing - it tells you what indexes are being hit, etc.</p>\n'}, {'answer_id': 18800, 'author': 'John Christensen', 'author_id': 1194, 'author_profile': 'https://Stackoverflow.com/users/1194', 'pm_score': 2, 'selected': False, 'text': "<p>I'll generally start with the joins - I'll knock each one of them out of the query one at a time and re-run the query to get an idea if there's a particular join I'm having a problem with.</p>\n"}, {'answer_id': 18802, 'author': 'csmba', 'author_id': 350, 'author_profile': 'https://Stackoverflow.com/users/350', 'pm_score': 1, 'selected': False, 'text': '<p>Index the table(s) by the clm(s) you filter by</p>\n'}, {'answer_id': 18812, 'author': 'Ryan', 'author_id': 1545, 'author_profile': 'https://Stackoverflow.com/users/1545', 'pm_score': 2, 'selected': False, 'text': '<p>Sometimes in SQL Server if you use an OR in a where clause it will really jack with performance. Instead of using the OR just do two selects and union them together. You get the same results at 1000x the speed.</p>\n'}, {'answer_id': 18815, 'author': 'Andy', 'author_id': 1993, 'author_profile': 'https://Stackoverflow.com/users/1993', 'pm_score': 2, 'selected': False, 'text': "<p>Not necessarily a SQL performance trick per se but definately related: </p>\n\n<p>A good idea would be to use memcached where possible as it would be much faster just fetching the precompiled data directly from memory rather than getting it from the database. There's also a flavour of MySQL that got memcached built in (third party).</p>\n"}, {'answer_id': 18820, 'author': 'Stu', 'author_id': 414, 'author_profile': 'https://Stackoverflow.com/users/414', 'pm_score': 1, 'selected': False, 'text': '<ul>\n<li>Prefix all tables with dbo. to prevent recompilations.</li>\n<li>View query plans and hunt for table/index scans.</li>\n<li>In 2005, scour the management views for missing indexes.</li>\n</ul>\n'}, {'answer_id': 18822, 'author': 'Seibar', 'author_id': 357, 'author_profile': 'https://Stackoverflow.com/users/357', 'pm_score': 2, 'selected': False, 'text': '<p>On all of my temp tables, I like to add unique constraints (where appropriate) to make indexes, and primary keys (almost always).</p>\n\n<pre><code>declare @temp table(\n    RowID int not null identity(1,1) primary key,\n    SomeUniqueColumn varchar(25) not null,\n    SomeNotUniqueColumn varchar(50) null,\n    unique(SomeUniqueColumn)\n)\n</code></pre>\n'}, {'answer_id': 18824, 'author': 'Barrett Conrad', 'author_id': 1227, 'author_profile': 'https://Stackoverflow.com/users/1227', 'pm_score': 2, 'selected': False, 'text': "<p>Make sure your index lengths are as small as possible.  This allows the DB to read more keys at a time from the file system, thus speeding up your joins. I assume this works with all DB's, but I know it's a specific recommendation for MySQL. </p>\n"}, {'answer_id': 18835, 'author': 'Seibar', 'author_id': 357, 'author_profile': 'https://Stackoverflow.com/users/357', 'pm_score': 1, 'selected': False, 'text': '<p>I like to use</p>\n\n<pre><code>isnull(SomeColThatMayBeNull, \'\')\n</code></pre>\n\n<p>Over</p>\n\n<pre><code>coalesce(SomeColThatMayBeNull, \'\')\n</code></pre>\n\n<p>When I don\'t need the multiple argument support that coalesce gives you.</p>\n\n<p><a href="http://blog.falafel.com/2006/04/05/SQLServerArcanaISNULLVsCOALESCE.aspx" rel="nofollow noreferrer">http://blog.falafel.com/2006/04/05/SQLServerArcanaISNULLVsCOALESCE.aspx</a></p>\n'}, {'answer_id': 18845, 'author': 'Seibar', 'author_id': 357, 'author_profile': 'https://Stackoverflow.com/users/357', 'pm_score': 0, 'selected': False, 'text': '<p>Don\'t prefix Stored Procedure names with "sp_" because system procedures all start with "sp_", and SQL Server will have to search harder to find your procedure when it gets called.</p>\n'}, {'answer_id': 18865, 'author': 'jason saldo', 'author_id': 1293, 'author_profile': 'https://Stackoverflow.com/users/1293', 'pm_score': 4, 'selected': False, 'text': "<p>Slightly off topic but if you have control over these issues...<br/>\nHigh level and High Impact.</p>\n\n<ul>\n<li>For high IO environments make sure your disks are for either RAID 10 or RAID 0+1 or some nested implementation of raid 1 and raid 0. </li>\n<li>Don't use drives less than 1500K.</li>\n<li>Make sure your disks are only used for your Database.  IE no logging no OS.</li>\n<li>Turn off auto grow or similar feature.  Let the database use all storage that is anticipated. Not necessarily what is currently being used.</li>\n<li>design your schema and indexes for the type queries.</li>\n<li>if it's a log type table (insert only) and must be in the DB don't index it.</li>\n<li>if your doing allot of reporting (complex selects with many joins) then you should look at creating a data warehouse with a star or snowflake schema. </li>\n<li>Don't be afraid of replicating data in exchange for performance!</li>\n</ul>\n"}, {'answer_id': 18928, 'author': 'Mark Brackett', 'author_id': 2199, 'author_profile': 'https://Stackoverflow.com/users/2199', 'pm_score': 4, 'selected': False, 'text': "<ol>\n<li>Have a pretty good idea of the optimal path of running the query in your head.</li>\n<li>Check the query plan - always.</li>\n<li>Turn on STATS, so that you can examine both IO and CPU performance. Focus on driving those numbers down, not necessarily the query time (as that can be influenced by other activity, cache, etc.).</li>\n<li>Look for large numbers of rows coming into an operator, but small numbers coming out. Usually, an index would help by limiting the number of rows coming in (which saves disk reads).</li>\n<li>Focus on the largest cost subtree first. Changing that subtree can often change the entire query plan.</li>\n<li>Common problems I've seen are:\n\n<ul>\n<li>If there's a lot of joins, sometimes Sql Server will choose to expand the joins, and then apply WHERE clauses. You can usually fix this by moving the WHERE conditions into the JOIN clause, or a derived table with the conditions inlined. Views can cause the same problems.</li>\n<li>Suboptimal joins (LOOP vs HASH vs MERGE). My rule of thumb is to use a LOOP join when the top row has very few rows compared to the bottom, a MERGE when the sets are roughly equal and ordered, and a HASH for everything else. Adding a join hint will let you test your theory.</li>\n<li>Parameter sniffing. If you ran the stored proc with unrealistic values at first (say, for testing), then the cached query plan may be suboptimal for your production values. Running again WITH RECOMPILE should verify this. For some stored procs, especially those that deal with varying sized ranges (say, all dates between today and yesterday - which would entail an INDEX SEEK - or, all dates between last year and this year - which would be better off with an INDEX SCAN) you may have to run it WITH RECOMPILE every time.</li>\n<li>Bad indentation...Okay, so Sql Server doesn't have an issue with this - but I sure find it impossible to understand a query until I've fixed up the formatting.</li>\n</ul></li>\n</ol>\n"}, {'answer_id': 18965, 'author': 'Guy', 'author_id': 993, 'author_profile': 'https://Stackoverflow.com/users/993', 'pm_score': 1, 'selected': False, 'text': "<p>I look out for:</p>\n\n<ul>\n<li>Unroll any CURSOR loops and convert into set based UPDATE / INSERT statements.</li>\n<li>Look out for any application code that:\n\n<ul>\n<li>Calls an SP that returns a large set of records,</li>\n<li>Then in the application, goes through each record and calls an SP with parameters to update records.</li>\n<li>Convert this into a SP that does all the work in one transaction.</li>\n</ul></li>\n<li>Any SP that does lots of string manipulation.  It's evidence that the data is not structured correctly / normalised.</li>\n<li>Any SP's that re-invent the wheel.</li>\n<li>Any SP's that I can't understand what it's trying to do within a minute!</li>\n</ul>\n"}, {'answer_id': 19025, 'author': 'Jon Ericson', 'author_id': 1438, 'author_profile': 'https://Stackoverflow.com/users/1438', 'pm_score': 2, 'selected': False, 'text': '<p>I\'ve made it a habit to always use bind variables.  It\'s possible bind variables won\'t help if the RDBMS doesn\'t cache SQL statements.  But if you don\'t use bind variables the RDBMS doesn\'t have a chance to reuse query execution plans and parsed SQL statements.  The savings can be enormous: <a href="http://www.akadia.com/services/ora_bind_variables.html" rel="nofollow noreferrer">http://www.akadia.com/services/ora_bind_variables.html</a>.  I work mostly with Oracle, but Microsoft SQL Server works pretty much the same way.</p>\n\n<p>In my experience, if you don\'t know whether or not you are using bind variables, you probably aren\'t.  If your application language doesn\'t support them, find one that does.  Sometimes you can fix query A by using bind variables for query B.</p>\n\n<p>After that, I talk to our DBA to find out what\'s causing the RDBMS the most pain.  Note that you shouldn\'t ask "Why is this query slow?"  That\'s like asking your doctor to take out you appendix.  Sure your query might be the problem, but it\'s just as likely that something else is going wrong.  As developers, we we tend to think in terms of lines of code.  If a line is slow, fix that line.  But a RDBMS is a really complicated system and your slow query might be the symptom of a much larger problem.</p>\n\n<p>Way too many SQL tuning tips are cargo cult idols.  Most of the time the problem is unrelated or minimally related to the syntax you use, so it\'s normally best to use the cleanest syntax you can.  Then you can start looking at ways to tune the database (not the query).  Only tweak the syntax when that fails.</p>\n\n<p>Like any performance tuning, always collect meaningful statistics.  Don\'t use wallclock time unless it\'s the user experience you are tuning.  Instead look at things like CPU time, rows fetched and blocks read off of disk.  Too often people optimize for the wrong thing.</p>\n'}, {'answer_id': 19079, 'author': 'AlexCuse', 'author_id': 794, 'author_profile': 'https://Stackoverflow.com/users/794', 'pm_score': 3, 'selected': False, 'text': '<p>@Terrapin there are a few other differences between isnull and coalesce that are worth mentioning (besides ANSI compliance, which is a big one for me).</p>\n\n<p><a href="http://wiki.lessthandot.com/index.php/Three_differences_between_COALESCE_and_ISNULL" rel="noreferrer" title="Three Differences Between Coalesce and IsNull">Coalesce vs. IsNull</a></p>\n'}, {'answer_id': 19292, 'author': 'travis', 'author_id': 1414, 'author_profile': 'https://Stackoverflow.com/users/1414', 'pm_score': 1, 'selected': False, 'text': '<pre><code>SET NOCOUNT ON\n</code></pre>\n\n<p>Usually the first line inside my stored procedures, unless I actually need to use <code>@@ROWCOUNT</code>.</p>\n'}, {'answer_id': 20254, 'author': 'Seibar', 'author_id': 357, 'author_profile': 'https://Stackoverflow.com/users/357', 'pm_score': 0, 'selected': False, 'text': '<p><a href="http://www.mssqlcity.com/Articles/Adm/SQL70Locks.htm" rel="nofollow noreferrer">Dirty reads</a> -</p>\n\n<pre><code>set transaction isolation level read uncommitted\n</code></pre>\n\n<p>Prevents dead locks where transactional integrity isn\'t absolutely necessary (which is usually true)</p>\n'}, {'answer_id': 28257, 'author': 'Seibar', 'author_id': 357, 'author_profile': 'https://Stackoverflow.com/users/357', 'pm_score': 1, 'selected': False, 'text': '<p>Remove cursors wherever the are not neceesary.</p>\n'}, {'answer_id': 31615, 'author': 'Will SQL for Food', 'author_id': 3348, 'author_profile': 'https://Stackoverflow.com/users/3348', 'pm_score': 3, 'selected': False, 'text': "<p><code>CREATE INDEX</code></p>\n\n<p>Assure there are indexes available for your <code>WHERE</code> and <code>JOIN</code> clauses.  This will speed data access greatly.</p>\n\n<p>If your environment is a <em>data mart or warehouse,</em> indexes should abound for almost any conceivable query.</p>\n\n<p>In a <em>transactional environment</em>, the number of indexes should be lower and their definitions more strategic so that index maintenance doesn't drag down resources. (Index maintenance is when the leaves of an index must be changed to reflect a change in the underlying table, as with <code>INSERT, UPDATE,</code> and <code>DELETE</code> operations.)</p>\n\n<p>Also, be mindful of the order of fields in the index - the more selective (higher cardinality) a field, the earlier in the index it should appear.  For example, say you're querying for used automobiles:</p>\n\n<pre><code>SELECT   i.make, i.model, i.price\nFROM     dbo.inventory i\nWHERE    i.color = 'red'\n  AND    i.price BETWEEN 15000 AND 18000\n</code></pre>\n\n<p>Price generally has higher cardinality.  There may be only a few dozen colors available, but quite possibly thousands of different asking prices.</p>\n\n<p>Of these index choices, <code>idx01</code> provides the faster path to satisfy the query:</p>\n\n<pre><code>CREATE INDEX idx01 ON dbo.inventory (price, color)\nCREATE INDEX idx02 ON dbo.inventory (color, price)\n</code></pre>\n\n<p>This is because fewer cars will satisfy the price point than the color choice, giving the query engine far less data to analyze.</p>\n\n<p>I've been known to have two very similar indexes differing only in the field order to speed queries (firstname, lastname) in one and (lastname, firstname) in the other.</p>\n"}, {'answer_id': 76313, 'author': 'Amy B', 'author_id': 8155, 'author_profile': 'https://Stackoverflow.com/users/8155', 'pm_score': 2, 'selected': False, 'text': '<p>First step:\nLook at the Query Execution Plan!<br/>\nTableScan -> bad<br/>\nNestedLoop -> meh warning<br/>\nTableScan behind a NestedLoop -> DOOM!<br/></p>\n\n<p>SET STATISTICS IO ON<br/>\nSET STATISTICS TIME ON</p>\n'}, {'answer_id': 103176, 'author': 'AJ.', 'author_id': 7211, 'author_profile': 'https://Stackoverflow.com/users/7211', 'pm_score': 7, 'selected': False, 'text': "<p>Here is the handy-dandy list of things I always give to someone asking me about optimisation.<br>\nWe mainly use Sybase, but most of the advice will apply across the board.  </p>\n\n<p>SQL Server, for example, comes with a host of performance monitoring / tuning bits, but if you don't have anything like that (and maybe even if you do) then I would consider the following...</p>\n\n<p><strong>99% of problems</strong> I have seen are caused by putting <strong>too many tables in a join</strong>.  The fix for this is to do half the join (with some of the tables) and cache the results in a temporary table.  Then do the rest of the query joining on that temporary table.  </p>\n\n<h2>Query Optimisation Checklist</h2>\n\n<ul>\n<li>Run UPDATE STATISTICS on the underlying tables\n\n<ul>\n<li>Many systems run this as a scheduled weekly job</li>\n</ul></li>\n<li>Delete records from underlying tables (possibly archive the deleted records) \n\n<ul>\n<li>Consider doing this automatically once a day or once a week.  </li>\n</ul></li>\n<li>Rebuild Indexes</li>\n<li>Rebuild Tables (bcp data out/in) </li>\n<li>Dump / Reload the database (drastic, but might fix corruption) </li>\n<li>Build new, more appropriate index</li>\n<li>Run DBCC to see if there is possible corruption in the database</li>\n<li>Locks / Deadlocks\n\n<ul>\n<li>Ensure no other processes running in database\n\n<ul>\n<li>Especially DBCC</li>\n</ul></li>\n<li>Are you using row or page level locking?</li>\n<li>Lock the tables exclusively before starting the query</li>\n<li>Check that all processes are accessing tables in the same order</li>\n</ul></li>\n<li>Are indices being used appropriately?  \n\n<ul>\n<li>Joins will only use index if both expressions are exactly the same data type</li>\n<li>Index will only be used if the first field(s) on the index are matched in the query</li>\n<li>Are clustered indices used where appropriate?\n\n<ul>\n<li>range data</li>\n<li>WHERE field between value1 and value2</li>\n</ul></li>\n</ul></li>\n<li>Small Joins are Nice Joins\n\n<ul>\n<li>By default the optimiser will only consider the tables 4 at a time.  </li>\n<li>This means that in joins with more than 4 tables, it has a good chance of choosing a non-optimal query plan</li>\n</ul></li>\n<li>Break up the Join\n\n<ul>\n<li>Can you break up the join?  </li>\n<li>Pre-select foreign keys into a temporary table</li>\n<li>Do half the join and put results in a temporary table</li>\n</ul></li>\n<li>Are you using the right kind of temporary table? \n\n<ul>\n<li><code>#temp</code> tables may perform much better than <code>@table</code> variables with large volumes (thousands of rows). </li>\n</ul></li>\n<li>Maintain Summary Tables\n\n<ul>\n<li>Build with triggers on the underlying tables</li>\n<li>Build daily / hourly / etc. </li>\n<li>Build ad-hoc</li>\n<li>Build incrementally or teardown / rebuild </li>\n</ul></li>\n<li>See what the query plan is with SET SHOWPLAN ON</li>\n<li>See what’s actually happenning with SET STATS IO ON </li>\n<li>Force an index using the pragma:  (index: myindex)</li>\n<li>Force the table order using SET FORCEPLAN ON </li>\n<li>Parameter Sniffing: \n\n<ul>\n<li>Break Stored Procedure into 2</li>\n<li>call proc2 from proc1</li>\n<li>allows optimiser to choose index in proc2 if @parameter has been changed by proc1</li>\n</ul></li>\n<li>Can you improve your hardware? </li>\n<li>What time are you running? Is there a quieter time? </li>\n<li>Is Replication Server (or other non-stop process) running?  Can you suspend it?  Run it eg. hourly?  </li>\n</ul>\n"}, {'answer_id': 103258, 'author': 'jinsungy', 'author_id': 1316, 'author_profile': 'https://Stackoverflow.com/users/1316', 'pm_score': 1, 'selected': False, 'text': "<p>In SQL Server, use the nolock directive.  It allows the select command to complete without having to wait - usually other transactions to finish.  </p>\n\n<pre><code>SELECT * FROM Orders (nolock) where UserName = 'momma'\n</code></pre>\n"}, {'answer_id': 115125, 'author': 'Valerion', 'author_id': 16156, 'author_profile': 'https://Stackoverflow.com/users/16156', 'pm_score': 2, 'selected': False, 'text': '<p>Running the query using WITH (NoLock) is pretty much standard operation in my place. Anyone caught running queries on the tens-of-gigabytes tables without it is taken out and shot.</p>\n'}, {'answer_id': 473817, 'author': 'jandersson', 'author_id': 56506, 'author_profile': 'https://Stackoverflow.com/users/56506', 'pm_score': 3, 'selected': False, 'text': '<p>A trick I recently learned is that SQL Server can update local variables as well as fields, in an update statement.</p>\n<pre><code>UPDATE table\nSET @variable = column = @variable + otherColumn\n</code></pre>\n<p>Or the more readable version:</p>\n<pre><code>UPDATE table\nSET\n    @variable = @variable + otherColumn,\n    column = @variable\n</code></pre>\n<p>I\'ve used this to replace complicated cursors/joins when implementing recursive calculations, and also gained a lot in performance.</p>\n<p>Here\'s details and example code that made fantastic improvements in performance:\n<a href="https://web.archive.org/web/20200212211219/http://geekswithblogs.net:80/Rhames/archive/2008/10/28/calculating-running-totals-in-sql-server-2005---the-optimal.aspx" rel="nofollow noreferrer">Link</a></p>\n'}, {'answer_id': 495956, 'author': 'mwigdahl', 'author_id': 60647, 'author_profile': 'https://Stackoverflow.com/users/60647', 'pm_score': 0, 'selected': False, 'text': "<p>I always go to SQL Profiler (if it's a stored procedure with a lot of nesting levels) or the query execution planner (if it's a few SQL statements with no nesting) first.  90% of the time you can find the problem immediately with one of these two tools.</p>\n"}, {'answer_id': 496040, 'author': 'Martin Brown', 'author_id': 20553, 'author_profile': 'https://Stackoverflow.com/users/20553', 'pm_score': 2, 'selected': False, 'text': '<p>Convert NOT IN queries to LEFT OUTER JOINS if possible. For example if you want to find all rows in Table1 that are unused by a foreign key in Table2 you could do this:</p>\n\n<pre><code>SELECT *\nFROM Table1\nWHERE Table1.ID NOT IN (\n    SELECT Table1ID\n    FROM Table2)\n</code></pre>\n\n<p>But you get much better performance with this:</p>\n\n<pre><code>SELECT Table1.*\nFROM Table1\nLEFT OUTER JOIN Table2 ON Table1.ID = Table2.Table1ID\nWHERE Table2.ID is null\n</code></pre>\n'}, {'answer_id': 1232523, 'author': 'callisto', 'author_id': 67249, 'author_profile': 'https://Stackoverflow.com/users/67249', 'pm_score': 1, 'selected': False, 'text': "<p>Remove function calls in Sprocs where a lot of rows will call the function.</p>\n\n<p>My colleague used function calls (getting lastlogindate from userid as example) to return very wide recordsets.</p>\n\n<p>Tasked with optimisation, I replaced the function calls in the sproc  with the function's code: I got many sprocs' running time down from > 20 seconds to &lt; 1.</p>\n"}]
['https://Stackoverflow.com/questions/18783', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/357/']