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'
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.
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 COUNT(*) slow in MySQL? Spoiler: it is optimized to be fast, and you should use it.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With