The union is a very nice feature to have when working with pulling multiple items from multiple tables. This article is going to go over how to use a union to join information under designated columns.
What is a Union
A union is a feature of sql that allows us to join information from multiple tables and store it into one singular table. There are a few requirements in order to do this properly and if the requirements are not followed you are going to get a few error messages and/or incorrect data returned.
Rules of the Union Operator
1. The union operator requires the same amount of columns.
2. All of the columns need to have the same name.
3. The union operator needs to be placed between queries.
Column Setup
Because you need to have the same amount of columns and the same names for each columns there is a high chance that rather than parsing the content you will just be displaying generic information such as type, title and content.
Note: There is no limit to the amount of queries you are able to union together but it would end up being a rather large query.
An example of a working union operator.
1 2 3 4 5 6 7 8 9 10 11 | SELECT name, job, title, salary FROM job_1_employees WHERE job LIKE ? UNION SELECT name, job, title, salary FROM job_2_employees WHERE job LIKE ? |
In this query we are pulling the information from both tables and merging the content into one large list of company and sub company employees. The search is done based on the like operator.
An example of a broken union operator
1 2 3 4 5 6 7 8 9 10 11 | SELECT book_nid, author, title, YEAR FROM book_listings WHERE title LIKE ? UNION SELECT magazine_nid, publisher, title, YEAR FROM magazine_listings WHERE title LIKE ? |
In order to get a query like this to work properly we are going to have to store the information into some renamed columns to get it to work. Whenever dealing with a work around it is best to create an extra column with a null value rather than changing up the entire query format.
How to Fix the Union Query
1 2 3 4 5 6 7 8 9 10 11 | SELECT book_nid nid, author creator, title, YEAR, 'book' AS TYPE FROM book_listings WHERE title LIKE ? UNION SELECT magazine_nid nid, publisher creator, title, YEAR, 'magazine' AS TYPE FROM magazine_listings WHERE title LIKE ? |
You will notice that we have changed some of the different columns and created another column that will store the type of field that is being returned. This is a good thing to have when you need to create a link to a specific kind of page or display a special icon.


