diff --git a/src/query/plan/rule_based_planner.cpp b/src/query/plan/rule_based_planner.cpp index 4c85b7040..33f6463c2 100644 --- a/src/query/plan/rule_based_planner.cpp +++ b/src/query/plan/rule_based_planner.cpp @@ -472,13 +472,7 @@ auto GenReturnBody(LogicalOperator *input_op, bool advance_command, } last_op = new Produce(std::shared_ptr(last_op), body.named_expressions()); - // Where may see new symbols so it comes after we generate Produce. - if (body.where()) { - last_op = new Filter(std::shared_ptr(last_op), - body.where()->expression_); - } // Distinct in ReturnBody only makes Produce values unique, so plan after it. - // Hopefully, it is more efficient to have Filter before Distinct. if (body.distinct()) { last_op = new Distinct(std::shared_ptr(last_op), body.output_symbols()); @@ -498,6 +492,12 @@ auto GenReturnBody(LogicalOperator *input_op, bool advance_command, last_op = new Limit(std::shared_ptr(last_op), body.limit()); } + // Where may see new symbols so it comes after we generate Produce and in + // general, comes after any OrderBy, Skip or Limit. + if (body.where()) { + last_op = new Filter(std::shared_ptr(last_op), + body.where()->expression_); + } return last_op; } diff --git a/tests/unit/query_planner.cpp b/tests/unit/query_planner.cpp index 6992c5c6c..8ec502e1c 100644 --- a/tests/unit/query_planner.cpp +++ b/tests/unit/query_planner.cpp @@ -703,7 +703,7 @@ TEST(TestLogicalPlanner, CreateWithOrderByWhere) { }); auto plan = MakeLogicalPlan(storage, symbol_table, *dba); CheckPlan(*plan, symbol_table, ExpectCreateNode(), ExpectCreateExpand(), acc, - ExpectProduce(), ExpectFilter(), ExpectOrderBy()); + ExpectProduce(), ExpectOrderBy(), ExpectFilter()); } TEST(TestLogicalPlanner, ReturnAddSumCountOrderBy) { @@ -796,7 +796,7 @@ TEST(TestLogicalPlanner, CreateWithDistinctSumWhereReturn) { auto aggr = ExpectAggregate({sum}, {}); auto plan = MakeLogicalPlan(storage, symbol_table, *dba); CheckPlan(*plan, symbol_table, ExpectCreateNode(), acc, aggr, ExpectProduce(), - ExpectFilter(), ExpectDistinct(), ExpectProduce()); + ExpectDistinct(), ExpectFilter(), ExpectProduce()); } TEST(TestLogicalPlanner, MatchCrossReferenceVariable) {