Select from union tsql

BlargleMonster picture BlargleMonster · Sep 13, 2012 · Viewed 55.9k times · Source

Is it possible to select from the result of a union? For example I'm trying to do something like:

SELECT A
FROM
(
    SELECT A, B FROM TableA
    UNION
    SELECT A, B FROM TableB
)
WHERE B > 'some value'

Am I missing anything or making an assumption about how this works? I'm using MSSQL 2005 so any solution will need to conform to what I can do there.

Answer

Himanshu Jansari picture Himanshu Jansari · Sep 13, 2012

You should give alias to your table. So try this:

SELECT A
FROM
(
    SELECT A, B FROM TableA
    UNION
    SELECT A, B FROM TableB
) AS tbl
WHERE B > 'some value'