I have Table employee, Table sport that have n to m relations, that's means, i also have one more table, let's say table emp_sport
table employee
emp_id emp_name ------------------ e1 name1 e2 name2 e3 name3 e4 name4 table sport sport_id sport_name --------------------- sp1 spName1 sp2 spName2 sp3 spName3 table emp_sport emp_id sport_id ------------------- e1 sp1 e1 sp2 e1 sp3 e2 sp2
i want to select data from employee like this
select distinct(e.emp_id), e.emp_name
from employee e
where e.emp_id not in (select sp.emp_id from sport_emp sp where sp.sport_id = 'sp1')
the result, i have
e2 name2 e3 name3 e4 name4
the problem is, when i have very huge data in table employee and also emp_sport, query was very slow.
NOT EXISTS (SELECT 1 WHERE ...)
thanNOT IN (SELECT ...)
. Also, yourNOT IN (SELECT ...)
will probably produce unexpected results unlesssp.emp_id
isNOT NULL
. For query performance questions you need to include more information; see stackoverflow.com/tags/postgresql-performance/info for what you need to add by editing your question (not comments). – Craig Ringer Feb 7 '14 at 7:10