📜  postgres count distinct - SQL (1)

📅  最后修改于: 2023-12-03 15:18:37.652000             🧑  作者: Mango

PostgreSQL COUNT DISTINCT - SQL

Introduction

In PostgreSQL, the COUNT DISTINCT function is used to count the number of unique values in a specified column of a table. It returns the count as a single result. This function is useful when you want to know the number of distinct values in a specific column, excluding duplicates.

Syntax

The basic syntax of the COUNT DISTINCT function in PostgreSQL is as follows:

SELECT COUNT(DISTINCT column_name)
FROM table_name;
Example

Consider a table named "customers" with the following data:

| id | name | country | |----|---------|---------| | 1 | John | USA | | 2 | Emily | Canada | | 3 | John | USA | | 4 | Michael | UK | | 5 | Emily | Canada |

To count the distinct names in the "name" column, you can use the COUNT DISTINCT function as follows:

SELECT COUNT(DISTINCT name) AS distinct_names
FROM customers;

The result will be:

| distinct_names | |----------------| | 3 |

Explanation

In the above example, the COUNT DISTINCT function counts the distinct names in the "name" column of the "customers" table. The result shows that there are 3 unique names in the "name" column.

Conclusion

The COUNT DISTINCT function in PostgreSQL is a useful tool to count the number of unique values in a specified column. It allows you to exclude duplicates and obtain a count of distinct values. This can be helpful in various scenarios, such as analyzing customer data, identifying unique entries, and more.