Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Best Practice: count(1) or count(*) [duplicate]

Tags:

sql

Possible Duplicate:
Count(*) vs Count(1)

I remember anecdotally being told:

never use count(*) when count(1) will do

Recently I passed this advice on to another developer, and was challenged to prove this was true. My argument was what I was told along with when I was given the advice: that the database would only return the first column, which would then be counted. The counterargument was that the database wouldn't evaluate anything in the brackets.

From some (unscientific) testing on small tables, there certainly seems to be no difference. I don't currently have access to any large tables to experiment on.

I was given this advice when I was using Sybase, and tables had hundreds of millions of rows. I'm now working with Oracle and considerably less data.

So I guess in summary, my two questions are:

  1. Which is faster, count(1) or count(*)?
  2. Would this vary in different database vendors?
like image 324
Clarkey Avatar asked Aug 19 '11 16:08

Clarkey


People also ask

Which is better COUNT (*) or COUNT 1?

There is no difference. "1" is a non-null expression: so it's the same as COUNT(*) .

Is COUNT * or COUNT 1 faster?

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. The semantics for COUNT(1) differ slightly; we'll discuss them later. However, the results for COUNT(*) and COUNT(1) are identical.

Does COUNT (*) include duplicate values?

COUNT(*) returns the number of items in a group. This includes NULL values and duplicates.

Does COUNT include duplicates in SQL?

The syntax of the SQL COUNT function: By default, SQL Server Count Function uses All keyword. It means that SQL Server counts all records in a table. It also includes the rows having duplicate values as well.


1 Answers

According to another similar question (Count(*) vs Count(1)), they are the same.

In Oracle, according to Ask Tom, count(*) is the correct way to count the number of rows because the optimizer changes count(1) to count(*). count(1) actually means to count rows with non-null 1's (all of them are non-null so optimizer will change it for you).

like image 97
andy Avatar answered Nov 01 '22 17:11

andy