Why optimize SQL query?
Many of us feel the query that we wrote is final and once it works and provides the result then that query is the best.
Actually, Query optimization is not only the technique to make your query fetch details or execute many CRUD operations but also they are the main scope to make the end user continue with your application.
It’s the same situation when we access some websites, and fetching data pull most of your time, then you may prefer to use other websites which get you all results instantly.
Optimization is not only to create impact technically but also from a business point of view has a very large impact.
How to Optimize SQL Query?
Hope now you feel that optimizing a query is better also there are a few things that you have to consider before writing a query or before deploying the same.
Avoid using “*” in select query
We have the habit of always writing a query using “*” in select operations.
Example
SELECT * FROM Students [X]
Where the select will fetch all the columns of the table, whenever there is a need for the column then use it, don’t fetch all the columns of the table. Always use column-specific names.
Example
SELECT ID, Name FROM Students [√]
Avoid using Copy Paste of Code randomly
We have the habit of copying the code from existing code or from online forums whenever required while copying please use only the code that exactly applies to the logic, reusing similar code or copying unwanted lines which may not create an impact on your query but may take time for execution, so during code reusability always use only code that exactly required to fetch results for you.
Avoid using functions in the Where Clause
When we have to execute any query there will be a conditional check using the where clause for filtering of data.
Example
SELECT Name, DOB FROM Students WHERE DOB < getdate() [X]
When we use any of the system-defined or user-defined functions in the where clause, then each time; i.e., each of the rows in the table will be checked against the function results which in turn execute the function each time. Obviously, this will take more time and we all know the parameterless function will always return the same values.
Better assign the function value to a variable and then use it in a where clause.
DECLARE @MyDate as date
SET @MyDate = GetDate()
SELECT Name, DOB FROM Students WHERE DOB < @MyDate [√]
Avoid using Joins between two types of columns
As all of you know Type Conversion during data manipulation is another place where a large amount of time will be consumed, when we are trying to join two types of columns then the other column has to be converted, and the values of the lower column has to be converted and this will take some time for converting for each of the row values.
SELECT Name FROM Student, Parents WHERE
Student.SchoolFees = Parents.KidsFees [X]
Student.SchoolFees - Int Value
Parents.KidsFees - Float Value
Avoid using COUNT(*) from tables for getting row count
We usually use the COUNT(*) to get the number of rows available in a table.
Example
SELECT COUNT(*) FROM Student [X]
This count(*) makes the full scan of the table, whenever the code is executed.
SELECT rows FROM Student
WHERE id = OBJECT_ID('dbo.Orders') AND indid < 2 [√]
Note
This query will not do a full scan of table rows, where if you need to check for any value for that condition available then this query may be useful, but not always provide the exact count of rows.
Avoid using DISTINCT when Join Tables
When we use the Distinct keyword it looks as if the query will be automatically optimized by the internal SQL engine, that is true when you use the Distinct for filtering operations when we use the distinct during the table join operations which has one too many relations then it’s not advisable.

Pravin LalgePosted Jun 12, 2018, 7:59 AM
Very useful
Bhuvanesh MohankumarPosted May 23, 2016, 3:42 AM
Thanks Humayun Kabir Mamun
Humayun Kabir MamunPosted May 22, 2016, 7:18 AM
Nice...
Bhuvanesh MohankumarPosted May 19, 2016, 6:52 AM
Thanks Pradeep Sahoo
Bhuvanesh MohankumarPosted May 19, 2016, 6:52 AM
Thanks Ipsita Sethi
Pradeep SahooPosted May 15, 2016, 11:14 PM
Nice information .Thanks for sharing.
Ipsita SethiPosted May 11, 2016, 1:33 PM
Good job Bhuvan
Former memberPosted May 9, 2016, 1:29 AM
Thanks...It's Very Helpful
Bhuvanesh MohankumarPosted May 6, 2016, 3:12 AM
Thanks for reading Tim Jefferson, optimization depends on individual views and this article is intended for the "Beginners" you can check the Reader Level what we suggest in C-Sharp corner for the target audience in right top. When the people start reading the SQL and in initial state making them to understand or learn about the Execution Plan for a self studying person will be tough, as they can learn coding SQL queries in hours for them this article will help to write a better code, we also have many article which makes your optimize for the Best level available in C-Sharp corner for the Expertise where the points you mentioned all are covered. In General forum variety of readers will be available including students and very initial stage beginners based on which the content will be loaded with knowledge.
Tim JeffersonPosted May 6, 2016, 1:06 AM
This article really has nothing related to how to optimize SQL queries, the best way to optimize any query surely starts with looking at the Execution Plan, understanding that plan and then either tweaking the SQL or creating indexes to reduced the cost of the query. This article attempts to list some possible best practices, but I would even question if many of them are very good practices. These days all SQL should be written using ANSI joins, not comma delimited tables. Your point 3 is incorrect, using GetDate() in the where clause has no extra cost, it is not executed per row, it is executed once and then compared against the rows, if you look at the Plan you will see this. Point 4 is just bizarre, why would you be joining two columns with different datatypes? - this points to your model being wrong, and will also not allow you to correctly create Foreign Keys on this columns. Point 5 - generally when you want to count something you don't want all the rows, just a subset, so count is still a good option for that (however using COUNT(1) rather than COUNT(*) is generally considered better). Point 6, 7, 8, 9 are generally valid, however Temp tables do have there place when dealing with a distinct set of more than 100 rows (and table variables useful when dealing with less than 100 rows). Point 10 is only really valid for adhoc queries, generally NO application code should ever use "With(No Lock)", as dirty reads will return inconsistent data.
Thiruppathi RPosted May 2, 2016, 4:33 AM
Really useful.but i am confused 5th point
NitinPosted Apr 26, 2016, 4:57 AM
good one
Vignesh ManiPosted Apr 25, 2016, 8:16 AM
Nice
Raja TPosted Apr 25, 2016, 8:00 AM
Nice, Thanks for sharing
Saurabh NayakPosted Apr 25, 2016, 7:06 AM
Nice article!
Pankaj Kumar ChoudharyPosted Apr 25, 2016, 5:58 AM
But if you want find out records for each table in database then you can use this query like as below "SELECT T.name AS Table_Name, I.rows AS Records_ FROM sys.tables AS T INNER JOIN sys.sysindexes AS I ON T.object_id = I.id AND I.indid < 2 ORDER BY I.rows DESC So i request you check out the execution plan for both query and after that write which method you find best to count the records for a table...
Pankaj Kumar ChoudharyPosted Apr 25, 2016, 5:58 AM
And one more thing title of your article is "how to optimize the sql query". In case of query 5 i think this title violating the rule because the method that you are using to count the number of records for table is very complex to compare of "select count(*) from table_name" query method. Because your query perform some extra calculation like "Nested Loops", "Filter" "Table valued funcation" more than one time that makes it very slow.For satisfication run the both query and check the execution plan and you will find that your query taking more time compare to count(*). When i checked the execution plan for my table that contains 22 rows i found that estimated cost for count(*) was 0.0033199 and estimated cost for another query was 0.0065918. that prove that this this method is not correct to count the records for a table. Best method to count the total record for any table is "Select count(1) from Table_Name".
Bhuvanesh MohankumarPosted Apr 25, 2016, 3:35 AM
Hi Pankaj, Both the queries are same, the query which I have shared are the sample snippet for reference and not with actual data, SELECT I.rows AS RecordFROM sys.sysindexes IWHERE I.id=OBJECT_ID('Table_Name') AND I.indid<2 Thanks
Gowtham RajamanickamPosted Apr 25, 2016, 2:36 AM
very good article
Pankaj Kumar ChoudharyPosted Apr 25, 2016, 2:31 AM
Hello! Bhuvanesh I think there is something wrong in query of part 5. I think your query is wrong and it will not provide any result. the actual query is "SELECT I.rows AS RecordFROM sys.sysindexes IWHERE I.id=OBJECT_ID('Table_Name') AND I.indid<2". Now this query will provide the correct result... Hello! Bhuvanesh confirm that if this query similar to your query or not..
Yashwant VishwakarmaPosted Apr 25, 2016, 2:11 AM
Nice article on SQL Query optimization, I was searching for it.
Ghyath SerhalPosted Apr 25, 2016, 1:50 AM
Part 5 did not work for me. Invalid column name 'rows'.
Pankaj Kumar ChoudharyPosted Apr 25, 2016, 12:38 AM
Nice Share Bhuvanesh......
Muhammad Aqib ShehzadPosted Apr 24, 2016, 11:48 PM
Good Info
Jaipal ReddyPosted Apr 24, 2016, 11:35 PM
Nice one. .