smartyfy.mrindigi.com

Databases & SQL Master Course — 054. Targeted DELETE

Lesson 054 Targeted DELETE

DELETE removes selected records, so correctness includes both the removed population and everything that must remain. This lesson rehearses a narrowly defined cleanup in disposable data, verifies relationship constraints, and rolls every change back. It does not authorize cleanup of a real database or establish a retention policy.

Prerequisites and objectives

Complete Lesson 053. You should understand targeted predicates, foreign keys, date-like text, and rollback rehearsals. You will preview deletion targets, verify retained rows, distinguish zero matches from failures, and recognize when a related child record blocks a parent deletion.

Practice safety and transaction preview

Use only a new disposable SQLite database containing the fictional setup below. Every write demonstration starts with BEGIN and ends with ROLLBACK, so its changes are inspected and then undone. Run complete blocks on the same connection, outside any existing transaction. Detailed transaction behavior comes later; this is a controlled rehearsal, not permission to change real data.

PRAGMA foreign_keys = ON;
CREATE TABLE draft_items (
 item_id INTEGER PRIMARY KEY, title TEXT NOT NULL,
 status TEXT NOT NULL, created_day TEXT NOT NULL
);
CREATE TABLE item_notes (
 note_id INTEGER PRIMARY KEY,
 item_id INTEGER NOT NULL REFERENCES draft_items(item_id)
);
INSERT INTO draft_items VALUES
 (1,'Old draft','Draft','2026-01-01'),(2,'New draft','Draft','2026-10-01'),
 (3,'Published guide','Published','2026-01-01'),
 (4,'Another old draft','Draft','2026-02-01'),
 (5,'Archived reference','Archived','2026-01-10');
INSERT INTO item_notes VALUES (1,5);

Step 1 Define a bounded cleanup rule

The fictional exercise selects records whose status is Draft and whose normalized created_day is before 2026-03-01. Both conditions are required. A published item from January must remain, as must a new October draft. IDs 1 and 4 are the intended targets.

The date column uses fixed-width year-first day labels. This comparison is suitable for the controlled fixture, but arbitrary date strings would need validation. A real retention decision also depends on organizational, contractual, or legal requirements that this practice rule does not supply.

Step 2 Preview identities and context

SELECT item_id, title, status, created_day FROM draft_items
WHERE status = 'Draft' AND created_day < '2026-03-01' ORDER BY item_id;

The preview shows two exact records and why each qualifies. Keep those identifiers available for the after-check. Looking only at the count would not reveal whether an incorrect predicate selected two different records.

Step 3 Rehearse the deletion

BEGIN;
DELETE FROM draft_items WHERE status = 'Draft' AND created_day < '2026-03-01';
SELECT item_id, status FROM draft_items ORDER BY item_id;
ROLLBACK;

Inside the transaction, IDs 2, 3, and 5 remain. The new draft and published guide are preserved, and the archived reference is outside the rule. ROLLBACK then restores all five items. A successful deletion statement is not sufficient evidence; the retained population is part of the required result.

The rule requires Draft status AND a date before 2026-03-01. IDs 1 and 4, dated 2026-01-01 and 2026-02-01, are removed during rehearsal. IDs 2, 3 and 5 remain: a new Draft, a Published guide and an Archived reference. Child note 1 still references item 5. Rollback restores all five original records.
Both conditions define the intended two-row population. Successful rehearsal includes the retained records and their dependencies, not just the deletion count. Open full-size diagram

Step 4 Understand deletion scope

DELETE removes rows, not the table definition. The table can remain with zero rows if all its records are intentionally deleted. Omitting WHERE would target every row, so never rely on a familiar table name or an editor’s visual selection as the actual scope restriction.

The rule’s AND matters. Replacing it with OR would include every draft regardless of age and every old item regardless of status. A narrowly written cleanup request can therefore become a broad destructive operation through one logical operator. Reuse the reviewed predicate exactly.

Step 5 Check related records

item_notes contains a child reference to item 5. With foreign-key enforcement enabled and no cascading delete action declared, removing that referenced parent is rejected in this fixture.

BEGIN;
DELETE FROM draft_items WHERE item_id = 5;
SELECT item_id, status FROM draft_items WHERE item_id = 5;
ROLLBACK;

The error is an expected protection, and item 5 remains. If your editor stops at the failed statement, run the inspection and ROLLBACK separately on the same connection. Do not disable foreign keys or delete child records merely to force the parent removal without reviewing the intended lifecycle.

Other schemas can declare cascading actions, so never assume every blocked relationship behaves this way. Inspect the actual definition before a real change. A parent deletion may affect more records than appear in its direct WHERE selection when cascades or triggers exist.

Step 6 Distinguish no-op and failure

A DELETE whose predicate matches no row is a valid zero-change statement. A DELETE rejected by a constraint is a failed attempted change. Both can leave the same row count, but they provide different evidence and need different explanations.

Also distinguish rollback from a general undo promise. These examples deliberately keep changes inside a transaction and then undo them. Once a real deletion is committed, ordinary product recovery, backups, or other mechanisms determine recoverability. Do not claim a later ROLLBACK can reverse an already committed operation.

Step 7 Review the whole change boundary

A safe operational workflow would establish authority, scope, expected effects, dependency behavior, and recovery before executing. It would also account for concurrent changes between preview and deletion. This single-user practice database isolates the SQL mechanics without implying that those broader checks are optional in real work.

For the lesson, verify the two deleted IDs, the three survivors, the protected referenced item, and restoration after rollback. These controls prove a concrete state transition rather than merely showing that a DELETE keyword ran.

Practice with worked solutions

Exercise 1

Rehearse deleting only draft item 1 by identity and confirm item 4 remains.

Worked solution
BEGIN;
DELETE FROM draft_items WHERE item_id = 1 AND status = 'Draft';
SELECT item_id FROM draft_items ORDER BY item_id;
ROLLBACK;

Only ID 1 is removed during the rehearsal. Including status makes the intended eligibility explicit, while the identity limits the target to at most one row.

Exercise 2

Use a future cleanup category that matches nothing and verify the population remains five.

Worked solution
BEGIN;
DELETE FROM draft_items WHERE status = 'Temporary';
SELECT COUNT(*) FROM draft_items;
ROLLBACK;

No fixture row has that status. The statement succeeds as a no-op; it is not the same as the foreign-key rejection demonstrated earlier.

Exercise 3

Count the reviewed old-draft targets without deleting them.

Worked solution
SELECT COUNT(*) AS targets FROM draft_items
WHERE status = 'Draft' AND created_day < '2026-03-01';

Two records qualify. Use this count alongside the identity preview, not instead of it, because equal counts can hide different selected populations.

Exercise 4

Explain why deleting item 5’s child note or disabling foreign keys is not an automatic repair for its blocked deletion.

Worked solution

The constraint exposes a dependency. Removing that dependency changes the scope and potentially loses related information. Review whether the parent should be retained, whether the child has a separate lifecycle, and what action is authorized. A failed parent delete does not supply permission for a broader cleanup.

Knowledge check

Question 1

Which IDs meet the reviewed cleanup rule?

  1. 1 and 4
  2. Every old item
  3. 2 and 3
  4. 3 and 5
Answer and explanation

A. Both Draft status and a date before March 1 are required.

Question 2

What does DELETE remove here?

  1. The table schema
  2. Selected rows
  3. Every related table automatically
  4. Only values in the columns mentioned by WHERE
Answer and explanation

B. The table definition remains unless a separate schema operation changes it.

Question 3

Why is item 5 protected in this fixture?

  1. The DELETE statement targets no matching row
  2. A child foreign-key reference blocks the parent removal
  3. Archived is always undeletable
  4. The date condition prevents its selection
Answer and explanation

B. The enforced relationship, not the text label alone, causes the rejection.

Question 4

Can ROLLBACK undo an already committed real deletion?

  1. Yes, by starting a new empty transaction
  2. Yes, when the same connection remains open
  3. Always
  4. Not as a general later undo mechanism
Answer and explanation

D. The lesson’s rollback works because the rehearsal changes remain in the active transaction.

Question 5

Why verify survivors as well as targets?

  1. To disable constraints
  2. To change retention rules
  3. To detect accidental over-deletion
  4. To generate replacement IDs
Answer and explanation

C. Preserving unrelated records is part of the correctness contract.

Pitfalls and summary

Do not broaden a deletion to overcome a mismatch, ignore dependencies, or promise recovery without evidence. Preview exact identities, inspect relationship effects, and verify both removal and preservation. Keep practice changes reversible within the controlled transaction and real changes within explicit authority.

SQLite behavior and references

Examples were checked with SQLite 3.53.1 on 10 October 2026. Use a SQLite SQL editor; Python is not a prerequisite. Verify dialect-specific functions, comparison rules, and numeric behavior before moving the examples to another engine.

Primary references