Updated on 2025-10-23 GMT+08:00

Compound Queries

A query that contains a compound operator is a compound query. All compound queries have the same priority. The number of columns and expressions in each query result in a set operation must be the same, and the types must be compatible.

Common set operations include:

  • UNION: a union set of the two query result sets where duplicates are removed.
  • UNION ALL: a union set of the two queries where the results of the two queries are simply combined.

Examples

-- Create a table and insert data into the table.
m_db=# CREATE TABLE test1(c11 INT, c12 VARCHAR(20));
m_db=# INSERT INTO test1 VALUES (1,'a'),(2,'b'),(4,'d');

m_db=# CREATE TABLE test2(c21 INT, c22 VARCHAR(20)); 
m_db=# INSERT INTO test2 VALUES (1,'a'),(3,'c');
  • UNION
    m_db=# SELECT * FROM test1 UNION SELECT * FROM test2;
     c11 | c12 
    -----+-----
       4 | d
       3 | c
       1 | a
       2 | b
    (4 rows)
  • UNION ALL
    m_db=# SELECT * FROM test1 UNION ALL SELECT * FROM test2;
     c11 | c12 
    -----+-----
       1 | a
       2 | b
       4 | d
       1 | a
       3 | c
    (5 rows)