**How to reproduce**
Clickhouse version 21.2-21.3

```
SELECT x
FROM
(
    SELECT 1 AS x
    UNION DISTINCT
    SELECT 1
)
LIMIT 1

Query id: b82bbb8d-dea9-4f1c-9a2f-5b0e9b6c2422


0 rows in set. Elapsed: 0.002 sec.

Received exception from server (version 21.2.3):
Code: 49. DB::Exception: Received from localhost:9000. DB::Exception: Bad cast from type DB::ASTSelectWithUnionQuery to DB::ASTSelectQuery.
```


query_info.view_query = view->restoreViewName(getSelectQuery(), view_table);
            view = nullptr;
        }
        if (try_move_to_prewhere && storage && !row_policy_filter && query.where() && !query.prewhere() && !query.final())
        {
            
            if (const auto & column_sizes = storage->getColumnSizes(); !column_sizes.empty())
            {
                
                std::unordered_map<std::string, UInt64> column_compressed_sizes;
                for (const auto & [name, sizes] : column_sizes)
                    column_compressed_sizes[name] = sizes.data_compressed;
                SelectQueryInfo current_info;
                current_info.query = query_ptr;
                current_info.syntax_analyzer_result = syntax_analyzer_result;
                MergeTreeWhereOptimizer{current_info, *context, std::move(column_compressed_sizes), metadata_snapshot, syntax_analyzer_result->requiredSourceColumns(), log};
            }
        }
        query_analyzer = std::make_unique<SelectQueryExpressionAnalyzer>(
                query_ptr, syntax_analyzer_result, *context, metadata_snapshot,
                NameSet(required_result_column_names.begin(), required_result_column_names.end()),
                !options.only_analyze, options, std::move(subquery_for_sets));
        if (!options.only_analyze)
        {
            if (query.sampleSize() && (input || input_pipe || !storage || !storage->supportsSampling()))
                throw Exception("Illegal SAMPLE: table doesn't support sampling", ErrorCodes::SAMPLING_NOT_SUPPORTED);
            if (query.final() && (input || input_pipe || !storage || !storage->supportsFinal()))
                throw Exception((!input && !input_pipe && storage) ? "Storage " + storage->getName() + " doesn't support FINAL" : "Illegal FINAL", ErrorCodes::ILLEGAL_FINAL);
            if (query.prewhere() && (input || input_pipe || !storage || !storage->supportsPrewhere()))