Skip to content
Advertisement

How to Use a Subquery in MySQL in the Where clause that is an argument to an OR operator?

I am trying to filter a table for specific markets by using a subquery. I want to include all null values and exclude the markets that are included in the subquery.

SELECT l.market
FROM lease
WHERE l.market != ANY(SELECT market FROM market_cte) OR l.market IS NULL

This query isn’t filtering out the markets I want to get rid of.

SELECT l.market
FROM lease
WHERE l.market NOT IN (SELECT id FROM market_cte) OR l.market IS NULL

And this created a SQL compilation error.

When I list the markets I want to exclude individually, the query works but I am trying to make it more dynamic.

SELECT l.market
FROM lease
WHERE l.market NOT IN (1,2,3) OR l.market IS NULL

Advertisement

Answer

I would just use not exists:

select market
from lease l
where not exists (select 1 from market_cte c where c.id = l.market)

Note that this will allow records where market is null (since, in this case, c.id = l.market will never be fullfilled).

Another option is to use the left join antipattern:

select l.market
from lease l
left join market_cte c on c.id = l.market
where c.id is null
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement