Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subquery with NOT IN

Tags:

sql

sql-server

I have a table of cities like:

state  city
-----  ----
texas  houston
texas  austin
texas  dallas
texas  san antonio
texas  beaumont
texas  brownsville
texas  el paso
california  anaheim
california  san diego
california  los angeles
california  oakland
california  simi valley
california  san francisco

I need a query to find the states that don't have a city named 'houston' or 'dallas'. My first thought was this

select distinct state from cities where city not in ('houston', 'dallas');

but that won't work. I think I need a subquery and a NOT IN of some sort..

like image 429
user2378895 Avatar asked Jan 08 '23 05:01

user2378895


2 Answers

A way you can do this is with a NOT EXISTS clause:

Select  Distinct State
From    Cities  C1
Where   Not Exists
(
    Select  *
    From    Cities  C2
    Where   C2.City In ('Houston', 'Dallas')
    And     C1.State = C2.State
)
like image 104
Siyual Avatar answered Jan 10 '23 20:01

Siyual


select distinct state from cities where state not in (SELECT state FROM cities WHERE city in ('houston', 'dallas'));
like image 24
aleroot Avatar answered Jan 10 '23 19:01

aleroot