STATE OF THE UNION

The Library database does not offer us much reason to use UNION, but let's pretend that you want the full list of book titles and author names combined. Perhaps you want to create a master directory, in which you can look up a book either by its title or author, all in one list:

SELECT 
    books.bk_title AS title
FROM books
UNION 
SELECT 
    authors.au_last_name 
FROM authors

UNION does not establish a link, or a connection, between tables; it simply jams them together, one atop another. Note that the syntax of a UNION operation is different from that of a JOIN. UNION reflects the fact that tables are not connected, but merely “glued” together, as shown in Table 7-8.

TABLE 7-8: Result of a UNION Query

TITLE
A Short History of Nearly Everything
After the Gold Rush: Creating a True Profession of Software Engineering
Bach
Bryson
Garrett
Gillenson
Heinlein
Hesse
Jonathan Livingston Seagull
Jones
Kriegel
Letters From Earth
McConnell
Microsoft SQL Server 2000 Weekend Crash Course
Miller
Mindswap
Plew
Ponniah
Powell
Proust
A La Recherche du Temps Perdu
Sheckley
SQL Bible
SQL Functions: Programmers Reference
Stephens
Steppenwolf
Stranger in a Strange Land
Taylor
Trukhnov
Twain
Wiley Pathways: Introduction to Database Management

Note that the book titles and the author names are all in the same single column of the resulting data set, and they are ordered alphabetically, without paying attention whence the ...

Get Discovering SQL: A Hands-On Guide for Beginners now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.