```
SELECT msg, toDateTime(intDiv(ms, 1000)) AS time
FROM (
    SELECT 'hello' as msg, toUInt64(t)*1000 as ms FROM generateRandom('t DateTime') LIMIT 10
)
ORDER BY msg, time
```

```
/* optimize_redundant_functions_in_order_by=1 -- (default) */

SELECT msg, toDateTime(intDiv(ms, 1000)) AS time
FROM (
    SELECT 'hello' as msg, toUInt64(t)*1000 as ms FROM generateRandom('t DateTime') LIMIT 10
)
ORDER BY msg, time

Query id: 85b48419-d2eb-40e1-9606-088a1136ad6c

┌─msg───┬────────────────time─┐
│ hello │ 2048-05-08 14:54:21 │
│ hello │ 2003-01-25 22:23:27 │
│ hello │ 2049-03-11 15:29:16 │
│ hello │ 2002-04-14 08:17:00 │
│ hello │ 1990-04-22 03:55:27 │
│ hello │ 2034-04-14 21:30:22 │
│ hello │ 2011-11-03 04:36:37 │
│ hello │ 1988-12-06 02:15:03 │
│ hello │ 2017-01-17 14:44:14 │
│ hello │ 2094-05-25 13:22:16 │
└───────┴─────────────────────┘

10 rows in set. Elapsed: 0.002 sec. 


explain syntax SELECT msg, toDateTime(intDiv(ms, 1000)) AS time
 FROM (
     SELECT 'hello' as msg, toUInt64(t)*1000 as ms FROM generateRandom('t DateTime') LIMIT 10
 )
 ORDER BY msg, time

┌─explain──────────────────────────────────┐
│ SELECT                                   │
│     msg,                                 │
│     toDateTime(intDiv(ms, 1000)) AS time │
│ FROM                                     │
│ (                                        │
│     SELECT                               │
│         'hello' AS msg,                  │
│         toUInt64(t) * 1000 AS ms         │
│     FROM generateRandom('t DateTime')    │
│     LIMIT 10                             │
│ )                                        │
│ ORDER BY msg ASC                         │
└──────────────────────────────────────────┘
```

Disabling the optimizer resolves the issue. 
#pragma once
#include <Interpreters/InDepthNodeVisitor.h>
#include <Parsers/ASTFunction.h>
#include <Parsers/ASTIdentifier.h>
#include <Parsers/ASTOrderByElement.h>
#include <Parsers/ASTSelectQuery.h>
namespace DB
{
class RedundantFunctionsInOrderByMatcher
{
public:
    struct Data
    {
        std::unordered_set<String> & keys;
        const Context & context;
        bool redundant = true;
        bool done = false;
        void preventErase()