UNION: Uniting Data with UNION in SQL: A Beginner’s Guide

Learn SQL with Udemy

For an instructor lead, in-depth look at learning SQL click below.


Welcome to this beginner’s guide for using the UNION operator in SQL! UNION is a very useful SQL operand that lets you combine the result sets of two or more SQL queries.

What is UNION?

UNION is a SQL command that combines the results of two SELECT queries into a single result set. The two SELECT queries that UNION combines must return the same number of columns, and corresponding columns must be of compatible data types.

Basic Syntax

How does UNION Work?

UNION eliminates duplicate rows from the results. If you have duplicate rows in your result set and you want to keep them, you should use UNION ALL instead.

UNION vs UNION ALL

The difference between UNION and UNION ALL is that UNION ALL will not eliminate duplicate rows, instead it just pulls all rows from all tables fitting your query specifics and combines them into a table of all results.

Example: Using UNION

Let’s see how UNION works through an example. Assuming we have two tables: Students and Teachers. Both the tables have similar columns: name, age, and city.

This query will return a list of all the names, ages, and cities from both the Students and Teachers tables, but it will eliminate any duplicates.

Example: Using UNION ALL

If we want to keep the duplicates, we should use UNION ALL.

This query will return a list of all the names, ages, and cities from both the Students and Teachers tables, with any duplicates included.

Concluding Thoughts

As you can see, UNION and UNION ALL are very powerful tools in SQL. They allow you to combine data from multiple tables, which is essential for creating complex reports and performing advanced analytics. Remember that practicing is the key to mastering these commands, so keep experimenting with different queries!

Leave a Comment