How to Work with Unions in SQL

  • google plus

In Brief...

A common challenge in SQL is to combine the results from two or more selects. For example, we might want to list city name and state abbreviation on one report and then combine that output with a report on state name and state abbreviation. A union operation with solve this challenge!

Take our Introduction to SQL Training course for free.

See the Course Outline and Register

Instructions

To learn how work with unions in SQL, follow these steps:

  1. You'll need to setup the MySQL database tables. The instructions for the setup can be found in How to add comments in simple SQL selects. Follow steps 1 through 7 before proceeding to the next step.
  2. We can now write an a union in a SQL select.
  3. As mentioned above, let's write a union to display the city data combined with the state data. Execute this SQL select statement:
    Union to display city and state data
    What we have are two select statements that are connected with the union keyword. Each select statement must display the same number of columns or expressions. Notice that I have included a literal expression on each select statement in order to make the output more readable (e.g., state data is identified as "State").

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, XML, Windows, Java, Adobe, HTML5, JavaScript, Angular, and much more. Check out our complete course catalog.

Categories

Courses

Author: Stephen Withrow

Stephen has over 30 years' experience in training, development, and consulting in a variety of technology areas including Java, C, C++, XML, JavaScript, AJAX, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen is a published writer in both technical and non-technical endeavors. Stephen received an undergraduate degree in Computer Science and Physics from Florida State University.

Discuss