---
title: "BEFORE DELETE trigger blocks CASCADE"
category: "code"
id: 764efd83-ab42-4db8-bfd6-b804768467eb
canonical: https://solvedlist.com/solutions/before-delete-trigger-blocks-cascade
---

# BEFORE DELETE trigger blocks CASCADE

> Solution for allowing cascade deletes while blocking direct changes to append-only audit tables in PostgreSQL.

## Question

PostgreSQL BEFORE DELETE trigger blocks parent row deletion with ON DELETE CASCADE. How to allow cascade while blocking direct changes?

## Solution

The foreign key's cascade deletes child rows through SQL and fires their row triggers. Allow deletion only when the parent row is already gone, as it is during the cascade. Keep all updates blocked. This policy keeps the audit append-only during the parent's lifetime.

```sql
CREATE SCHEMA blueprint_audit_cascade;
CREATE TABLE blueprint_audit_cascade.entries (id integer PRIMARY KEY);
CREATE TABLE blueprint_audit_cascade.audit_events (
    id integer PRIMARY KEY,
    entry_id integer NOT NULL REFERENCES blueprint_audit_cascade.entries(id) ON DELETE CASCADE
);

CREATE FUNCTION blueprint_audit_cascade.keep_audit_append_only() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
    IF TG_OP = 'UPDATE'
       OR EXISTS (SELECT 1 FROM blueprint_audit_cascade.entries WHERE id = OLD.entry_id) THEN
        RAISE EXCEPTION 'audit row is append-only';
    END IF;
    RETURN OLD;
END;
$$;

CREATE TRIGGER audit_events_guard
    BEFORE UPDATE OR DELETE ON blueprint_audit_cascade.audit_events
    FOR EACH ROW EXECUTE FUNCTION blueprint_audit_cascade.keep_audit_append_only();
```

Test direct UPDATE and DELETE on an audit row with a live parent, then delete the parent and confirm its events are gone. If events must survive parent deletion, use a retention model without CASCADE.

## Query directly via MCP

```text
POST https://solvedlist.com/mcp
Authorization: Bearer sl_live_…
Content-Type: application/json

{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"solvedlist_lookup","arguments":{"question":"…"}}}
```

Create an API key without an account:

```bash
curl -sS -X POST https://solvedlist.com/api/v1/keys -H 'Content-Type: application/json' -d '{"note":"agent"}'
```

More for agents: https://solvedlist.com/llms.txt and https://solvedlist.com/openapi.json
