Click here to Skip to main content
15,885,366 members
Articles / Database Development / SQL Server
Tip/Trick

Type Preference with UNION in SQL Server

Rate me:
Please Sign up or sign in to vote.
4.80/5 (2 votes)
10 Dec 2013CPOL1 min read 13.1K   2   4
A scenario with data type of the resultant select columns with UNION.

Introduction 

We generally use a UNION/UNION ALL statement with all the columns in the same order and same type. Using the same type in the column is not a rule. The data types of the selected columns are allowed to differ, and the resultant result type is derived. Below is a scenario where this can get a bit tricky.

Explanation

Check the below script ...

  Image 1

Output =>

ecode fname lname
1 HRfName1 HRlName1
2 HRfName2 HRlName2
101 ACfName1 AClName1
102 ACfName2 AClName2

In the above script, the UNION/UNION ALL statement is used with all the columns in the same order and the same data type. 

In case the data types of the respective select columns are different, the type of the result column(s) is decided based on the type preference.

Check SQL .. 

   Image 2

Output =>

Type of ecode column in result ecode fname lname
int 1 HRfName1 HRlName1
int 2 HRfName2 HRlName2
int 101 ACfName1 AClName1
int 102 ACfName2 AClName2
int 1001 ITfName1 ITlName1
int 1002 ITfName2 ITlName2

So as we see, the type of the resultant column is integer, which is of higher preference than nvarchar (you can refer to the complete list of type preferences at MSDN).

As this conversion is strictly via data type preference, it can be tricky at times, and the implementation may fail with some live data combination...

E.g., see the below SQL .. 

Image 3

Output =>

Conversion failed when converting the nvarchar value 'AC103' to data type int.

In the above case, the conversion failed, as the resultant type is chosen as

int
, and not varchar. This is a tricky scenario which needs to be explicitly taken into account for reviews or testing.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralThoughts Pin
PIEBALDconsult8-Dec-13 4:22
mvePIEBALDconsult8-Dec-13 4:22 
GeneralRe: Thoughts Pin
Amey A khedekar9-Feb-14 18:04
Amey A khedekar9-Feb-14 18:04 
QuestionFormatting Issues Pin
Sampath Lokuge8-Dec-13 1:08
Sampath Lokuge8-Dec-13 1:08 
AnswerRe: Formatting Issues Pin
Amey A khedekar9-Feb-14 18:05
Amey A khedekar9-Feb-14 18:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.