Fix some bugs in the query creation