> (though you might want to replace the view reference with a `UNION ALL` to leverage indices.)

To make sure I understand, you mean to perform this `SELECT` statement on each events table separately and `UNION ALL` the results?

> This will only work if I remembered to put `ON DELETE CASCADE` in the environments table definition. If I didn't, you'll need to do this in parts.

The event tables' foreign key reference to the environments table have it, which contradicts what you said but I think that's the way it's supposed to be for this to work.

> Extra points if you figure out a way to delete old environments that were never used...

I came up with:

    DELETE FROM environments
    WHERE id IN
            (SELECT id
            FROM environments LEFT OUTER JOIN events_view
            ON environments.id = events_view.env
            WHERE date IS NULL AND id != ?);

Where `?` refers to the current environment's ID. Note that this is untested (and potentially syntactically incorrect). I tried pretty hard (a couple of hours) to combine your query and mine in an efficient way, but to no avail. If an `OR` is appended to your query and everything up to `id` removed from mine, they can be combined in a rather trivial, silly way though.

Presumably the left outer join will be significantly more expensive than the joins in your query because the indices cannot be used. As such, this orphaned environment query may not be something we want to run every time we delete from the database.

It might be possible to mitigate this expensiveness by running each `SELECT` individually on a temporary table with the results of the `LEFT OUTER JOIN` so that the DB could potentially do all the operations in one pass (assuming this is possible - I'm not very proficient in my DB knowledge).

Alternatively, we can keep some kind of "unused env" metadata table, but that will increase code/schema complexity and make the recording of measurements more expensive (but potentially less impactful than the expensive join above).

Without benchmarking, I personally prefer the idea of deleting the unused environments less often than we delete old events (or do both at the same time but fairly infrequently) as most environments (at least with the current environment representation) will have measurements and thus not be unused. Would you agree?