3

I have a table containing a unique ID field. Another field (REF) contains a reference to another dataset's ID field. Now I have to select all datasets where REF points to a dataset that doesn't exist.

SELECT * FROM table WHERE ("no dataset with ID=REF exists")

How can I do this?

Holgerwa
  • 3,430
  • 9
  • 42
  • 50

8 Answers8

22

3 ways

SELECT * FROM YourTable y WHERE NOT EXISTS 
     (SELECT * FROM OtherTable o WHERE y.Ref = o.Ref)

SELECT * FROM YourTable WHERE Ref NOT IN 
     (SELECT Ref FROM OtherTable WHERE Ref IS NOT NULL)

SELECT y.* FROM YourTable y 
LEFT OUTER JOIN  OtherTable o ON y.Ref = o.Ref
WHERE o.Ref IS NULL

See also Five ways to return all rows from one table which are not in another table

SQLMenace
  • 132,095
  • 25
  • 206
  • 225
6

Try this:

SELECT * FROM TABLE WHERE NOT EXISTS 
     (SELECT * FROM OtherTable WHERE TABLE.Ref = OtherTable.ID)
cjk
  • 45,739
  • 9
  • 81
  • 112
5

I think this should work

SELECT * FROM table WHERE id NOT IN (SELECT ref_id FROM ref_table)

or with JOIN

SELECT table.* 
FROM table LEFT JOIN ref_table ON table.id = ref_table.ref_id
WHERE ref_table.ref_id IS NULL
Jhonny D. Cano -Leftware-
  • 17,663
  • 14
  • 81
  • 103
4
SELECT 
 table1.* 
FROM 
 table1
 LEFT JOIN table2 ON table1.id = table2.ref
WHERE 
 table2.ref IS NULL
Jose Basilio
  • 50,714
  • 13
  • 121
  • 117
3

You can do a subquery like:

select * from table where somefield not in (select otherfield from sometable where ID=REF)
Alex Fort
  • 18,459
  • 5
  • 42
  • 51
1
SELECT * 
FROM table 
WHERE ((SELECT COUNT(*) FROM table2 WHERE table2.id = table.ref) = 0)
antonioh
  • 2,924
  • 6
  • 26
  • 28
  • hahaha! -2 points, I'm glad at least the code works even if it's not the neatest, otherwise who knows how many points less! – antonioh Apr 17 '09 at 16:03
1

Something like that :

SELECT * FROM table WHERE ID NOT IN(SELECT REF FROM Table2 )
Canavar
  • 47,715
  • 17
  • 91
  • 122
0

Yes you can use

select * from x where not exist ( select * from y )

Racer SQL
  • 207
  • 1
  • 3
  • 14