Your first instinct might be to export the data from each table into a spreadsheet and combine the information there. However, you can combine these records within your database by writing separate queries for each constituency and combining the results of those queries with the UNION statement.
UNION Statement SyntaxThe syntax of the UNION statement is quite simple:
SELECT_Query_1The two SELECT queries above must meet several requirements:
- They must return the same number of fields.
- The fields must be in the same order.
- The fields must have compatible data types.
UNION Statements by ExampleThe easiest way to understand the UNION statement is through the use of an example. Let’s return to that school database described earlier. We can use the following SQL statement to produce a directory containing the names and telephone numbers of all students, faculty and staff:
SELECT first_name, last_name, telephoneNotice in the example above that the fields do not need to have the same names in each table. As long as the data types are compatible, your database will still be able to combine the results. Additionally, it’s important to point out that the database tables may contain plenty of other information: the UNION statement does not require that the tables be identical in their entirety, only that you include compatible fields in your SELECT statement. Finally, we did not use the ALL keyword in the statement above. Therefore, the database will remove any duplicate results from the output.
SELECT fname, lname, phone
SELECT firstname, lastname, telephone
That’s all there is to the UNION statement. You can use this SQL command to combine results from multiple tables in your relational databases.