Click here to Skip to main content
15,901,122 members
Please Sign up or sign in to vote.
1.67/5 (2 votes)
See more:
Hi Everyone, I'm very new to SQL and am having difficulty understanding why my IN and NOT IN clause is returning the same results when I write my query.

I have three tables: TableA,TableB, and TableC. A fourth table has a table of our plants. I am trying to return all the data from TableC that isn't linked to a valid Plants.ID


SQL
SELECT TableC.* FROM TablePlants
  JOIN TableA ON TablePlants.ID = TableA.Plant_ID
  JOIN TableB ON TableA.ID = TableB.TableA_ID
  JOIN TableC ON TableB.ID = TableC.TableB_ID
   WHERE EXISTS( select * FROM TableA 
    WHERE TableA.Plant_ID NOT IN (select TablePlants.ID FROM TablePlants))


Whether I have 'NOT IN' or just 'IN' it returns only those entries which are IN TablePlants.

What am I missing?

Thanks a ton for any help!
Posted

1 solution

SQL
SELECT
  TableC.ID
 --,TableC.SomeColumn1
 --,TableC.SomeColumn2
FROM TableC LEFT JOIN TableB ON TableB.ID = TableC.TableB_ID
 LEFT JOIN TableA ON TableA.ID = TableB.TableA_ID
WHERE TableA.Plant_ID NOT IN (SELECT ID FROM TablePlants)
 --AND TableA.Plant_ID IS NOT NULL --eventually


I encourage you to ban SELECT * from your vocabulary, as it is a quite bad practice :)

If you put some constraint enforcements on your foreign keys, this situation would not happen anymore.

For example
SQL
ALTER TABLE TableA
 WITH CHECK ADD CONSTRAINT FK_TableA_TablePlants
 FOREIGN KEY (Plant_ID)
 REFERENCES TablePlants (ID)
 ON UPDATE CASCADE
 ON DELETE CASCADE --SET DEFAULT could be an option here
GO
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900