Home >Database >Mysql Tutorial >How to Count Distinct Values in a SQL Column?

How to Count Distinct Values in a SQL Column?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-05 00:12:40519browse

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:

  1. SELECT DISTINCT column_name FROM table_name;
  2. SELECT column_name FROM table_name GROUP BY column_name;

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn