Optimizing the database query