Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WHERE statement after a UNION in SQL?

Tags:

sql

mysql

How do I apply a WHERE statement after a UNION in SQL/MySQL?

like image 621
einstein Avatar asked Mar 27 '11 20:03

einstein


People also ask

How do you use WHERE UNION?

If you want to apply the WHERE clause to the result of the UNION, then you have to embed the UNION in the FROM clause: SELECT * FROM (SELECT * FROM TableA UNION SELECT * FROM TableB ) AS U WHERE U.

Can you group after UNION SQL?

You can simple GROUP BY in both tables and then union. But then you'll need another group by anyway, to unite any grouped row from the first table to the one in the second.

How do I count after a union in SQL?

Here is the query to count on the union query. mysql> select count(*) as UnionCount from -> ( -> select distinct UserId from union_Table1 -> union -> select distinct UserId from union_Table2 -> )tbl1; The following is the output displaying the count.


1 Answers

If you want to apply the WHERE clause to the result of the UNION, then you have to embed the UNION in the FROM clause:

SELECT *   FROM (SELECT * FROM TableA         UNION         SELECT * FROM TableB        ) AS U  WHERE U.Col1 = ... 

I'm assuming TableA and TableB are union-compatible. You could also apply a WHERE clause to each of the individual SELECT statements in the UNION, of course.

like image 184
Jonathan Leffler Avatar answered Sep 29 '22 16:09

Jonathan Leffler