Writing Soft Delete Code With LLMs in November 2026: Use a deleted_at Timestamp, Filter Deleted Rows by Default, and Fix Unique Constraints Before They Block New Records

"Don't actually delete it, just hide it" is one of the most common requests in application code. Users want an undo button, support wants to recover the project someone removed by accident, and finance wants old invoices to keep pointing at the customer who closed their account. The usual answer is a soft delete: instead of removing the row, you mark it as deleted and stop showing it.

Ask an LLM to "add soft delete to the Project model" and you will get something that looks finished in a minute: an is_deleted column, a delete method that flips it, and one list query that filters it out. The trouble is everything the model did not touch. The detail page still loads deleted projects by ID. The search endpoint still returns them. The unique index on the project name still blocks anyone from reusing a name that only exists in the trash. Child rows that used to be removed by ON DELETE CASCADE are now orphaned in plain sight.

This post covers how to get an LLM to write soft delete code that holds up: a timestamp column, a filter that applies everywhere by default, unique constraints that ignore deleted rows, an explicit plan for related records, and a real purge job. The SQL examples use PostgreSQL, with notes for MySQL and common ORMs.

Decide whether you need soft delete at all

Soft delete is not free. Every query on the table has to remember the filter, the table keeps growing, and deleted data is still data you are responsible for. Before you ask a model to add it, write down which of these you actually need:

  • Undo or a trash view. Users can restore something for a limited time, such as 30 days.
  • Keeping references intact. Orders, invoices, or audit records must keep pointing at a row that is no longer active.
  • Support recovery. Staff can bring back something deleted by mistake.

If the real need is history ("who changed what, when"), an audit log or history table is usually a better fit than keeping dead rows in the live table. If the data is personal and the user asked for it to be erased, a soft delete is not an erasure. It hides the row from your UI while every byte stays in the database and backups. Say this to the model up front so it does not propose soft delete as a privacy feature.

A lost and found box

A soft delete is a lost and found box: things are out of sight, but still there until someone clears it out. Image: Lost and Found Box by Paul Gorbould, CC BY 2.0, via Wikimedia Commons.

Give the model the context it cannot guess

The quality of soft delete code depends on facts about your codebase that the model does not have. Put them in the prompt:

  • The table definition, including every unique constraint, index, and foreign key that touches it.
  • Your database and version, and your ORM or query layer.
  • Every place the table is read: list endpoints, detail endpoints, search, counts, exports, background jobs, admin screens, and reports. A quick grep for the table and model name gives you this list.
  • What should happen to child records when the parent is deleted.
  • How long deleted rows should be kept before they are removed for real.

A prompt that works well looks like this:

Add soft delete to the "projects" table (PostgreSQL 16, Django 5).
Schema and constraints are below. Reads happen in these places: [list].
Requirements:
- Use a nullable deleted_at timestamptz column, not a boolean.
- Deleted projects must be invisible by default everywhere, including
  lookups by ID and foreign key access from tasks.
- Project names are unique per workspace among active projects only.
- Deleting a project soft-deletes its tasks in the same transaction.
- Restoring a project restores only the tasks deleted with it.
- A daily job hard-deletes projects deleted more than 30 days ago.
List every read path you changed and every one you think I missed.

That last line matters. Models are good at finding the obvious query and quiet about the five others. Asking for a list of read paths turns the gaps into something you can check.

Use a timestamp, not a boolean

An is_deleted boolean tells you that a row is gone. A deleted_at timestamp tells you that and when, which you need for the trash view ("deleted 3 days ago"), for restore rules, and for the purge job. NULL means active.

ALTER TABLE projects ADD COLUMN deleted_at timestamptz;
ALTER TABLE projects ADD COLUMN deleted_by bigint REFERENCES users(id);

Adding a nullable column with no default is a fast metadata change in PostgreSQL, so this is safe on a large table. If the model suggests a DEFAULT false boolean plus a separate timestamp, push back: two columns that must agree will eventually disagree.

The delete itself becomes an update. Make it conditional so deleting twice does not overwrite the original timestamp:

UPDATE projects
SET deleted_at = now(), deleted_by = %(user_id)s
WHERE id = %(id)s AND workspace_id = %(workspace_id)s AND deleted_at IS NULL;

Make the filter the default, not a habit

The most common soft delete bug is a query that forgot WHERE deleted_at IS NULL. You will not fix that by asking developers, or a model, to remember. Put the filter somewhere it applies automatically, and make reading deleted rows the thing that takes extra effort.

In the database: a view

One reliable approach is to rename the table and put a view in its place:

ALTER TABLE projects RENAME TO projects_all;
CREATE VIEW projects AS
  SELECT * FROM projects_all WHERE deleted_at IS NULL;

Existing queries against projects now see only active rows. In PostgreSQL a simple single-table view like this is automatically updatable, so inserts and updates through it still work. The trash screen and the purge job read projects_all directly. One catch: SELECT * in a view is expanded when the view is created, so a column added to the table later will not show up in the view until you recreate it. Ask the model to include that step in your migration template.

In the ORM: a default scope or manager

If you would rather keep this in application code, every major ORM has a hook, and every one has an edge case the model may skip:

  • Django: a custom manager as the default objects that filters deleted_at__isnull=True, plus a separate all_objects manager. Check forward foreign key access, such as task.project: Django uses the model's base manager for that, not your default manager, so it can still return a deleted project unless you handle it.
  • SQLAlchemy: a do_orm_execute event that adds with_loader_criteria for soft-deletable models covers ORM selects and relationship loads. Raw text() SQL is not covered.
  • Rails: default_scope works but leaks into new and create and is easy to forget when you call unscoped. Many teams prefer an explicit kept scope from a gem like discard and a lint rule or review checklist.
  • Prisma and similar query builders: a client extension or middleware can rewrite findMany and findUnique, but raw queries bypass it.

Whatever you pick, ask the model to name the paths that bypass it in your stack: raw SQL, reporting queries, bulk updates, and database-level jobs. Those are where deleted rows leak back out.

Lookups by ID return 404

Fetching /projects/42 for a deleted project should behave like the project does not exist, usually a 404. If you return 403 or a "this project was deleted" page to people who are not allowed to see the trash, you confirm that the ID was once valid. Owners who can restore it should reach it through the trash view, which reads deleted rows on purpose.

Fix unique constraints so deleted rows do not block new ones

Suppose project names are unique per workspace. With soft delete, a user deletes "Website Redesign", then tries to create a new "Website Redesign" and gets a duplicate key error, because the old row is still there. The model often misses this because the code it wrote never touched the constraint.

In PostgreSQL, replace the constraint with a partial unique index that only covers active rows:

ALTER TABLE projects_all DROP CONSTRAINT projects_workspace_id_name_key;
CREATE UNIQUE INDEX projects_active_name_uniq
  ON projects_all (workspace_id, lower(name))
  WHERE deleted_at IS NULL;

On a big, busy table, build the index with CREATE UNIQUE INDEX CONCURRENTLY first and drop the old constraint after, so writes are not blocked during the build. MySQL has no partial indexes. A common workaround there is a generated column that holds the name for active rows and NULL for deleted ones, with a unique index on that column plus the workspace ID; InnoDB unique indexes allow multiple NULLs.

While you are here, the same idea applies to performance. If most queries only touch active rows, partial indexes with WHERE deleted_at IS NULL stay smaller and faster than full ones as the trash grows.

Old wooden archive boxes on shelves

Kept records need clear labels and rules for when they finally go. Image: Einsiedeln Abbey-old wooden archive boxes-2 by MHM55, CC BY-SA 4.0, via Wikimedia Commons.

Plan what happens to related records

ON DELETE CASCADE fires on a real DELETE. It does nothing when you update deleted_at. So when a project is soft-deleted, its tasks, comments, and file attachments are still active rows unless your code handles them. Decide for each relationship and tell the model:

  • Cascade the soft delete. Tasks belong to the project and should disappear with it. Update them in the same transaction.
  • Leave alone. Invoices that reference a deleted customer stay as they are, because they are records of something that happened.
  • Block. A workspace with active billing cannot be deleted until billing is cancelled.

For cascades, record which delete removed each child. The simplest way is to reuse the parent's exact timestamp:

BEGIN;
UPDATE projects_all SET deleted_at = %(ts)s
  WHERE id = %(id)s AND deleted_at IS NULL;
UPDATE tasks SET deleted_at = %(ts)s
  WHERE project_id = %(id)s AND deleted_at IS NULL;
COMMIT;

Because tasks that were already deleted keep their earlier timestamp, a restore can bring back only the tasks that went away with the project. Some teams use a separate deletion_batch_id column for the same purpose, which is clearer when deletes can span many tables.

Write restore as carefully as delete

Restore looks like setting deleted_at back to NULL, but it has its own failure cases. Ask the model to handle them explicitly:

  1. Uniqueness conflicts. Someone created a new "Website Redesign" while the old one was in the trash. Restoring the old one will hit the partial unique index. Catch that error and ask the user to rename, rather than returning a 500.
  2. Deleted parents. Restoring a task whose project is still deleted should either be blocked or restore the project too. Pick one.
  3. Permissions. Check that the person restoring is still allowed to act on the workspace. They may have lost access since the delete.
  4. Retention window. If the purge job runs after 30 days, the restore endpoint should refuse rows that are past that point, even if the purge has not run yet.

Purge for real, in batches

Soft-deleted rows should not live forever. A scheduled job should hard-delete rows past the retention window, along with anything stored outside the database such as uploaded files. Do it in small batches so one run does not lock the table:

DELETE FROM projects_all
WHERE id IN (
  SELECT id FROM projects_all
  WHERE deleted_at < now() - interval '30 days'
  ORDER BY id
  LIMIT 1000
);

Run that in a loop until it deletes zero rows, with a short pause between batches. Here ON DELETE CASCADE on the foreign keys does help, because this is a real delete. Make sure the job deletes stored files before or alongside the rows that reference them, otherwise you lose track of which files to remove. If a user asks for their data to be erased, that request should go through the purge path right away, not wait out the trash window.

Test the paths the model did not mention

Most soft delete bugs are leaks, so the most useful tests create a row, soft-delete it, and then check every read path:

  • The list endpoint does not include it, and total counts and pagination ignore it.
  • The detail endpoint returns 404 by ID.
  • Search, autocomplete, exports, and reports do not include it.
  • Child rows deleted with it are hidden, and children deleted earlier stay deleted after a restore.
  • A new row with the same unique name can be created, and restoring the old one with a conflict returns a clear error.
  • The purge job removes rows past the window and leaves newer ones.

You can ask the model to generate these tests, but give it the full list of read paths from your grep, not just the ones it changed.

A review checklist

  • Is there a single nullable deleted_at column, with the delete update guarded by deleted_at IS NULL?
  • Is the active-only filter applied by default (view, manager, or scope), and are the bypasses listed?
  • Do foreign key lookups and joins from other tables respect it?
  • Are unique constraints replaced with partial indexes, or the MySQL equivalent?
  • Is each relationship's behavior on delete decided, and done in one transaction?
  • Does restore handle name conflicts, deleted parents, permissions, and the retention window?
  • Is there a batched purge job that also removes stored files?
  • Is it clear to everyone that soft delete is not erasure?

The short version

LLMs write the delete method for soft delete easily. What they skip is the rest of the system: the detail lookup, the search index, the unique constraint, the cascades, the restore conflicts, and the purge. Give the model your schema and every read path, ask for a deleted_at timestamp with a default filter, partial unique indexes, explicit child handling, a careful restore, and a batched purge, and then test every read path with a deleted row before you ship.

Comments

Popular posts from this blog

Grok Bot - a step closer to AGI

Tencent Hy4 Preview: Open 770B MoE Built for Real Work

Structured Outputs and Constrained Decoding for Reliable LLM APIs in Production (September 2026)