**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_plan.addStep(std::move(remove_columns));
            }
        }
    }
    else
    {
        if (prepared_input)
        {
            auto prepared_source_step = std::make_unique<ReadFromPreparedSource>(
                    Pipe(std::make_shared<SourceFromInputStream>(prepared_input)), context);
            query_plan.addStep(std::move(prepared_source_step));
        }
        else if (prepared_pipe)
        {
            auto prepared_source_step = std::make_unique<ReadFromPreparedSource>(std::move(*prepared_pipe), context);
            query_plan.addStep(std::move(prepared_source_step));
        }
        if (from_stage == QueryProcessingStage::WithMergeableState &&
            options.to_stage == QueryProcessingStage::WithMergeableState)
            intermediate_stage = true;
        
        
        if (from_stage == QueryProcessingStage::WithMergeableStateAfterAggregation)
            from_aggregation_stage = true;
        
        if (options.to_stage == QueryProcessingStage::WithMergeableStateAfterAggregation)
            to_aggregation_stage = true;
        if (storage && expressions.filter_info && expressions.prewhere_info)
            throw Exception("PREWHERE is not supported if the table is filtered by row-level security expression", ErrorCodes::ILLEGAL_PREWHERE);