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,390
  • 7
  • 41
  • 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
  • 128,762
  • 24
  • 200
  • 224
6

Try this:

SELECT * FROM TABLE WHERE NOT EXISTS 
     (SELECT * FROM OtherTable WHERE TABLE.Ref = OtherTable.ID)
cjk
  • 44,524
  • 9
  • 79
  • 111
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,104
  • 14
  • 80
  • 102
4
SELECT 
 table1.* 
FROM 
 table1
 LEFT JOIN table2 ON table1.id = table2.ref
WHERE 
 table2.ref IS NULL
Jose Basilio
  • 49,569
  • 12
  • 117
  • 116
3

You can do a subquery like:

select * from table where somefield not in (select otherfield from sometable where ID=REF)
Alex Fort
  • 17,823
  • 5
  • 41
  • 51
1
SELECT * 
FROM table 
WHERE ((SELECT COUNT(*) FROM table2 WHERE table2.id = table.ref) = 0)
antonioh
  • 2,914
  • 6
  • 25
  • 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,036
  • 17
  • 87
  • 121
0

Yes you can use

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

Racer SQL
  • 167
  • 2
  • 13