Skip to content

WITHIN GROUP

  • within group: This keyword in PostgreSQL is used to order or sort the partitioned data within a group. Within each group, this function sorts the data based on the expression provided.
  • order by expression: It is the sorting order that is specified. Data can be sorted in ascending or descending order based on numeric value, string value, date value, etc. This ordering is done as per the criteria specified in the expression.
SELECT gender,
avg(age) WITHIN GROUP (ORDER BY age) as average_age
FROM employee
GROUP BY gender;
gender | average_age
--------+-------------
male | 35.4
female | 33.6

In the code example, the WITHIN_GROUP function is used in conjunction with the avg function to calculate the ordered average age within each gender group from the employee table. The results are then grouped by the gender column. Network traffic is reduced because the sorted results are retrieved directly from the server.