Combining Sets: UNIONOne more problem about bicycles and helmets, then we'll pedal on to the next chapter. Let's say you're trying to solve this request, which looks simple enough on the surface."Show me the orders that contain either a bike or a helmet."
Actually, that works just fine! So why use a UNION to solve this problem? The truth is, you probably would not. However, if we make the problem more complicated, a UNION would be useful."List the customers who ordered a bicycle together with the vendors who provide bicycles."Unfortunately, answering this request involves creating a couple of queries using JOIN operations, then using UNION to get the final result. Because we haven't shown you how to do a JOIN yet,we'll save solving this problem for Chapter 10. Gives you something to look forward to, doesn't it? Let's get back to the "bicycles or helmets"problem and solve it with a UNION. If you visualize orders with bicycles and orders with helmets as two distinct sets, then you'll find it easier to understand the problem. Figure 7-11 shows you one possible relationship between the two sets of orders.Figure 7-11 Orders for bicycles or helmetsSeeing "either,""or," or "together" in your request suggests that you'll need to break the solution into separate sets of data and then link the two sets with a UNION. This particular request can be broken into two parts."Show me the orders that contain a bike."
"Show me the orders that contain a helmet."
Now you're ready to get the final solution by using-you guessed it-a union of the two sets. Figure 7-12 shows the SQL syntax diagram that handles this problem.Figure 7-12 Linking two SELECT statements with UNIONYou can now take the two parts of your request and link them with a UNION operator to get the correct answer.
The good news is that most commercial implementations of SQL support the UNION operator. As is perhaps obvious from the examples, a UNION might be doing it the hard way when you want to get an "either-or" result from a single table. UNION is most useful for compiling a list from several similarly structured but different tables.We'll explore UNION in much more detail in Chapter 10.