July 14, 2011 at 6:45 pm
when you do Union all, does the order of the columns matter?
July 14, 2011 at 7:45 pm
July 15, 2011 at 7:11 am
As Ron said, "Yes". You can prove this to yourself by playing around with something like:
DECLARE @Animal1 table (name varchar(20), weight smallint)
INSERT @Animal1 (name, weight) VALUES ('Gazelle', 250),
('Eland', 300),
('Gnu', 450)
DECLARE @Animal2 table (name varchar(20), weight smallint)
INSERT @Animal2 (name, weight) VALUES ('Toad', 2),
('Aligator', 100),
('Salamander', 1)
--
SELECT name, weight
FROM @Animal1
UNION ALL
SELECT weight, name
FROM @Animal2
This code will give an error as you are trying to put a string (varchar) into a number (smallint). The union statement puts the two selects together by order, not by name.
July 15, 2011 at 8:40 am
The order has to be the same in all of the queries you're unioning together. Beyond that, the general order of the columns in the query as a whole doesn't matter.
Gail Shaw
Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability
July 15, 2011 at 2:28 pm
Weird thing you don't have to have the same size of data type.
If you were to explicitly convert the columns to be the same datatype you can, but as you can see
the size I used varchar(8) instead of 20.
SELECT name as 'name', cast(weight as varchar(8)) as 'name'
FROM @Animal1
UNION ALL
SELECT cast(weight as varchar(8)) as 'name2', name as 'weight2'
FROM @Animal2
I believe the main issue is conversion , it is not possbile to convert 'Toad' to an int, if we replace all names with numbers , but leave them as characters it works.
So it doesn't matter which order, it matters how it gets explicity converted.
July 15, 2011 at 3:20 pm
jwbart06 (7/15/2011)
Weird thing you don't have to have the same size of data type.
No, they just have to be implicitly convertable.
Gail Shaw
Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability
Viewing 6 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply