-- DELETE orders that are more than 7 years old from the database

BEGIN;
    DELETE FROM order_rows WHERE order_id IN (
        SELECT id FROM orders WHERE inserted < date_trunc('year', now() - interval '7 years')
    );

    DELETE FROM invoices WHERE order_id IN (
        SELECT id FROM orders WHERE inserted < date_trunc('year', now() - interval '7 years')
    );

    DELETE FROM carts WHERE order_id IN (
        SELECT id FROM orders WHERE inserted < date_trunc('year', now() - interval '7 years')
    );

    DELETE FROM orders WHERE inserted < date_trunc('year', now() - interval '7 years');
COMMIT;

DELETE FROM addresses addr WHERE NOT EXISTS (
    SELECT NULL FROM samples s WHERE addr.id = s.address_id
) AND NOT EXISTS (
    SELECT NULL FROM orders o WHERE addr.id = o.billing_address_id OR addr.id = o.delivery_address_id
);
