UNIONS in SQL

Kasim Ali
2 min readNov 20, 2022

--

In this post, we learn about unions in SQL. It has a very specific use case that it fulfils very well.

Learning Objectives:

  • Describe what a UNION is and how it works.
  • Discuss the rules for using UNIONs.
  • Write the correct syntax for a UNION statement.
  • Describe common situations in which UNIONS are useful.
UNIONS in SQL | OnyxWrench

What is a Union?

  • The UNION operator is used to combine the result of two or more SELECT statements.
  • Each SELECT statement within UNION must have the same number of columns.
  • Columns must have similar data types.
  • The columns in each SELECT statement must be in the same order.

UNION Example.

SELECT column_name
FROM table1
UNION
SELECT column_name
FROM table2;

This is what your basic setup will look like.

SELECT City, Country
FROM Customers
UNION
SELECT City, Country
FROM Suppliers
WHERE Country LIKE 'Germany'

And this is what it looks like in practice.

Notice you don’t use an ALIAS for table names and you use the WHERE statement at the end of the entire query.

I would also love to connect on Twitter, LinkedIn or on my Website. I am not sure what value I could provide you with but if you reach out, I would be more than happy to have a conversation or talk about what I have written here.

--

--

No responses yet