How to make a choice in Select

I have a table containing a unique ID field. Another field (REF) contains a link to another data set ID field. Now I need to select all datasets where REF points to a dataset that does not exist.

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

How can i do this?

+3
sql
Apr 17 '09 at 15:42
source share
9 answers

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 that are not in another table

+21
Apr 17 '09 at 15:49
source share

Try the following:

 SELECT * FROM TABLE WHERE NOT EXISTS (SELECT * FROM OtherTable WHERE TABLE.Ref = OtherTable.ID) 
+6
Apr 17 '09 at 15:45
source share

I think this should work

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

or using join

 SELECT table.* FROM table LEFT JOIN ref_table ON table.id = ref_table.ref_id WHERE ref_table.ref_id IS NULL 
+5
Apr 17 '09 at 15:44
source share
 SELECT table1.* FROM table1 LEFT JOIN table2 ON table1.id = table2.ref WHERE table2.ref IS NULL 
+4
Apr 17 '09 at 15:47
source share

You can execute a subquery, for example:

 select * from table where somefield not in (select otherfield from sometable where ID=REF) 
+3
Apr 17 '09 at 15:45
source share
 SELECT * FROM table WHERE ((SELECT COUNT(*) FROM table2 WHERE table2.id = table.ref) = 0) 
+1
Apr 17 '09 at 15:44
source share

Something like that:

 SELECT * FROM table WHERE ID NOT IN(SELECT REF FROM Table2 ) 
+1
Apr 17 '09 at 15:45
source share

yo dawg i herd u liek selects, so we put select in ur select so you can request the request during the request.

0
Apr 17 '09 at 15:48
source share

Yes you can use

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

0
Dec 18 '14 at 11:12
source share



All Articles