MDL-42882 upgrade: improved SQL query