UNION is a powerful SQL operator that combines the result sets of two or more SELECT statements into one. During combination, the number of columns and data types in the two tables must be the same and correspond to each other. Use the UNION or UNION ALL keyword between SELECT statements.
UNION removes duplicate rows, while UNION ALL keeps them. Deduplication is time-consuming, so UNION ALL can be faster than UNION if the data sets are already distinct by logic.

1 | SELECT column,... FROM table1 UNION [ALL]SELECT column,... FROM table2 |
1 2 3 4 5 6 7 | SET current_schema=public; DROP TABLE IF EXISTS student; CREATE table student( sId VARCHAR(10) NOT NULL , sname VARCHAR(10) NOT NULL , ssex VARCHAR(10) NOT NULl , sschool VARCHAR(10) NOT NULl ); |
1 2 3 4 5 6 7 8 | INSERT INTO student VALUES('s01' , 'ZhaoLei' , 'male', 'NENU'); INSERT INTO student VALUES('s02' , 'QianDian' , 'male', 'SJTU'); INSERT INTO student VALUES('s03' , 'SunFenng' , 'male', 'Tongji'); INSERT INTO student VALUES('s04' , 'LIYun' , 'male', 'CCOM'); INSERT INTO student VALUES('s05' , 'ZhouMei' , 'female', 'FuDan'); INSERT INTO student VALUES('s06' , 'WuLan' , 'female', 'WHU'); INSERT INTO student VALUES('s07' , 'ZhengZhu' , 'female', 'NWAFU'); INSERT INTO student VALUES('s08' , 'ZhangShan' , 'female', 'Tongji'); |
1 | SELECT * FROM student; |
Information similar to the following is displayed.

1 2 3 4 5 6 | DROP TABLE IF EXISTS teacher; CREATE table teacher( tid VARCHAR(10) NOT NULL , tname VARCHAR(10) NOT NULL , tsex VARCHAR(10) NOT NULL , tschool VARCHAR(10) NOT NULL ); |
1 2 3 | INSERT INTO teacher VALUES('t01' , 'ZhangLei', 'male', 'FuDan'); INSERT INTO teacher VALUES('t02' , 'LiLiang', 'male', 'WHU'); INSERT INTO teacher VALUES('t03' , 'WangGang', 'male', 'Tongji'); |
1 | SELECT * FROM teacher; |

1 2 3 4 5 6 7 8 | SELECT t.school FROM ( SELECT sschool AS school FROM student UNION SELECT tschool AS school FROM teacher ) t ORDER BY t.school ASC; |
Information similar to the following is displayed.

1 2 3 4 5 6 7 8 | SELECT t.school FROM ( SELECT sschool AS school FROM student UNION ALL SELECT tschool AS school FROM teacher ) t ORDER BY t.school ASC; |

1 2 3 4 5 6 7 8 9 10 | SELECT t.* FROM ( SELECT Sid AS id ,Sname AS name ,Ssex AS sex ,Sschool AS school FROM student WHERE Sschool='Tongji' UNION ALL SELECT Tid AS id ,Tname AS name ,Tsex AS sex ,Tschool AS school FROM teacher WHERE Tschool='Tongji' ) t ORDER BY t.id ASC; |

In actual service scenarios, pay attention to the following points when using UNION and UNION ALL: