SQL has many unique commands that help simplify database commands. SQL’s UNION command allows us to combine the results of two or more database queries that are not necessarily linked through a database relationship. For example, if we have a school database and wish to use it to create a master contact list for all students, faculty and staff that could be difficult. Looking at our database, we can discover that the records corresponding to each of these constituencies appears in separate database tables. Our first impulse might be to export the data from each table into a spreadsheet and combine the information there. However, an easier way would be to combine these records within the database by writing separate queries for each constituency and combining the results of those queries with the UNION statement. The syntax of the UNION statement is the following:
The purpose of the SQL UNION command is to combine the results of two queries together. UNION is somewhat similar to the JOIN command in that they are both used to related information from multiple tables. This command does have some restrictions. One restriction of UNION is that all corresponding columns need to be of the same data type. Also, when using UNION, only distinct values are selected similar to SELECT DISTINCT. Also, each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types and all of the columns in each SELECT statement must be in the same order. There is also a UNION ALL command (Rob and Coronel (2009). The purpose of the SQL UNION ALL command is also to combine the results of two queries together. The difference between UNION ALL and UNION is that, while UNION only selects distinct values, UNION ALL selects all values. The syntax is as follows:
[SQL Statement 1]
[SQL Statement 2] (SQL Book)
Another helpful SQL command is INTERSECT. Similar to the UNION...
References: Rob, P., & Coronel, C. (2009). Database Systems Design, Implementation, and Management (8th ed.). Boston, MA: Thomson Course Technology.
SQL Book. Retrieved from http://www.sqlbook.com/SQL/SQL-UNION-and-UNION-ALL-32.aspx
BLACK WASP. Retrieved from http://www.blackwasp.co.uk/SQLExceptIntersect.aspx
Please join StudyMode to read the full document