For a web application where deleting records happens often, what is the best, if we take performance into consideration?
-
check if the record has any reletaionship with other tables and prevent the user from deleting.
ex : the query will be like this
if not exist(select * from table1 where tableX_id = @id) and not exist(select * from table2 where tableX_id = @id) ... then delete from tableX where id = @idor
-
perform the
deleteand let the RDBMS rais an error due to theforiegn keyconstrainttry{ Service.DeleteRecord(id) }catch{ Handle the error here }in this case the query will be simple
delete from TableX where id = @id
If the goal is to prevent rows from being deleted only in the case where actually running the delete would yield an error because it is referenced by other tables, then I suggest you check for the violation before letting SQL Server check for you. I’ve done some testing on this and letting SQL catch the error or just using TRY/CATCH can be more expensive if you expect even a moderate amount of failures. With the proper indexes in place, the additional cost of performing the check is negligible; however the cost of NOT doing the check is certainly LESS negligible.