Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

limit vs exists vs count(*) vs count(id) in MySQL [duplicate]

I just want to know which one is the fastest.

What I'm trying to do is to just check if the data is existing on the table. I've been using "LIMIT" most of the time but in your opinion or if you have basis, which one is the fastest to check if data is existing.

Example:

limit 1:

SELECT ID 
       FROM TABLE 
       WHERE ID=1 LIMIT 1;

exists:

SELECT EXISTS(
              SELECT * 
              FROM TABLE 
              WHERE ID=1);

count(*):

SELECT (*) 
FROM TABLE;

count(ID):

SELECT (ID) 
FROM TABLE;" 

Additional: I'm using InnoDB.

like image 214
Echusen Avatar asked Nov 15 '13 09:11

Echusen


People also ask

What is difference between COUNT (*) and COUNT ID?

Count(*) includes rows with null values whereas count(id) would not include rows with a null id.

Which one is faster COUNT (*) or COUNT 1?

The simple answer is no – there is no difference at all. The COUNT(*) function counts the total rows in the table, including the NULL values.

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.

What is difference between COUNT (*) and COUNT column?

The count(*) returns all rows whether column contains null value or not while count(columnName) returns the number of rows except null rows.


1 Answers

Limit is always the fastest, because it iterate one line of the table.

Exists has little difference with Limit because you just add another select statement, we can say it has the same efficiency as the first one.

Count will iterate all the table and count the result. When you use count(), by default, mysql count the primary key of the table. I've done some tests of count(id), count(), count(field) and count(1) in big table, there is no big difference. In my opinion, 'count' will always try to count the index unless the field you count is not an index, but many people said that we should use count(id) rather than use count(*).

In a small table, the four ways all work fine. But if you join with some big table, count will take a very very long time.

So in all, the time used is count(*) > count(id) >> exists > limit

like image 95
user2208436 Avatar answered Oct 20 '22 08:10

user2208436