Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql count vs mysql SELECT, which one is faster?

If I want to do a check a name, I want to see how many rows/name exists in the "username" column under users table. Lets say thousands ... hundred of thousands, should I use:

  • count(name),

  • count(*) or

  • SELECT username FROM users where username = 'name'

Which one is the more appropriate? Or they will give same result in term of speed/response?

EDIT:

Thanks guys, I found the answer, count() will definitely faster

Is this query correct

SELECT COUNT( username )
FROM users
WHERE `username` = 'tim' 
like image 782
myphpsql00 Avatar asked Nov 02 '09 08:11

myphpsql00


People also ask

Is Select * faster than count *?

UPDATE: Given the clarification the original poster made in their comment, the short, definitive answer is that a SELECT 1 or SELECT COUNT(1) is no faster than a SELECT COUNT(*) . Contrary to whatever coding guidelines you are looking at, COUNT(*) is the preferred way of counting all the rows.

Which is faster Count 1 or Count *?

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.

Is MySQL count slow?

Is COUNT(*) slow in MySQL? Spoiler: it is optimized to be fast, and you should use it.

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.


1 Answers

COUNT(*) and COUNT(Name) might produce different values. COUNT will not include NULL values, so if there are any instances of Name that equal NULL they will not be counted.

COUNT(*) will also perform better than Count(Name). By specifying COUNT(*) you are leaving the optimizer free to use any index it wishes. By specifying COUNT(Name) you are forcing the query engine to use the table, or at least an index that contains the NAME column.

like image 101
Andrew Shepherd Avatar answered Sep 28 '22 10:09

Andrew Shepherd