Our expert trainers can help you get the best results.
If you would like any further information please contact one of our training advisors.
Where is the SQL Union query used? Well, one of our regular SQL support topics is where an organisation’s data is spread across different data sources and there is a need to combine the results into a single report. A supplementary issue is to identify in the results set just where the data came from. A variation of this theme is where two or more completely different results sets are required from the same data source and they need to be tagged to identify their reason for inclusion in the results.
A SQL Union Query is the solution for this type of problem. It is has a few rules but they are very reasonable.
Multiple select queries on different data sources can be merged together by using the UNION keyword between each query. For example:
Select column1, column2 From table1 Where condition_x UNION Select Column7, column9 From table3 Wherecondition_y UNION ….etc
By including a character description in the SELECT Clause of each Select Query then it becomes possible to identify the individual rows in the results as having come from a particular data source and / or is the result of a specific WHERE condition.
Example:
use pubs go select fname as 'First Name', 'Employee' as 'Source' from employee union ALL select au_fname, 'Author' from authors order by 'First Name'
Results in:
First Name Source Abraham Author ... … Ann Employee Ann Author ... … Maria Employee Maria Employee … … Yoshi Employee
The SQL Union query is a very uesful way to bring together data from different tables into one dataset.