Some optimization by reducing number of queries