Might be better to do it in batches but not sure how to write that query though. Do I do subqueries?
Discussion
I always find it easier to do recursive queries via API calls instead in code - excluding things like tree parent/child select queries.
Often there is a batch or streaming API that can be used. Unsure for SQLITE.