Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL to find the number of distinct values in a column

Tags:

sql

distinct

I can select all the distinct values in a column in the following ways:

  • SELECT DISTINCT column_name FROM table_name;
  • SELECT column_name FROM table_name GROUP BY column_name;

But how do I get the row count from that query? Is a subquery required?

like image 932
Christian Oudard Avatar asked Sep 26 '08 19:09

Christian Oudard


People also ask

How do I count distinct values in a column in SQL?

The COUNT DISTINCT function returns the number of unique values in the column or expression, as the following example shows. SELECT COUNT (DISTINCT item_num) FROM items; If the COUNT DISTINCT function encounters NULL values, it ignores them unless every value in the specified column is NULL.

How do I count the number of unique values in a column?

You can use the combination of the SUM and COUNTIF functions to count unique values in Excel. The syntax for this combined formula is = SUM(IF(1/COUNTIF(data, data)=1,1,0)). Here the COUNTIF formula counts the number of times each value in the range appears.

Can I do a distinct count 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.

How do I count distinct rows in SQL?

The syntax of the SQL COUNT function:COUNT ([ALL | DISTINCT] expression); 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

You can use the DISTINCT keyword within the COUNT aggregate function:

SELECT COUNT(DISTINCT column_name) AS some_alias FROM table_name 

This will count only the distinct values for that column.

like image 105
Noah Goodrich Avatar answered Sep 19 '22 00:09

Noah Goodrich