SQLite Upsert (Insert Or Replace)

It is a bit unusual to do that manually in a trigger. I think if you just set up your FKs the normal way like

Alter Table myRelatedTable add column myFK integer references MainTable ON DELETE CASCADE

you shouldn’t run into the problem you describe at all. Haven’t tested this though…