tags:

views:

36

answers:

3

Hi,

is there a way to delete a relation only if it exists in the table? If not, Whats the best approach when deleting a relation in a table:

  1. Check if the relation exists. If it does then delete. (2 operations)
  2. Delete and catch the error if it didnt exist. (1 operation)

Thanks

A: 

I think you can do a subselect and choose which record you want to delete from that subselect, something like this

DELETE FROM target WHERE target_table.id IN (
  SELECT target_table.id INNER JOIN relation_table ON relation_table.target_table_id = target_table.id
)

where the subselect, using INNER JOIN will return records with relations =)

hope it helps! =)

Staelen
+4  A: 
DELETE FROM table WHERE id=30

will delete a row if it exists and will do nothing if it is not. No need for catching errors.

vava
In summary, there is no need to check if the row exists before trying to delete it.
Taylor Leese
Nope, if it doesn't exist, nothing will happen.
Ólafur Waage
Understood! Thanks
Emir
+1  A: 

DELETE deletes a row only if it's exist. It doesn't throw an error if there is nothing to delete.

arno