Home >Database >Mysql Tutorial >How to Count Distinct Values in a SQL Column?
Distinct Values in SQL: Counting Unique Entries
When working with database tables, it's often necessary to identify and count distinct values within a specific column. This can be achieved using the DISTINCT keyword combined with the COUNT aggregate function.
Obtaining Distinct Values
To select only the distinct values in a column, you have two options:
Both methods will return a result set containing only the unique values for the specified column.
Counting Distinct Values
To determine the count of distinct values in a column, you can use the following syntax:
SELECT COUNT(DISTINCT column_name) AS some_alias FROM table_name
Here, the DISTINCT keyword is used within the COUNT aggregate function. This operation counts only the distinct values, ignoring duplicates, and returns the result as a new column with an alias of your choosing (e.g., some_alias).
Example
Consider the following table customers:
id | name |
---|---|
1 | John |
2 | Mary |
3 | John |
4 | David |
5 | Mary |
To count the distinct values in the name column, we would execute the following query:
SELECT COUNT(DISTINCT name) AS distinct_names FROM customers
The result of this query would be:
distinct_names |
---|
3 |
As you can see, the query returns the count of distinct names in the name column, which is 3.
The above is the detailed content of How to Count Distinct Values in a SQL Column?. For more information, please follow other related articles on the PHP Chinese website!