Let’s say we want to display all the person names available to us. Person names means all the names of students and all the names of authors, in a single result, under a single column.
In this case, we need to include data from two entirely different queries:
SELECT name FROM students
SELECT name FROM authors
and present them together in a single column.
For such a use case, SQL provides a combination clause called
UNION, which helps display data of different types together, from results of two or more queries.
Notice that the results contain 35 rows of names (25 students + 10 authors).
Another key thing to notice about
UNIONs is, the number of columns from each query that constitutes a union, should be equal. Go ahead and run the query below:
We see an error because the first query in the
UNION results produces two columns, while the second one produces only one, which is not acceptable in a