Some changes to reduce many duplicate queries
(cherry picked from commit 90496519dfa9f877e6e85e56c19c78335773d59d)