Function for constructing query