diff --git a/src/Interpreters/InterpreterSelectQuery.cpp b/src/Interpreters/InterpreterSelectQuery.cpp index 3008c55973d..da6ad7ab102 100644 --- a/src/Interpreters/InterpreterSelectQuery.cpp +++ b/src/Interpreters/InterpreterSelectQuery.cpp @@ -1285,8 +1285,11 @@ void InterpreterSelectQuery::executeFetchColumns( const auto & desc = query_analyzer->aggregates()[0]; const auto & func = desc.function; std::optional num_rows{}; + if (!query.prewhere() && !query.where()) + { num_rows = storage->totalRows(settings); + } else // It's possible to optimize count() given only partition predicates { SelectQueryInfo temp_query_info; @@ -1296,6 +1299,7 @@ void InterpreterSelectQuery::executeFetchColumns( num_rows = storage->totalRowsByPartitionPredicate(temp_query_info, *context); } + if (num_rows) { AggregateFunctionCount & agg_count = static_cast(*func); @@ -1790,7 +1794,7 @@ void InterpreterSelectQuery::executeMergeAggregated(QueryPlan & query_plan, bool auto merging_aggregated = std::make_unique( query_plan.getCurrentDataStream(), std::move(transform_params), - settings.distributed_aggregation_memory_efficient, + settings.distributed_aggregation_memory_efficient && storage && storage->isRemote(), settings.max_threads, settings.aggregation_memory_efficient_merge_threads);