5

I think this is newbie ask. How to delete row if id doesn't exist in other table? My thought is fetch the ids first and delete. I'm looking for better querying.

1
  • MyISAM or Innodb tables? This changes the response considerably. Commented Jul 29, 2011 at 8:22

1 Answer 1

11

You can set foreign keys to these tables.

More info here

for simple query, here it is:

 DELETE FROM table WHERE (SELECT count(1) FROM table2 WHERE id = table.id) < 1
Sign up to request clarification or add additional context in comments.

2 Comments

I also found this useful - thank you. I knew it would be a subquery, but I couldn't think how to write it. Edit, for those interested I'm using MySQL.
Is there any reason why you used COUNT? That query will have to go through all of table2's rows to count how many occurrences of id there are. Using EXISTS would have been a lot more efficient as the query would stop as soon as it finds the first ocurrence: DELETE FROM table WHERE NOT EXISTS (SELECT 1 FROM table2 WHERE id = table.id)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.