Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select from union tsql

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.

like image 606
BlargleMonster Avatar asked Sep 13 '12 04:09

BlargleMonster


People also ask

What is UNION SELECT in SQL?

The UNION operator is used to combine the result-set of two or more SELECT statements. Every SELECT statement within UNION must have the same number of columns. The columns must also have similar data types. The columns in every SELECT statement must also be in the same order.

Why UNION is used in SQL query?

What Is UNION in SQL? The UNION operator is used to combine the data from the result of two or more SELECT command queries into a single distinct result set. This operator removes any duplicates present in the results being combined.

What is Union in SQL with example?

In SQL, the UNION operator selects rows from two or more tables. If rows of tables are the same, those rows are only included once in the result set. For example, SELECT age FROM Teachers UNION SELECT age FROM Students; Run Code.


1 Answers

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' 
like image 84
Himanshu Jansari Avatar answered Oct 02 '22 23:10

Himanshu Jansari