optimize query construction