Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL count(*) and distinct

Tags:

sql

Why can't we use count(distinct *) in SQL? As in to count all distinct rows?

like image 581
Nitish Upreti Avatar asked Dec 01 '09 13:12

Nitish Upreti


People also ask

How do I use count and distinct together in SQL?

The correct syntax for using COUNT(DISTINCT) is: SELECT COUNT(DISTINCT Column1) FROM Table; The distinct count will be based off the column in parenthesis. The result set should only be one row, an integer/number of the column you're counting distinct values of.

What is the difference between Count Count distinct and count (*) in SQL?

So, is there any difference? 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.

What does count (*) do in SQL?

COUNT(*) returns the number of rows in a specified table, and it preserves duplicate rows. It counts each row separately. This includes rows that contain null values.

Is there a count distinct function in SQL?

Suppose we want to know the distinct values available in the table. We can use SQL COUNT DISTINCT to do so. In the following output, we get only 2 rows. SQL COUNT Distinct does not eliminate duplicate and NULL values from the result set.


3 Answers

select count(*) from (select distinct * from MyTable) as T

Although I strongly suggest that you re-think any queries that use DISTINCT. In a large percentage of cases, GROUP BY is more appropriate (and faster).

EDIT: Having read the question comments, I should point out that you should never ask the DBMS to do more work than actually needs doing to get a result. If you know in advance that there will not be any duplicated rows in a table, then don't use DISTINCT.

like image 146
Christian Hayter Avatar answered Nov 17 '22 00:11

Christian Hayter


You can select all the columns in your table and group by...

SELECT column1, column2, column3, count(*)
FROM someTable
GROUP BY column1, column2, column3
like image 39
Jason Punyon Avatar answered Nov 16 '22 23:11

Jason Punyon


why not?

select 
  count(distinct name)
from 
  people
like image 4
silent Avatar answered Nov 16 '22 22:11

silent