diff --git a/src/Interpreters/LogicalExpressionsOptimizer.cpp b/src/Interpreters/LogicalExpressionsOptimizer.cpp index 5dd1b510480..78297c0ef5c 100644 --- a/src/Interpreters/LogicalExpressionsOptimizer.cpp +++ b/src/Interpreters/LogicalExpressionsOptimizer.cpp @@ -204,26 +204,41 @@ inline ASTs & getFunctionOperands(const ASTFunction * or_function) bool LogicalExpressionsOptimizer::isLowCardinalityEqualityChain(const std::vector & functions) const { - if (functions.size() > 1) + if (functions.size() <= 1) + return false; + + if (!functions[0]) + return false; + + /// Check if the identifier has LowCardinality type. + auto & first_operands = getFunctionOperands(functions.at(0)); + + if (first_operands.empty()) + return false; + + if (!first_operands[0]) + return false; + + const auto * identifier = first_operands.at(0)->as(); + if (!identifier) + return false; + + auto pos = IdentifierSemantic::getMembership(*identifier); + if (!pos) + pos = IdentifierSemantic::chooseTableColumnMatch(*identifier, tables_with_columns, true); + + if (!pos) + return false; + + if (*pos >= tables_with_columns.size()) + return false; + + if (auto data_type_and_name = tables_with_columns.at(*pos).columns.tryGetByName(identifier->shortName())) { - /// Check if identifier is LowCardinality type - auto & first_operands = getFunctionOperands(functions[0]); - const auto * identifier = first_operands[0]->as(); - if (identifier) - { - auto pos = IdentifierSemantic::getMembership(*identifier); - if (!pos) - pos = IdentifierSemantic::chooseTableColumnMatch(*identifier, tables_with_columns, true); - if (pos) - { - if (auto data_type_and_name = tables_with_columns[*pos].columns.tryGetByName(identifier->shortName())) - { - if (typeid_cast(data_type_and_name->type.get())) - return true; - } - } - } + if (typeid_cast(data_type_and_name->type.get())) + return true; } + return false; } diff --git a/tests/queries/0_stateless/02893_trash_optimization.reference b/tests/queries/0_stateless/02893_trash_optimization.reference new file mode 100644 index 00000000000..573541ac970 --- /dev/null +++ b/tests/queries/0_stateless/02893_trash_optimization.reference @@ -0,0 +1 @@ +0 diff --git a/tests/queries/0_stateless/02893_trash_optimization.sql b/tests/queries/0_stateless/02893_trash_optimization.sql new file mode 100644 index 00000000000..a61bc86eeb9 --- /dev/null +++ b/tests/queries/0_stateless/02893_trash_optimization.sql @@ -0,0 +1,3 @@ +SELECT * +FROM merge('system', '^one$') AS one +WHERE (one.dummy = 0) OR (one.dummy = 1);