Q: How to query selecting name with specific code in field and the same time has no code in the same field Example of my table

Name    Code
Jolas   sd02
Jolas   da014
Albert  cca01
Albert  da014
Julito  sd02
Julito  da014
Vergel  cca01
Vergel  da014

I want to select all da014 without sd02, so my output should be Vergel and Albert because both of them has no SD02
How should i query it
Thanks

A: You can use conditional aggregation based filtering using GROUP BY with HAVING clause:
SELECT Name
FROM your_table_name 
GROUP BY Name
HAVING 
  SUM(Code = 'da014') AND /* Has code `da014` */
  NOT SUM(Code = 'sd02') /* Does not have code sd02 */


A: I generally prefer the group by approach for these types of problems.  But if performance is an issue, then this might be faster with the right indexes:
select t.name
from t
where t.code = 'da014' and
      not exists (select 1 from t t2 where t2.name = t.name and t2.code = 'sd02');

In particular, you want indexes on t(code, name) and t(name, code) -- one is for the outer query and one is for the subquery.
If you do use group by, then filtering before the aggregation can help performance:
select t.name
from t
where t.code in ('da014', 'sd02')
group by t.name
having sum(t.code = 'sd02') = 0;

You only have to check 'sd02'.  If it is not there, then name must have the other code to be processed by the group by.
