diff --git a/src/Processors/QueryPlan/DistinctStep.cpp b/src/Processors/QueryPlan/DistinctStep.cpp index 0628048411a..60966b08beb 100644 --- a/src/Processors/QueryPlan/DistinctStep.cpp +++ b/src/Processors/QueryPlan/DistinctStep.cpp @@ -8,16 +8,16 @@ namespace DB static bool checkColumnsAlreadyDistinct(const Names & columns, const NameSet & distinct_names) { - bool columns_already_distinct = true; - if (columns.size() != distinct_names.size()) { - columns_already_distinct = false; - } else { - for (const auto & name : columns) - if (distinct_names.count(name) == 0) - columns_already_distinct = false; - } + if (distinct_names.empty()) + return false; - return columns_already_distinct; + /// Now we need to check that distinct_names is a subset of columns. + std::unordered_set columns_set(columns.begin(), columns.end()); + for (const auto & name : distinct_names) + if (columns_set.count(name) == 0) + return false; + + return true; } static ITransformingStep::Traits getTraits(bool pre_distinct, bool already_distinct_columns)