Code.is.power
Code.is.power

Reputation: 15

SQL query for non like records

I am a newbie at SQL and trying to wrap my head around something and could use some help.

I have 2 tables (pardon the rough description):

Table 1: |date_val | sec_id |

Table 2: |item_id | sec_id | legal_name | date_val | value |

This is probably going to be really simple to some - but I just can't wrap my head around it. I need a list (put into a new table) of all rows from Table 1 that don't have a corresponding sec_id and date_val combination on table 2. In this case, Table 1 has all the sec_id and date_val combinations that should exist. I just need to find those rows on Table 1 that don't have the same sec_id and date_val on Table 2. I hope this makes sense!

I was thinking WHERE NOT EXIST but sub queries are still a little new to me!

Thanks!

Upvotes: 0

Views: 42

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1270401

WHERE NOT EXISTS is exactly what you want:

select t1.*
from table1 t1
where not exists (select 1
                  from table2 t2
                  where t2.sec_id = t1.sec_id and
                        t2.date_val = t1.date_val
                 );

Note: This assumes that the two columns are not NULL. If you need to handle NULL values, then the logic can be tweaked for that.

Upvotes: 1

Related Questions