Improving query to use indexes better. Fixes #5101
Merge pull request #5120 from Hackwar/extensiontable

Improving query to use indexes better. Fixes #5101