简体   繁体   中英

select distinct count(id) vs select count(distinct id)

I'm trying to get distinct values from a table. When I ran select distinct count(id) from table I got over a million counts. However if I ran select count(distinct id) from table I've got only around 300k counts. What was the difference of the two queries?

Thanks

When you do select distinct count(id) then you are basically doing:

select distinct cnt
from (select count(id) as cnt from t) t;

Because the inner query only returns one row, the distinct is not doing anything. The query counts the number of rows in the table (well, more accurately, the number of rows where id is not null ).

On the other hand, when you do:

select count(distinct id)
from t;

Then the query counts the number of different values that id takes on in the table. This would appear to be what you want.

The second select is definitely what you want, because it will aggregate the id's (if you have 10 records with id=5 then they will all be counted as one record) and the select will return "how many distinct id's were in the table". However the first select will do something odd, and i'm not entirely sure what it will do.

If id is the pk the count with distinct count(id) will match the no of rows returned with count(distinct id) .

If id is not the pk but has a unique constraint(on id alone, not in combination with any other column), the no of rows returned with count(distinct id) will be equal to the count with distinct count(id) , as in the case of pk.

If id is just another column, select count distinct count(id) from table will return one row with the no of records where the id column is NOT NULL where as select count count(distinct id) from table will return 'one column' with all non NULL unique ids in the table.

In no case will the count or the no of rows returned exceed the total no of rows in your table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM