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


{
    const Settings & settings = context->getSettingsRef();
    auto finish_sorting_step = std::make_unique<FinishSortingStep>(
            query_plan.getCurrentDataStream(),
            input_sorting_info->order_key_prefix_descr,
            output_order_descr,
            settings.max_block_size,
            limit);
    query_plan.addStep(std::move(finish_sorting_step));
}
void InterpreterSelectQuery::executeOrder(QueryPlan & query_plan, InputOrderInfoPtr input_sorting_info)