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


settings.max_block_size,
                0 ,
                settings.max_bytes_before_remerge_sort,
                settings.remerge_sort_lowered_memory_bytes_ratio,
                settings.max_bytes_before_external_sort,
                context->getTemporaryVolume(),
                settings.min_free_disk_space_for_temporary_data);
            merge_sorting_step->setStepDescription(
                "Merge sorted blocks for window '" + w.window_name + "'");
            query_plan.addStep(std::move(merge_sorting_step));
            
            auto merging_sorted = std::make_unique<MergingSortedStep>(
                query_plan.getCurrentDataStream(),
                w.full_sort_description,
                settings.max_block_size,
                0 );
            merging_sorted->setStepDescription(
                "Merge sorted streams for window '" + w.window_name + "'");
            query_plan.addStep(std::move(merging_sorted));
        }
        auto window_step = std::make_unique<WindowStep>(
            query_plan.getCurrentDataStream(),
            w,
            w.window_functions);
        window_step->setStepDescription("Window step for window '"
            + w.window_name + "'");
        query_plan.addStep(std::move(window_step));
    }
}
void InterpreterSelectQuery::executeOrderOptimized(QueryPlan & query_plan, InputOrderInfoPtr input_sorting_info, UInt64 limit, SortDescription & output_order_descr)