how to find records that violate referential integrity

sql, sql-server

Solution

select *
from table2 t2
where not exists(
    select 1
    from table1 t1
    where t1.AccountId = t2.AccountId
)

Problem

I have two tables that should be in a one-to-many relationship but there seems to be some records on the many side of the table that are preventing the relationship from being created. Violates referential integrity. Since there are lots of records in both tables is there a way to query to see which records are in the many side, but not in the one side? ``` **Ex.** Table 1: (one side) (pk)AccountId Table 2: (many side) (pk)UserId (fk)AccountId <-- Some accountId's are not in Table 1 ```

Original source

Related problems