Computer Science · Ch 9 — Structured Query Language (SQL)
Union (∪)
Union (∪)
Union (∪)
The UNION operation combines the selected rows from two tables into a single result set. When you apply UNION, every row that appears in either of the two tables is included in the output. A key rule: if the same row exists in both tables, it appears only once in the final result — duplicates are automatically removed.
Think of it like taking two sets and merging them into one. For example, if one set contains students in Dance and another contains students in Music, their union gives you the complete list of students who participate in at least one of the two events. The book illustrates this with a Venn diagram (Figure 9.4) showing two overlapping circles labelled "Dance" and "Music", where the shaded area covering both circles represents the union.
Example with DANCE and MUSIC tables
Consider two relations: DANCE and MUSIC, each storing student participation data with columns SNo, Name, and Class.
Table 9.18: DANCE
| SNo | Name | Class |
|---|---|---|
| 1 | Aastha | 7A |
| 2 | Mahira | 6A |
| 3 | Mohit | 7B |
| 4 | Sanjay | 7A |
Table 9.19: MUSIC
| SNo | Name | Class |
|---|---|---|
| 1 | Mehak | 8A |
| 2 | Mahira | 6A |
| 3 | Lavanya | 7A |
| 4 | Sanjay | 7A |
| 5 | Abhay | 8A |
Notice that Mahira (SNo 2) and Sanjay (SNo 4) appear in both tables. When we apply the UNION operation (written as DANCE ∪ MUSIC), these duplicate rows are listed only once.
Table 9.20: DANCE ∪ MUSIC
| SNo | Name | Class |
|---|---|---|
| 1 | Aastha | 7A |
| 2 | Mahira | 6A |
| 3 | Mohit | 7B |
| 4 | Sanjay | 7A |
| 1 | Mehak | 8A |
| 3 | Lavanya | 7A |
| 5 | Abhay | 8A |
The result has seven rows — the four from DANCE plus the three from MUSIC that were not already present (Mehak, Lavanya, Abhay). Mahira and Sanjay appear only once, even though they were in both original tables. …
Drawn by us to help you understand the concept clearly, and verified to make sure it's accurate. For exams, practice from your textbook's own diagram.
A Venn diagram of the two sets used throughout this section: Music and Dance (students who participate in each activity). For the UNION operation, the ENTIRE area of both circles is shaded — every student who is in Music, in Dance, or in both, counted only once even if they appear in both lists. …
| SNo | Name | Class |
|---|---|---|
| 1 | Aastha | 7A |
| 2 | Mahira | 6A |
| 3 | Mohit | 7B |
| SNo | Name | Class |
|---|---|---|
| 1 | Mehak | 8A |
| 2 | Mahira | 6A |
| 3 | Lavanya | 7A |
| SNo | Name | Class |
|---|---|---|
| 1 | Aastha | 7A |
| 2 | Mahira | 6A |
| 3 | Mohit | 7B |
| 4 | Sanjay | 7A |
| 1 | Mehak | 8A |