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

Sort

Description

Sorts the tuples returned by the bottom-layer node. The sort operator is used to sort query results based on specified sorting rules and return ordered result sets.

Typical Scenarios

  • If a query statement contains the ORDER BY clause, GaussDB selects the sort operator in the execution plan to perform sorting.
  • Merge join is used for join operations.

Examples

Example: The query statement contains the ORDER 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=# EXPLAIN SELECT * FROM student ORDER BY grade; 
                           QUERY PLAN                            
---------------------------------------------------------------- 
 Sort  (cost=10.64..11.14 rows=200 width=12) 
   Sort Key: grade 
   ->  Seq Scan on student  (cost=0.00..3.00 rows=200 width=12) 
(3 rows)

-- Drop.
gaussdb=# DROP TABLE student;

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

Item

Description

Sort

Operator name.

Sort Key

Keyword based on which the sort operator uses for sorting. In the example, the value is grade.