Union

This lesson demonstrates how to combine results from several queries.

We'll cover the following...

Union

The UNION clause allows us to combine the results from several queries together. The clause doesn’t join the table but merely clubs the two results together.

Syntax

<Query1>

UNION

<Query2>

Connect to the terminal below by clicking in the widget. Once connected, the command line prompt will show up. Enter or copy and paste the command ./DataJek/Lessons/27lesson.sh and wait for the MySQL prompt to start-up.

Press + to interact
-- The lesson queries are reproduced below for convenient copy/paste into the terminal.
-- Query 1
SELECT FirstName FROM Actors
UNION
SELECT URL FROM DigitalAssets;
-- Query 2
(SELECT CONCAT(FirstName, ' ', SecondName) AS "Actor Name"
FROM Actors
ORDER BY NetworthInMillions DESC
LIMIT 2)
UNION
(SELECT CONCAT(FirstName, ' ', SecondName) AS "ThisAliasIsIgnored"
FROM Actors
ORDER BY NetworthInMillions ASC
LIMIT 2);
-- Query 3
SELECT FirstName, Id FROM Actors
UNION
SELECT FirstName FROM Actors;
-- Query 4
SELECT FirstName, Id FROM Actors
UNION
SELECT FirstName, null FROM Actors;
-- Query 5
SELECT MaritalStatus FROM Actors
UNION
SELECT Gender FROM Actors;
-- Query 6
SELECT MaritalStatus FROM Actors
UNION ALL
SELECT Gender FROM Actors;
-- Query 7
(SELECT CONCAT(FirstName, ' ', SecondName) AS "Actor Name"
FROM Actors
ORDER BY NetworthInMillions DESC LIMIT 2)
UNION
(SELECT NetworthInMillions
FROM Actors
ORDER BY NetworthInMillions ASC);
-- Query 8
(SELECT CONCAT(FirstName, ' ', SecondName) AS "Actor Name"
FROM Actors
ORDER BY NetworthInMillions DESC LIMIT 2)
UNION
(SELECT NetworthInMillions
FROM Actors
ORDER BY NetworthInMillions ASC LIMIT 3);
Terminal 1
Terminal
Loading...
  1. As a contrived example, we’ll write a query that prints all the first names from the Actors table and all the URLs from the DigitalAssets table.

    SELECT FirstName FROM Actors
...
Access this course and 1400+ top-rated courses and projects.