Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best to check if item exist or not: Select Count(ID)OR Exist(...)?

What's the best in performance to determined if an item exist or not specially if the table contain more than 700,000 row

if (Select count(id) from Registeration where email='[email protected]') > 0
    print 'Exist'
else
    print 'Not Exist'

OR

if Exists(Select id from Registeration where email='[email protected]') 
    print 'Exist'
else
    print 'Not Exist'
like image 530
Amr Badawy Avatar asked Jul 17 '10 12:07

Amr Badawy


People also ask

Why exists () is faster than Count ()?

Answer: Using the T-SQL EXISTS keyword to perform an existence check is almost always faster than using COUNT(*). EXISTS can stop as soon as the logical test proves true, but COUNT(*) must count every row, even after it knows one row has passed the test.

How do you check if data exists in SQL?

To test whether a row exists in a MySQL table or not, use exists condition. The exists condition can be used with subquery. It returns true when row exists in the table, otherwise false is returned. True is represented in the form of 1 and false is represented as 0.

What is Count ID?

In this case, COUNT(id) counts the number of rows in which id is not NULL .


2 Answers

EXISTS, always

  • COUNT will traverse the table or an index: you asked for a COUNT
  • EXISTS will stop as soon as it finds a row

Edit, to be clear

Of course, in this case if the email column is unique and indexed it will be close.

Generally, EXISTS will use less resources and is more correct too. You are looking for existence of a row, not "more than zero" even if they are the same

Edit2: In the EXISTS, you can use NULL, 1, ID, or even 1/0: it isn't checked...

21 May 2011 edit:

It looks like this was optimised in SQL Server 2005+ so COUNT is now the same as EXISTS in this case

like image 196
gbn Avatar answered Oct 18 '22 04:10

gbn


also take in consideration that Count() only return int in which if you count some data that exceed int it will generate error

like image 36
Hotmoil Avatar answered Oct 18 '22 04:10

Hotmoil