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


{
                if (required_columns.end() == std::find(required_columns.begin(), required_columns.end(), column.name))
                    required_columns.push_back(column.name);
            }
        }
        
        auto alias_columns_required = false;
        const ColumnsDescription & storage_columns = metadata_snapshot->getColumns();
        for (const auto & column_name : required_columns)
        {
            auto column_default = storage_columns.getDefault(column_name);
            if (column_default && column_default->kind == ColumnDefaultKind::Alias)
            {
                alias_columns_required = true;
                break;
            }
        }
        
        
        
        
        
        
        
        if (alias_columns_required)
        {
            NameSet required_columns_from_prewhere; 
            NameSet required_aliases_from_prewhere; 
            if (prewhere_info)
            {