I'm not quite sure where this query comes from. At first I thought it is https://github.com/matomo-org/matomo/blob/3.x-dev/plugins/PrivacyManager/LogDataPurger.php#L154-L162 but this query doesn't seem to be executed by a task and only in UI. Not sure where this query is from?
Maybe the query is from https://github.com/matomo-org/matomo/blob/3.12.0-b2/core/DataAccess/RawLogDao.php#L249-L269 ?
It probably be also good to launch this query on the reader, not the writer.