rewrite query with criteria