Dynamically build the query