Example of GROUP BY Clause
Example 1: Total number of students in each Grade
Suppose we want to see the total number of students having the same grade for different grades, we can run the below query.
Query:
SELECT Grade, COUNT(*) AS total_students
FROM student
GROUP BY Grade;
Output:
Explanation: This query calculates the total number of students in each grade by adding the students having the same grade.
Example 2: Average age of students in each Grade
Suppose we want to know the average age of students who obtained the same grade. We can use the below query,
Query:
SELECT Grade, AVG(Age) AS avg_age
FROM student
GROUP BY Grade;
Output:
Explanation: This query calculates the average age (using an aggregate function) of the students having the same Grade.
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.
Contact Us