I want to write a query to fetch records in record table A and but not in table B. As per my current application design, if a record is present in A then it should be present in table B as well. But due to some interfacing issues, not all records of table A are present table B. Now I want to have all those records which are in A but not in B. How can I fetch those records? Any help is appreciated. TIA.
Asked
Active
Viewed 582 times
1 Answers
1
You can use NOT EXISTS
, e.g.:
SELECT *
FROM tableA a
WHERE NOT EXISTS (
SELECT * FROM tableB b WHERE b.a_id = a.id
);

Darshan Mehta
- 30,102
- 11
- 68
- 102
-
Awesome! it worked. But, in my scenario I'll need to check records like this: if records is present in A1 or A2 or A3 but not in B1 and B2. How can I do so? Thanks! – Pushpendra Yadav Jun 01 '17 at 20:06
-
You can use `UNION` in that case, e.g. `SELECT * FROM (SELECT * FROM A1 UNION SELECT * FROM A2 ) a WHERE NOT EXISTS (*uion query for B tables*)`. – Darshan Mehta Jun 01 '17 at 20:35