Brettb.Com
  HOME | ABOUT ME | BIOTECHNOLOGY | ARTICLES | GALLERY | CONTACT
Search: Go
TECHNICAL ARTICLES
 ASP
 ASP.NET
 JavaScript
 Transact SQL
 Other Articles
 Software Reviews

PHOTO GALLERIES
 Canon EOS 300D Samples
 Akihabara Maids!
 More Galleries...

TRAVEL LOG
 2009: China
 2008: Tokyo
 2007: Tokyo
 2006: Hong Kong
 2005: New York City

MORE STUFF
 Search Engine Optimisation
 Build an ASP Search Engine
 My Tropical Fishtank
 Autoglass
 SQL Month Name
 SQL Get Date Today
 SQL Year Month
 Other New Stuff...

POPULAR STUFF
 Regular Expressions
 Index Server & ASP
 JavaScript Ad Rotator

Home > Articles > Transact SQL Programming Articles

Using the Transact SQL Union Statement

The Union clause is a useful Transact SQL statement that allows two or more select queries to be bunched together in a single results set. It is a great function to be able to have in stored procedures that are  used to return results sets for use in web applications and other database driven applications.

The Union clause is really easy to use - you just put the Union keyword between two SQL select statements, e.g.

select ProductID, ProductName from Products_In_Stock

union

select ProductID, ProductName from Products_Out_Of_Stock

The query above therefore returns a single results set containin ProductID and ProductName data columns.

There is no limit to the number of select queries that can be combined using the union operator.

The drawback with the Union clause is that it can only be used to combine two or more select queries that return the same number of data columns. The other consideration is that the Union function will also only work if the columns in the different queries have the same (or compatible) data types. If the data types differ then it might however be possible to make the Union join work if the convert function is used.

Problems can also occur when using union select statements where the columns to be combined have different numerical column data types, such as combining float columns and int columns. In this case, the SQL Server data precedence rules will apply.

Useful Links

  • The SQL Documentation Tool automates the process of writing technical documentation for your Microsoft SQL Server databases. A free trial version is available for download.

  Site Map | Privacy Policy

All content is 1995 - 2012