PostgreSQL- DISTINCT Clause
The DISTINCT
clause is used in a SELECT
statement to eliminate duplicate rows from the result set. It ensures that only unique values are returned for the specified columns, effectively reducing the result set to distinct rows.
The basic syntax of using the DISTINCT
clause is as follows:
SELECT DISTINCT column1, column2, ... FROM table_name WHERE condition;
Here’s what the different parts of the DISTINCT
clause mean:
where column1, column2, ...
: specifies the columns for which you want to retrieve distinct values. You can include one or more columns, separated by commas.
and table_name
is the name of the table from which you want to retrieve data.
and WHERE condition
is an optional condition that filters the rows based on specified criteria before applying the DISTINCT
operation.
Here’s an example of how you might use the DISTINCT
clause in a PostgreSQL query.
SELECT DISTINCT department_id FROM employees;
In this example, we’re retrieving distinct department IDs from the employees
table. This means that if there are multiple employees belonging to the same department, only one instance of that department ID will be returned.
The DISTINCT
clause is useful when you want to identify unique values or create summary reports without duplicate entries. It’s important to note that the DISTINCT
operation applies to all selected columns together. If you want to retrieve distinct values for only one column while still displaying other columns, you can use aggregate functions like MAX
, MIN
, or SUM
.