6

I would like to know what are the differences between using:

SELECT email, COUNT( email ) AS total
FROM `newsletter`
GROUP BY email having total>1

or

SELECT count(*) as total, email 
FROM 'newsletter' 
GROUP BY email having total > 1

Both give same results but what else is counting count(*) than the emails?

Toni Michel Caubet
  • 19,333
  • 56
  • 202
  • 378
  • See http://dba.stackexchange.com/q/2511/630 explains in relation to the ANSI standard – gbn Jan 10 '12 at 11:16
  • 1
    possible duplicate of [In SQL, what's the difference between count(column) and count(*)?](http://stackoverflow.com/questions/59294/in-sql-whats-the-difference-between-countcolumn-and-count) and many others – gbn Jan 10 '12 at 11:18

4 Answers4

5

There's at least one difference.

  • They may return different results if email can contain NULL.

For more information, see this article.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
2

COUNT(*) counts all rows WHEREAS COUNT(columnname) counts non-NULLs only.

Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
2

count(*) allows the database to use an index for counting, so it can do performance-improvements. as you said, the result is the same in most cases, but:

  • count(column) only counts non-null-rows

so in colusion: if you have to mess around with null-values, use count(column), otherwise use count(*) for better performance.

oezi
  • 51,017
  • 10
  • 98
  • 115
1

SELECT COUNT(*) counts all ROWS

SELECT COUNT(email) counts all VALUES (non-NULL values)

In your case, if all rows contain values, both results may be the same. But it can make a difference in performance, but this depends on table volumne, storage engine, indexes...

rabudde
  • 7,498
  • 6
  • 53
  • 91