Fix generating invalid query plans