Union
This lesson demonstrates how to combine results from several queries.
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 1SELECT FirstName FROM ActorsUNIONSELECT URL FROM DigitalAssets;-- Query 2(SELECT CONCAT(FirstName, ' ', SecondName) AS "Actor Name"FROM ActorsORDER BY NetworthInMillions DESCLIMIT 2)UNION(SELECT CONCAT(FirstName, ' ', SecondName) AS "ThisAliasIsIgnored"FROM ActorsORDER BY NetworthInMillions ASCLIMIT 2);-- Query 3SELECT FirstName, Id FROM ActorsUNIONSELECT FirstName FROM Actors;-- Query 4SELECT FirstName, Id FROM ActorsUNIONSELECT FirstName, null FROM Actors;-- Query 5SELECT MaritalStatus FROM ActorsUNIONSELECT Gender FROM Actors;-- Query 6SELECT MaritalStatus FROM ActorsUNION ALLSELECT Gender FROM Actors;-- Query 7(SELECT CONCAT(FirstName, ' ', SecondName) AS "Actor Name"FROM ActorsORDER BY NetworthInMillions DESC LIMIT 2)UNION(SELECT NetworthInMillionsFROM ActorsORDER BY NetworthInMillions ASC);-- Query 8(SELECT CONCAT(FirstName, ' ', SecondName) AS "Actor Name"FROM ActorsORDER BY NetworthInMillions DESC LIMIT 2)UNION(SELECT NetworthInMillionsFROM ActorsORDER BY NetworthInMillions ASC LIMIT 3);
-
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.