i have two queries being combined with a UNION ALL
1:
--Query 1
SELECT Flavor, Color
FROM Friends
--Query 2
SELECT Flavor,
(SELECT TOP 1 Color
FROM Rainbows
WHERE Rainbows.StrangerID = Strangers.StrangerID
ORDER BY Wavelength DESC
) AS Color
FROM Strangers
Both of which, of course, work fine separately, but when combined with a UNION ALL
:
SELECT Flavor, Color
FROM Friends
UNION ALL
SELECT Flavor,
(SELECT TOP 1 Color
FROM Rainbows
WHERE Rainbows.StrangerID = Strangers.StrangerID
ORDER BY Wavelength DESC
) AS Color
FROM Strangers
The query fails with the error:
Msg 104, Level 15, State 1, Line 3
ORDER BY items must appear in the select list if the statement contains a UNION operator.
How do i use an ORDER BY in a statement with a UNION ALL?
Copy-Pasteable Example
CREATE TABLE Friends (Flavor int, Color int)
CREATE TABLE Strangers (Flavor int, StrangerID int)
CREATE TABLE Rainbows (StrangerID int, Color int, Wavelength int)
go
SELECT Flavor, Color
FROM Friends
UNION ALL
SELECT Flavor,
(SELECT TOP 1 Color
FROM Rainbows
WHERE Rainbows.StrangerID = Strangers.StrangerID
ORDER BY Wavelength DESC
) AS Color
FROM Strangers
go
DROP TABLE Rainbows
DROP TABLE Strangers
DROP TABLE Friends
Server: Msg 104, Level 15, State 1, Line 2
ORDER BY items must appear in the select list if the statement contains a UNION operator.
Footnotes
- 1Contrived hypothetical example. Or not.