I would like to know for my scenario, if there are 2 tables:
employee:
id, city, job_level
filters:
city, job_level, some_val
I have a query like:
SELECT *
FROM employee e
WHERE NOT EXISTS(SELECT 1
FROM filters f
WHERE e.city = COALESCE(f.city, e.city)
AND ( f.job_level IS NULL
OR e.job_level = f.job_level ))
If you can see the conditions for both city and job_level work exactly the same way. However, I would like to know which one would perform better. Also, I would like to know the recommended indexes for these tables for such a query.
It isn't going to really make a difference from a performance perspective. You have a complicated WHERE
clause, that already includes an OR
condition. This pretty much precludes using an index.
Given what you are doing with the COALESCE()
, I think OR IS NULL
is clearer.
If you care about performance, you might consider splitting this into multiple comparisons:
WHERE NOT EXISTS (SELECT 1
FROM filters f
WHERE e.city = f.city AND
( f.job_level IS NULL OR e.job_level = f.job_level )
) AND
NOT EXISTS (SELECT 1
FROM filters f
WHERE f.city IS NULL AND
( f.job_level IS NULL OR e.job_level = f.job_level )
)
This can at least take advantage of an index on filters(city, job_level)
.