DELETE with Subquery and RETURNING

Uses DELETE with subquery conditions to remove specific rows and RETURNING to capture deleted data for audit logging and referential cleanup.

SqlData Integrity

Code

snippet
BEGIN;

-- Archive deleted records before removing
WITH deleted_orders AS (
    DELETE FROM orders
    WHERE status = 'cancelled'
      AND order_date < CURRENT_DATE - INTERVAL '90 days'
      AND customer_id IN (
          SELECT customer_id
          FROM customers
          WHERE is_active = false
      )
    RETURNING
        order_id,
        customer_id,
        order_date,
        total_amount,
        status
)
INSERT INTO archived_orders (order_id, customer_id, order_date, total_amount, status, archived_at)
SELECT
    order_id,
    customer_id,
    order_date,
    total_amount,
    status,
    CURRENT_TIMESTAMP
FROM deleted_orders;

-- Also clean up related order items
DELETE FROM order_items
WHERE order_id NOT IN (SELECT order_id FROM orders);

COMMIT;

How the snippet works

What runs here is SELECT / INSERT / DELETE — orders, customers, archived_orders, deleted_orders and order_items are the objects involved.

The SQL constructs in play: a CTE (WITH … AS) that names an intermediate result before the main query; a WHERE clause narrowing which rows one statement affects; a RETURNING clause that hands the affected rows back to the caller.

Applying it

The orders table is the working surface here.

Statements that matter

DELETE FROM order_items
WHERE order_id NOT IN (SELECT order_id FROM orders);

Interactive Tools for This Topic

FAQ

What relations does the SQL touch?
The references are `orders`, `customers`, `archived_orders`, `deleted_orders`, `order_items`.