Optimize query to database