Skip to content

Commit 1206bea

Browse files
fix(redshift): parser issue for TOP N DISTINCT (tobymao#7594)
* fix for TOP N DISTINCT * added tests * moved parsing to base class * updated tests * added ALL
1 parent bd5f4bc commit 1206bea

2 files changed

Lines changed: 19 additions & 4 deletions

File tree

sqlglot-integration-tests

sqlglot/parser.py

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3838,14 +3838,29 @@ def _parse_select_query(
38383838
else None
38393839
)
38403840

3841-
if all_ and distinct:
3842-
self.raise_error("Cannot specify both ALL and DISTINCT after SELECT")
3843-
38443841
operation_modifiers = []
38453842
while self._curr and self._match_texts(self.OPERATION_MODIFIERS):
38463843
operation_modifiers.append(exp.var(self._prev.text.upper()))
38473844

38483845
limit = self._parse_limit(top=True)
3846+
3847+
# Some dialects (e.g. Redshift, T-SQL) allow SELECT TOP N DISTINCT ...
3848+
if limit and not matched_distinct and not all_:
3849+
matched_distinct = self._match_set(self.DISTINCT_TOKENS)
3850+
if matched_distinct:
3851+
distinct = self.expression(
3852+
exp.Distinct(
3853+
on=self._parse_value(values=False)
3854+
if self._match(TokenType.ON)
3855+
else None
3856+
)
3857+
)
3858+
else:
3859+
all_ = self._match(TokenType.ALL)
3860+
3861+
if all_ and distinct:
3862+
self.raise_error("Cannot specify both ALL and DISTINCT after SELECT")
3863+
38493864
projections, exclude = self._parse_projections()
38503865

38513866
this = self.expression(

0 commit comments

Comments
 (0)