Example of DISTINCT Clause
Example 1: Obtaining Unique Grades
Suppose we want to see the unique grades in the table as there are duplicate grades also. We will run the below query.
Query:
SELECT DISTINCT Grade
FROM student;
Output:
Explanation: This query return the unique grades obtained by students. Each grade appears only once in the output.
Example 2: Obtaining Unique Ages
To see the distinct ages of the students, we can you the below query.
Query:
SELECT DISTINCT Age
FROM student;
Output:
Explanation: This query return the unique ages of the students. All the ages are listed only once which occurs once or more than once in the student table.
Group By Vs Distinct in PostgreSQL
The GROUP BY and DISTINCT clauses are essential in PostgreSQL for efficient data operations. The DISTINCT clause is used to retrieve unique values from a designated column or combination of columns within a result set, while the GROUP BY clause is used with aggregate functions to organize the result set based on one or more columns.
Distinct is good for retrieving unique values from a column, while GROUP BY is used to summarize the data. The GROUP BY clause is slower than the DISTINCT clause in large data sets due to aggregation. Understanding the differences between these two clauses is crucial for identifying patterns in datasets and optimizing database performance.