SQL Server Union query

No.of Views875
Bookmarked0 times
Downloads 
Votes0
By  youngmurukan   On  15 Feb 2010 21:02:15
Tag : Sql Servers , T-SQL
SQL Server Union query
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 Many time we require results from different tables or different queries. We try one after the other and list the result accordingly. There is a better way to do this by using UNION command or query. We can list records of two different tables by combining two sql queries to one.
What is the advantage ?

We can as well write the query two times and display one after the other. The point here is we can pick up unique records also. Say we have two tables one is storing name of the football players and other is storing players of baseball team. We want to display a list of players who are member of one of the team at least. Here we can display the name of the players by using UNION command. If John is member of football and baseball team then his name will appear once only. If we want to display all the records then we can use ALL along with the UNION command.

Here are two tables with three records each. Please note that there is one common record . Name Alex is there in both the tables.
BaseballFootball
name age
Reid16
Alex21
Greek19
name age
John20
Alex21
Robort23


SELECT name,age FROM football
UNION
SELECT name,age FROM baseball




OUT put is >
name age
John20
Alex21
Robort23
Reid16
Greek19
You can see from the above output that only unique records are displayed so the record Name Alex is displayed once. If the requirement is to display all the records then we have to add ALL command to the UNION query

SELECT name,age FROM football
UNION ALL
SELECT name,age FROM baseball




OUT put is >
name age
John20
Alex21
Robort23
Reid16
Alex21
Greek19
 
Sign Up to vote for this article
 
About Author
 
youngmurukan
Occupation-Not Provided
Company-Not Provided
Member Type-Senior
Location-Not Provided
Joined date-12 May 2009
Home Page-Not Provided
Blog Page-Not Provided
 
 
Other popularSectionarticles
Comments
By:RRaveenDate Of Posted:1/1/2011 2:10:46 AM
More about
Hi Swathi, Please give more details about your question.if i'm not wrong your face same problem what i have given solutions here.if not please post your problem in our messageboard. we will try to help. Thak you
By:swathiDate Of Posted:12/31/2010 3:11:51 AM
Child list for field app cannot be created.
please tell
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top