I am trying to query all unique city names for one particular state without pulling other states. This is what I am trying to do:
SELECT DISTINCT city_name
FROM table
WHERE state = 'California';
This does not work because there is a San Diego in other states aside from California. How would I query this so that it only gives me city_names unique only to California and not other US states? Can someone please help? Thank you for your time.
SELECT DISTINCT city_name
FROM table
WHERE state = 'California';
The desired output is unique city names only in California and no where else.
2
Answers
This query is using a subquery in the WHERE clause to filter the results from the table "mytable" (aliased as "t1"), by checking that the city_name does not exist in the table with a different state, the subquery uses a NOT EXISTS clause to check that the city_name does not exist in the table "mytable" (aliased as "t2") with a different state than ‘California’.
You can use aggregation and set the conditions in the
HAVING
clause:SUM((state = 'California')::int)
will be1
only forcity_name
s that can be found in'California'
and it will be0
for all othercity_name
s.COUNT(*)
will be1
only forcity_name
s that exist in only 1 state (and it is never0
).The only case that these expressions are equal is when they are both
1
.