UNION

The UNION statement allows you to perform queries against several tables and return the results in a consolidated set, as in the following example.

SELECT column1, column2 FROM table1 UNION 
SELECT column1, column2 FROM table2;

This will return a result set with three columns containing data from both queries. By default, the UNION statement will omit duplicates between the tables unless the UNION ALL keyword is used. UNION is helpful when the returned columns from the different tables don’t have columns or data that can be compared and joined, or when it prevents running multiple queries and appending the results in your application code.

If column names don’t match, use aliases to give results meaningful headers:

SELECT column1, column2 AS Two, column3 AS Three 
FROM table1 UNION 
SELECT column1, column4 AS Two, column5 AS Three FROM table2;

Leave a Reply

You must be logged in to post a comment.