postgresql
  1. postgresql-distinct

DISTINCT - (PostgreSQL Clause)

The DISTINCT clause is used in PostgreSQL to retrieve only unique values from a specified column in a table. In this tutorial, we'll discuss the syntax, example, output, explanation, use, important points, and summary of the DISTINCT clause in PostgreSQL.

Syntax

The basic syntax of the DISTINCT clause is as follows:

SELECT DISTINCT column_name FROM table_name;
  • column_name: The name of the column for which unique values are to be retrieved.
  • table_name: The name of the table containing the column.

Example

Let's suppose we have a table named employees with the following columns:

id name department salary
1 John Doe Marketing 50000
2 Jane Doe Sales 60000
3 Jack Doe Marketing 55000
4 Jill Doe Sales 65000

If we want to retrieve only the unique departments from the employees table, we can use the following query:

SELECT DISTINCT department FROM employees;

The output of this query would be:

| department |
|------------|
| Marketing  |
| Sales      |

Explanation

In this example, we used the DISTINCT clause to retrieve only the unique department values from the employees table. The query returned only two departments (Marketing and Sales), even though there were four records in the table.

Use

The DISTINCT clause is useful for retrieving only the unique values from a column in a table. This can be helpful when you want to perform analysis on a column without considering duplicate values.

Important Points

  • You can use the DISTINCT clause with multiple columns to retrieve unique combinations of values from those columns.
  • The DISTINCT clause is applied to the entire row, not just the specified column. This means that if two rows have the same values in all columns, only one row will be returned.
  • The DISTINCT clause can be used with the ORDER BY clause to specify the order of the results.

Summary

In this tutorial, we discussed the DISTINCT clause in PostgreSQL. We covered the syntax, example, output, explanation, use, and important points of the DISTINCT clause. With this knowledge, you can now use the DISTINCT clause in your PostgreSQL queries to retrieve unique values from a specified column in a table.

Published on: