SQL UNION Operator
Posted on
< Previous Next >
The SQL UNION operator is used to combine the result sets of two or more SELECT statements into a single result set. The UNION operator is used when you want to combine the results of two SELECT statements and remove any duplicate rows.
UNION Syntax
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
For example,
Let's say you have two tables with similar data: one for students in a mathematics class and one for students in an English class. You want to combine the two tables and get a list of all the students in both classes. You can use the UNION operator to do this.
Here's an example of how to use the UNION operator with the student table:
SELECT name FROM student WHERE id <= 3
UNION
SELECT name FROM student WHERE id > 3
OUTPUT

In this example,
The first SELECT statement gets the names of the first three students in the table, and the second SELECT statement gets the names of the students with IDs greater than 3.The UNION operator combines the two result sets into a single result set with all the names. Note that the UNION operator removes any duplicate rows from the result set. If you want to include duplicate rows, you can use the UNION ALL operator instead.
< Previous Next >