patternMinor
Is it good practice to check for existence of records before deleting them
Viewed 0 times
deletingexistencepracticerecordsforgoodbeforecheckthem
Problem
I've came across the following SQL/PLSQL while investigating a stored procedure written by someone else:
Isn't only the DELETE statement in the line 4 sufficient to cover all the logic that's meant with these 5 lines? I first thought maybe V_COUNT is used somewhere else, but it's not. I can't think of any good reason in making a simple delete statement so complex. Do you also think it's a bad design or is there a point that I can't see?
1. V_COUNT NUMBER(5,0);
.........
2. SELECT COUNT(*) INTO V_COUNT FROM TABLE1 WHERE COL1='SOMEVALUE';
3. IF V_COUNT>0 THEN
4. DELETE FROM TABLE1 WHERE COL1='SOMEVALUE';
5. END IF;Isn't only the DELETE statement in the line 4 sufficient to cover all the logic that's meant with these 5 lines? I first thought maybe V_COUNT is used somewhere else, but it's not. I can't think of any good reason in making a simple delete statement so complex. Do you also think it's a bad design or is there a point that I can't see?
Solution
I would just
Even if I had to only delete if there were say exactly 2 records, then I would add this condition to the where clause, like
In all cases when writing a delete statement consider that in general the where clause is usually either
delete.Even if I had to only delete if there were say exactly 2 records, then I would add this condition to the where clause, like
DELETE FROM table1
WHERE col1='somevalue'
AND (SELECT COUNT(*) FROM table1 WHERE col1 = 'somevalue') = 2;In all cases when writing a delete statement consider that in general the where clause is usually either
- restricting to a single row using a key;
- restricting to a set of rows using a flag/code/status column; or
- restricting to a set of rows using a range of values -- often dates.
Code Snippets
DELETE FROM table1
WHERE col1='somevalue'
AND (SELECT COUNT(*) FROM table1 WHERE col1 = 'somevalue') = 2;Context
StackExchange Database Administrators Q#50553, answer score: 7
Revisions (0)
No revisions yet.