<p>What techniques can be applied effectively to improve the performance of SQL queries? Are there any general rules that apply?</p>

[{'answer_id': 39336, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 0, 'selected': False, 'text': '<p>I think using SQL query analyzer would be a good start.</p>\n'}, {'answer_id': 39342, 'author': 'hamishmcn', 'author_id': 3590, 'author_profile': 'https://Stackoverflow.com/users/3590', 'pm_score': 0, 'selected': False, 'text': '<p>In Oracle you can look at the <a href="http://www.oracle-base.com/articles/8i/ExplainPlanUsage.php" rel="nofollow noreferrer">explain plan</a> to compare variations on your query</p>\n'}, {'answer_id': 39344, 'author': 'Unsliced', 'author_id': 2902, 'author_profile': 'https://Stackoverflow.com/users/2902', 'pm_score': 5, 'selected': True, 'text': '<ul>\n<li>Use primary keys</li>\n<li>Avoid select *</li>\n<li>Be as specific as you can when building your conditional statements </li>\n<li>De-normalisation can often be more efficient </li>\n<li>Table variables and temporary tables (where available) will often be better than using a large source table </li>\n<li>Partitioned views </li>\n<li>Employ indices and constraints </li>\n</ul>\n'}, {'answer_id': 39345, 'author': 'megabytephreak', 'author_id': 4108, 'author_profile': 'https://Stackoverflow.com/users/4108', 'pm_score': 0, 'selected': False, 'text': '<p>Make sure that you have the right indexes on the table. if you frequently use a column as a way to order or limit your dataset an index can make a big difference. I saw in a recent article that select distinct can really slow down a query, especially if you have no index.</p>\n'}, {'answer_id': 39349, 'author': 'Ubiguchi', 'author_id': 2562, 'author_profile': 'https://Stackoverflow.com/users/2562', 'pm_score': 0, 'selected': False, 'text': "<p>The obvious optimization for SELECT queries is ensuring you have indexes on columns used for joins or in WHERE clauses.</p>\n\n<p>Since adding indexes can slow down data writes you do need to monitor performance to ensure you don't kill the DB's write performance, but that's where using a good query analysis tool can help you balanace things accordingly.</p>\n"}, {'answer_id': 39354, 'author': 'Danimal', 'author_id': 2757, 'author_profile': 'https://Stackoverflow.com/users/2757', 'pm_score': 2, 'selected': False, 'text': '<p>The biggest thing you can do is to look for table scans in sql server query analyzer (make sure you turn on "show execution plan"). Otherwise there are a myriad of articles at MSDN and elsewhere that will give good advice.</p>\n\n<p>As an aside, when I started learning to optimize queries I ran sql server query profiler against a trace,  looked at the generated SQL, and tried to figure out why that was an improvement. Query profiler is far from optimal, but it\'s a decent start.</p>\n'}, {'answer_id': 39359, 'author': 'pirho', 'author_id': 3911, 'author_profile': 'https://Stackoverflow.com/users/3911', 'pm_score': 0, 'selected': False, 'text': '<ul>\n<li>Indexes</li>\n<li>Statistics</li>\n<li>on microsoft stack, Database Engine Tuning Advisor</li>\n</ul>\n'}, {'answer_id': 39398, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 3, 'selected': False, 'text': '<p>Learn what\'s really going on under the hood - you should be able to understand the following concepts in detail:</p>\n\n<ul>\n<li>Indexes (not just what they are but actually how they work).</li>\n<li>Clustered indexes vs heap allocated tables.</li>\n<li>Text and binary lookups and when they can be in-lined.</li>\n<li><a href="https://stackoverflow.com/questions/10919/how-do-you-measure-sql-fill-factor-value">Fill factor</a>.</li>\n<li>How records are ghosted for update/delete.</li>\n<li>When page splits happen and why.</li>\n<li>Statistics, and how they effect various query speeds.</li>\n<li>The query planner, and how it works for your specific database (for instance on  some systems "select *" is slow, on modern MS-Sql DBs the planner can handle it).</li>\n</ul>\n'}, {'answer_id': 61422, 'author': 'Leo Moore', 'author_id': 6336, 'author_profile': 'https://Stackoverflow.com/users/6336', 'pm_score': 2, 'selected': False, 'text': '<p>There are a couple of things you can look at to optimize your query performance.</p>\n\n<ol>\n<li><p>Ensure that you just have the minimum of data. Make sure you select only the columns you need. Reduce field sizes to a minimum.</p></li>\n<li><p>Consider de-normalising your database to reduce joins</p></li>\n<li><p>Avoid loops (i.e. fetch cursors), stick to set operations.</p></li>\n<li><p>Implement the query as a stored procedure as this is pre-compiled and will execute faster.</p></li>\n<li><p>Make sure that you have the correct indexes set up. If your database is used mostly for searching then consider more indexes.</p></li>\n<li><p>Use the execution plan to see how the processing is done. What you want to avoid is a table scan as this is costly.</p></li>\n<li><p>Make sure that the Auto Statistics is set to on. SQL needs this to help decide the optimal execution. See Mike Gunderloy\'s great post for more info. <a href="http://www.developer.com/db/article.php/10920_3622881_1" rel="nofollow noreferrer">Basics of Statistics in SQL Server 2005</a></p></li>\n<li><p>Make sure your indexes are not fragmented. <a href="http://www.mssqlcity.com/Articles/Adm/index_fragmentation.htm" rel="nofollow noreferrer">Reducing SQL Server Index Fragmentation\n</a> </p></li>\n<li>Make sure your tables are not fragmented. <a href="http://www.sql-server-performance.com/articles/per/detect_fragmentation_sql2000_sql2005_p1.aspx" rel="nofollow noreferrer">How to Detect Table Fragmentation in SQL Server 2000 and 2005</a></li>\n</ol>\n'}, {'answer_id': 78938, 'author': 'EvilTeach', 'author_id': 7734, 'author_profile': 'https://Stackoverflow.com/users/7734', 'pm_score': 1, 'selected': False, 'text': "<p>Use a <strong>with</strong> statment to handle query filtering. \nLimit each subquery to the minimum number of rows possible. \nthen join the subqueries.</p>\n\n<pre><code>WITH\nmaster AS\n(\n    SELECT SSN, FIRST_NAME, LAST_NAME\n    FROM MASTER_SSN\n    WHERE STATE = 'PA' AND\n          GENDER = 'M'\n),\ntaxReturns AS\n(\n    SELECT SSN, RETURN_ID, GROSS_PAY\n    FROM MASTER_RETURNS\n    WHERE YEAR &lt; 2003 AND\n          YEAR &gt; 2000\n)\nSELECT *\nFROM master,\n     taxReturns\nWHERE master.ssn = taxReturns.ssn\n</code></pre>\n\n<p>A subqueries within a with statement may end up as being the same as inline views,\nor automatically generated temp tables.  I find in the work I do, retail data, that about 70-80% of the time, there is a performance benefit.</p>\n\n<p>100% of the time, there is a maintenance benefit.</p>\n"}, {'answer_id': 16611929, 'author': 'HLGEM', 'author_id': 9034, 'author_profile': 'https://Stackoverflow.com/users/9034', 'pm_score': 0, 'selected': False, 'text': "<p>Some other points (Mine are based on SQL server, since each db backend has it's own implementations they may or may not hold true for all databases):</p>\n\n<p>Avoid correlated subqueries in the select part of a statement, they are essentially cursors.</p>\n\n<p>Design your tables to use the correct datatypes to avoid having to apply functions on them to get the data out. It is far harder to do date math when you store your data as varchar for instance.</p>\n\n<p>If you find that you are frequently doing joins that have functions in them, then you need to think about redesigning your tables.</p>\n\n<p>If your WHERE or JOIN conditions include OR statements (which are slower) you may get better speed using a UNION statement. </p>\n\n<p>UNION ALL is faster than UNION if (And only if) the two statments are mutually exclusive and return the same results either way.</p>\n\n<p>NOT EXISTS is usually faster than NOT IN or using a left join with a WHERE clause of ID = null</p>\n\n<p>In an UPDATE query add a WHERE condition to make sure you are not updating values that are already equal. The difference between updating 10,000,000 records and 4 can be quite significant!</p>\n\n<p>Consider pre-calculating some values if you will be querying them frequently or for large reports.  A sum of the values in an order only needs to be done when the order is made or adjusted, rather than when you are summarizing the results of 10,000,000 million orders in a report. Pre-calculations should be done in triggers so that they are always up-to-date is the underlying data changes. And it doesn't have to be just numbers either, we havea calculated field that concatenates names that we use in reports. </p>\n\n<p>Be wary of scalar UDFs, they can be slower than putting the code in line. </p>\n\n<p>Temp table tend to be faster for large data set and table variables faster for small ones. In addition you can index temp tables.</p>\n\n<p>Formatting is usually faster in the user interface than in SQL.</p>\n\n<p>Do not return more data than you actually need.</p>\n\n<p>This one seems obvious but you would not believe how often I end up fixing this. Do not join to tables that you are not using to filter the records or actually calling one of the fields in the select part of the statement.  Unnecessary joins can be very expensive.</p>\n\n<p>It is an very bad idea to create views that call other views that call other views. You may find you are joining to the same table 6 times when you only need to once and creating 100,000,00 records in an underlying view in order to get the 6 that are in your final result.</p>\n\n<p>In designing a database, think about reporting not just the user interface to enter data. Data is useless if it is not used, so think about how it will be used after it is in the database and how that data will be maintained or audited.  That will often change the design. (This is one reason why it is a poor idea to let an ORM design your tables, it is only thinking about one use case for the data.) The most complex queries affecting the most data are in reporting, so designing changes to help reporting can speed up queries (and simplify them) considerably.</p>\n\n<p>Database-specific implementations of features can be faster than using standard SQL (That's one of the ways they sell their product), so get to know your database features and find out which are faster. </p>\n\n<p>And because it can't be said too often, use indexes correctly, not too many or too few. And make your WHERE clauses sargable (Able to use indexes).</p>\n"}]
['https://Stackoverflow.com/questions/39331', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/184/']