**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.
```


auto prewhere_required_columns = prewhere_info->prewhere_actions->getRequiredColumns().getNames();
                required_columns_from_prewhere.insert(prewhere_required_columns.begin(), prewhere_required_columns.end());
            }
            
            ASTPtr required_columns_all_expr = std::make_shared<ASTExpressionList>();
            
            ASTPtr required_columns_from_prewhere_expr = std::make_shared<ASTExpressionList>();
            
            
            for (const auto & column : required_columns)
            {
                ASTPtr column_expr;
                const auto column_default = storage_columns.getDefault(column);
                bool is_alias = column_default && column_default->kind == ColumnDefaultKind::Alias;
                if (is_alias)
                {
                    auto column_decl = storage_columns.get(column);
                    column_expr = column_default->expression->clone();
                    
                    replaceAliasColumnsInQuery(column_expr, metadata_snapshot->getColumns(), syntax_analyzer_result->getArrayJoinSourceNameSet(), *context);
                    column_expr = addTypeConversionToAST(std::move(column_expr), column_decl.type->getName(), metadata_snapshot->getColumns().getAll(), *context);
                    column_expr = setAlias(column_expr, column);
                }
                else
                    column_expr = std::make_shared<ASTIdentifier>(column);
                if (required_columns_from_prewhere.count(column))
                {
                    required_columns_from_prewhere_expr->children.emplace_back(std::move(column_expr));
                    if (is_alias)