Repository: tobymao/sqlglot

Issue:
ORDER BY in CTE not working
This is not working:

```
WITH
  cte1 AS(
    (
      SELECT
        *
      FROM
        table_1
      UNION ALL
      SELECT
        *
      FROM
        table_2
    )
    ORDER BY
      time_updated
  ),
SELECT
  *
FROM
  cte1
```


Discussion:

Resolving patch:
diff --git a/sqlglot/expressions.py b/sqlglot/expressions.py
--- a/sqlglot/expressions.py
+++ b/sqlglot/expressions.py
@@ -1328,7 +1328,13 @@ def selects(self):
 
 
 class Subquery(DerivedTable):
-    arg_types = {"this": True, "alias": False}
+    arg_types = {
+        "this": True,
+        "alias": False,
+        "order": False,
+        "limit": False,
+        "offset": False,
+    }
 
     def unnest(self):
         """
diff --git a/sqlglot/generator.py b/sqlglot/generator.py
--- a/sqlglot/generator.py
+++ b/sqlglot/generator.py
@@ -556,9 +556,12 @@ def placeholder_sql(self, *_):
     def subquery_sql(self, expression):
         alias = self.sql(expression, "alias")
         alias = f" AS {alias}" if alias else ""
+        order = self.sql(expression, "order")
+        limit = self.sql(expression, "limit")
+        offset = self.sql(expression, "offset")
         if self.pretty:
-            return f"{self.wrap(expression)}{alias}"
-        return f"({self.sql(expression, 'this')}){alias}"
+            return f"{self.wrap(expression)}{alias}{order}{limit}{offset}"
+        return f"({self.sql(expression, 'this')}){alias}{order}{limit}{offset}"
 
     def qualify_sql(self, expression):
         this = self.indent(self.sql(expression, "this"))
diff --git a/sqlglot/parser.py b/sqlglot/parser.py
--- a/sqlglot/parser.py
+++ b/sqlglot/parser.py
@@ -233,6 +233,7 @@ class Parser:
         "_curr",
         "_next",
         "_prev",
+        "_return_subquery",
     )
 
     def __init__(
@@ -257,6 +258,7 @@ def reset(self):
         self._curr = None
         self._next = None
         self._prev = None
+        self._return_subquery = False
 
     def parse(self, raw_tokens, sql=None):
         """
@@ -422,8 +424,13 @@ def _parse_statement(self):
                 expression=self._parse_string(),
             )
 
+        # the initial expression may be a subquery so we want to override the default
+        # behavior of returning a Paren object.
+        self._return_subquery = True
+        expression = self._parse_expression()
+        self._return_subquery = False
         return (
-            self._parse_set_operations(self._parse_expression()) or self._parse_with()
+            self._parse_set_operations(expression) if expression else self._parse_with()
         )
 
     def _parse_drop(self):
@@ -777,11 +784,7 @@ def _parse_select(self):
         if self._match(TokenType.L_PAREN):
             this = self._parse_table()
             self._match_r_paren()
-            this = self.expression(
-                exp.Subquery,
-                this=this,
-                alias=self._parse_table_alias(),
-            )
+            this = self._parse_subquery(this)
 
         if self._match(TokenType.SELECT):
             hint = self._parse_hint()
@@ -816,6 +819,16 @@ def _parse_select(self):
 
         return self._parse_set_operations(this)
 
+    def _parse_subquery(self, this):
+        return self.expression(
+            exp.Subquery,
+            this=this,
+            alias=self._parse_table_alias(),
+            order=self._parse_order(),
+            limit=self._parse_limit(),
+            offset=self._parse_offset(),
+        )
+
     def _parse_annotation(self, expression):
         if self._match(TokenType.ANNOTATION):
             return self.expression(
@@ -1030,7 +1043,7 @@ def _parse_order(self, this=None):
         )
 
     def _parse_ordered(self):
-        this = self._parse_bitwise()
+        this = self._parse_conjunction()
         self._match(TokenType.ASC)
         return self.expression(exp.Ordered, this=this, desc=self._match(TokenType.DESC))
 
@@ -1272,6 +1285,8 @@ def _parse_primary(self):
         if self._match(TokenType.L_PAREN):
             this = self._parse_conjunction() or self._parse_with()
             self._match_r_paren()
+            if self._return_subquery and isinstance(this, exp.Subqueryable):
+                return self._parse_subquery(this)
             return self.expression(exp.Paren, this=this)
 
         return None


Test patch:
diff --git a/tests/fixtures/identity.sql b/tests/fixtures/identity.sql
--- a/tests/fixtures/identity.sql
+++ b/tests/fixtures/identity.sql
@@ -190,6 +190,7 @@ SELECT a FROM test WHERE a > ALL (SELECT 1)
 SELECT a FROM test ORDER BY a
 SELECT a FROM test ORDER BY a, b
 SELECT x FROM tests ORDER BY a DESC, b DESC, c
+SELECT a FROM test ORDER BY a > 1
 SELECT a, b FROM test GROUP BY 1
 SELECT a, b FROM test GROUP BY a
 SELECT a, b FROM test WHERE a = 1 GROUP BY a HAVING a = 2
@@ -303,6 +304,8 @@ WITH a AS (SELECT 1) SELECT 1 EXCEPT DISTINCT SELECT 2
 (SELECT 1) UNION SELECT 2
 SELECT 1 UNION (SELECT 2)
 (SELECT 1 UNION SELECT 2) UNION (SELECT 2 UNION ALL SELECT 3)
+(SELECT 1 UNION SELECT 2) ORDER BY x LIMIT 1 OFFSET 1
+SELECT * FROM (((SELECT 1) UNION SELECT 2) ORDER BY x LIMIT 1 OFFSET 1)
 VALUES (1) UNION SELECT * FROM x
 WITH a AS (SELECT 1) SELECT a.* FROM a
 WITH a AS (SELECT 1), b AS (SELECT 2) SELECT a.*, b.* FROM a CROSS JOIN b