Check if a record exists using IF EXISTS instead of COUNT(*) for increased performance
Summary:
- How to find out if a record exists in a table efficiently using the IF EXISTS keyword, and
- How to test two queries to see which is faster using SQL Server Management Studio. This articles teaches you how to tune and tweak your queries.
If you are writing a query to find out if a record exists in your table, you might not be doing it the fastest way if you are using COUNT(*).
i.e. SELECT COUNT(*) FROM USERS where USERID=@UID
and then from your code you are checking if the count is greater than 0.
This can be efficiently re-written as
IF EXISTS (SELECT * FROM USERS WHERE USERID=@UID) select 1 else select 0
That is very easy. It is much more efficient.
How do we know its more efficient?
You can use SQL Server Management Studio to find out. What you have to do is write your two queries,
--testing variables declare @UID int set @UID = 1 --actual query 1 SELECT COUNT(*) FROM USERS where USERID=@UID --actual query 2 IF EXISTS (SELECT * FROM USERS WHERE USERID=@UID) select 1 else select 0
Select all, Click on the button to generate the query execution plan (screenshot below – click to enlarge)
And you will see that it will give you a percentage breakdown for each query. The first two lines, creating testing variables, you can ignore. However, looking at the last two queries will show you the breakdown of effort required to run those queries. It will be similar to 99% for query 1, and 1% for query 2. This is a quick way to find which query should run faster and you can tweak the queries until you get the results you want.
What that means is 98% of the work has to go into the first query (out of 2) and 2% for the second. That gives you a rough … idea… of which one is faster. Sometimes it will be more evenly broken down, closer to 50/50, and in that case they are roughly equivalent.
Related Reading:
Other Interesting Posts
2 Responses to Check if a record exists using IF EXISTS instead of COUNT(*) for increased performance
Leave a Reply Cancel reply
-
Articles
- January 2011
- April 2010
- March 2010
- February 2010
- January 2010
- August 2009
- July 2009
- June 2009
- May 2009
- April 2009
- February 2009
- December 2008
- November 2008
- October 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- February 2008
- December 2007
- November 2007
- October 2007
- September 2007
- August 2007
- July 2007
- June 2007
- May 2007
-
Meta










i want to find the records exists or not with the help of datareader,dataset and datatable pls give reply for my question
קידום דפי מקוונים עושים רק בחברת קידום אתרים מקצועית כמו חברת נט-סטייל . צרו עמנו קשר על מנת לרכוש שרות של קידום אתרים בגוגל בדרך הטובה ביותר.