Updated on 2025-03-13 GMT+08:00

Group

Description

The Group operator is used to process the GROUP BY clause and group the lower-layer sorted tuples. The returned result is the result after grouping by group key.

Typical Scenarios

Grouping: queries the number of different values in a column. The function of this operation is similar to that of DISTINCT.

Examples

Example: The query statement contains the GROUP BY clause.

-- Prepare data.
gaussdb=# CREATE TABLE student(id integer, class_id integer, grade number); 
CREATE TABLE 
gaussdb=# INSERT INTO student VALUES(generate_series(1,50), 1, floor(100 * random())); 
INSERT 0 50 
gaussdb=# INSERT INTO student VALUES(generate_series(51,100), 2, floor(100 * random())); 
INSERT 0 50 
gaussdb=# INSERT INTO student VALUES(generate_series(101,150), 3, floor(100 * random())); 
INSERT 0 50 
gaussdb=# INSERT INTO student VALUES(generate_series(151,200), 3, floor(100 * random())); 
INSERT 0 50

-- Execution result.
gaussdb=# SET enable_hashagg = off;
SET
gaussdb=# EXPLAIN SELECT class_id FROM student GROUP BY class_id ORDER BY class_id; 
                             QUERY PLAN                               
--------------------------------------------------------------------- 
 Group  (cost=10.64..11.64 rows=3 width=4) 
   Group By Key: class_id 
   ->  Sort  (cost=10.64..11.14 rows=200 width=4) 
         Sort Key: class_id 
         ->  Seq Scan on student  (cost=0.00..3.00 rows=200 width=4) 
(5 rows) 

-- Drop.
gaussdb=# DROP TABLE student;

In the preceding example, the output of the Group operator is as follows.

Item

Description

Group

Operator name.

Group By Key

Group keyword. In the example, class_id is used as the keyword.