Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL reduce duplicates in union clause

Tags:

sql

oracle

let's say for example I have the following query:

SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;

As you can see the WHERE Country='Germany' is repeated in both the targets of the union - is there any way to reduce this to a query without repetitions? I don't like my queries being too long.

I'm currently working on Oracle.

like image 269
dk123 Avatar asked Jan 09 '23 15:01

dk123


1 Answers

Why not include the WHERE only once like

SELECT * FROM
(
SELECT City, Country FROM Customers
UNION ALL
SELECT City, Country FROM Suppliers
ORDER BY City
) tab 
WHERE Country='Germany'

(OR) do a JOIN like

SELECT c.City as CustomerCity, c.Country as customerCountry, 
s.City as suppliercity, s.Country as suppliercountry
FROM Customers c
LEFT JOIN Suppliers s ON c.Country = s.Country
AND c.Country='Germany'
ORDER BY c.City;
like image 132
Rahul Avatar answered Jan 18 '23 08:01

Rahul