sql union

In this Step by step SQL Tutorial I will show you a simple example using SQL Union.

Union is used to combine two queries together so they appear as one result set.

 

Below is a simple example where I combine one row with another row using union.

Below are several basic SQL UNION rules (not all):

- Union should have two or more SELECT statement.

- Queries columns must be listed in the same order.

- Column data types must be the same.

 

IMPORTANT: Union shows DISTINCT rows in the final result. This is not always desired behavior so if you need to return exactly the same number of rows from both queries than use UNION ALL

PERFORMANCE: UNION applies DISTINCT; that means it will be slower comparing to UNION ALL that doesn't do that however always ensure you get the expected result.

 

You can also visit SQL UNION ALL Multiple queries issues with last UNION

 

I hope this very simple example of SQL UNION will help you

Take care

Katie 


SHARE:


Name: AJ Fahmy
Comment:

Hey guys, If I may add to the UNION section. UNION selects only distinct values where UNION ALL allow duplicate values


Date Posted: 20/06/2012 3:27:07 PM

Name: Emil
Comment:

Hi

Many thanks for your comment. This is very important and we will update the article to include this and performance implications.

Regards

Emil


Date Posted: 20/06/2012 5:15:03 PM




Disclaimer: While every caution has been taken to provide our readers with most accurate information and honest analysis, please use your discretion before taking any decisions based on the information in this blog. Author will not compensate you in any way whatsoever if you ever happen to suffer a loss/inconvenience/damage because of/while making use of information in this blog.