SQL UNION CLAUSE AND UNION ALL CLAUSE – SQL TUTORIAL

SQL UNION Clause:

SQL UNION operator combines the result of two or more SELECT statements.

The SQL UNION operator selects only distinct values by default.

Syntax:

1
SELECT * FROM Table_Name1 UNION SELECT * FROM Table_Name2;

Example:

1
2
3
SELECT * FROM PLAYERS
UNION
SELECT * FROM SCOREBOARD

In the below image, you could find two three SQL statements. First two statements returns the records from tables PLAYERS and SCOREBOARD individually. In the third query, we have used UNION clause with the first two queries. UNION clause combines the first two queries and returns only the distinct values. In the result you could see only the values which are not duplicated.

SQL UNION ALL Clause :

SQL UNION operator combines the result of two or more SELECT statements. If we want to include the duplicate values too then we could use UNION ALL operator.

Syntax:

1
SELECT * FROM Table_Name1 UNION ALL SELECT * FROM Table_Name2;

Example:

1
2
3
SELECT * FROM PLAYERS
UNION ALL
SELECT * FROM SCOREBOARD

In the below image, you could find two three SQL statements. First two statements returns the records from tables PLAYERS and SCOREBOARD individually. In the third query, we have used UNION ALL clause with the first two queries. UNION ALL clause combines the first two queries and returns the values from both the tables which includes duplicate values too (if any).

In the next tutorial, we will see ORDER BY keyword in SQL

Check out the complete SQL Tutorial by clicking on below link:

SQL Tutorial – Complete