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


throw Exception((!input && !input_pipe && storage) ? "Storage " + storage->getName() + " doesn't support PREWHERE" : "Illegal PREWHERE", ErrorCodes::ILLEGAL_PREWHERE);
            
            for (const auto & it : query_analyzer->getExternalTables())
                if (!context->tryResolveStorageID({"", it.first}, Context::ResolveExternal))
                    context->addExternalTable(it.first, std::move(*it.second));
        }
        if (!options.only_analyze || options.modify_inplace)
        {
            if (syntax_analyzer_result->rewrite_subqueries)
            {
                
                interpreter_subquery = joined_tables.makeLeftTableSubquery(options.subquery());
            }
        }
        if (interpreter_subquery)
        {
            
            if (query_analyzer->hasAggregation())
                interpreter_subquery->ignoreWithTotals();
        }
        required_columns = syntax_analyzer_result->requiredSourceColumns();
        if (storage)
        {
            source_header = metadata_snapshot->getSampleBlockForColumns(required_columns, storage->getVirtuals(), storage->getStorageID());
            
            if (row_policy_filter)
            {
                filter_info = std::make_shared<FilterInfo>();
                filter_info->column_name = generateFilterActions(filter_info->actions_dag, row_policy_filter, required_columns);
                source_header = metadata_snapshot->getSampleBlockForColumns(