Skip to content

Commit

Permalink
Fix: don't evaluate Rand twice when ordering by it (#3233)
Browse files Browse the repository at this point in the history
  • Loading branch information
georgesittas committed Mar 27, 2024
1 parent 8325039 commit fd5783f
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
2 changes: 1 addition & 1 deletion sqlglot/generator.py
Expand Up @@ -2091,7 +2091,7 @@ def ordered_sql(self, expression: exp.Ordered) -> str:
self.unsupported(
f"'{nulls_sort_change.strip()}' translation not supported with positional ordering"
)
else:
elif not isinstance(expression.this, exp.Rand):
null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else ""
this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}"
nulls_sort_change = ""
Expand Down
9 changes: 9 additions & 0 deletions tests/dialects/test_postgres.py
Expand Up @@ -310,6 +310,15 @@ def test_postgres(self):
)
self.validate_identity("SELECT * FROM t1*", "SELECT * FROM t1")

self.validate_all(
'SELECT * FROM "test_table" ORDER BY RANDOM() LIMIT 5',
write={
"bigquery": "SELECT * FROM `test_table` ORDER BY RAND() NULLS LAST LIMIT 5",
"duckdb": 'SELECT * FROM "test_table" ORDER BY RANDOM() LIMIT 5',
"postgres": 'SELECT * FROM "test_table" ORDER BY RANDOM() LIMIT 5',
"tsql": "SELECT TOP 5 * FROM [test_table] ORDER BY RAND()",
},
)
self.validate_all(
"SELECT (data -> 'en-US') AS acat FROM my_table",
write={
Expand Down

0 comments on commit fd5783f

Please sign in to comment.