Skip to content

Fix the order of LIMIT and OFFSET clauses when using the Presto flavor (issue #195) #196

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion select.go
Original file line number Diff line number Diff line change
Expand Up @@ -457,7 +457,7 @@ func (sb *SelectBuilder) BuildWithFlavor(flavor Flavor, initialArg ...interface{
buf.WriteLeadingString("LIMIT ")
buf.WriteString(sb.limitVar)
}
case PostgreSQL, Presto:
case PostgreSQL:
if len(sb.limitVar) > 0 {
buf.WriteLeadingString("LIMIT ")
buf.WriteString(sb.limitVar)
Expand All @@ -467,6 +467,20 @@ func (sb *SelectBuilder) BuildWithFlavor(flavor Flavor, initialArg ...interface{
buf.WriteLeadingString("OFFSET ")
buf.WriteString(sb.offsetVar)
}
case Presto:
// There might be a hidden constraint in Presto requiring offset to be set before limit.
// The select statement documentation (https://prestodb.io/docs/current/sql/select.html)
// puts offset before limit, and Trino, which is based on Presto, seems
// to require this specific order.
if len(sb.offsetVar) > 0 {
buf.WriteLeadingString("OFFSET ")
buf.WriteString(sb.offsetVar)
}

if len(sb.limitVar) > 0 {
buf.WriteLeadingString("LIMIT ")
buf.WriteString(sb.limitVar)
}

case SQLServer:
// If ORDER BY is not set, sort column #1 by default.
Expand Down
4 changes: 2 additions & 2 deletions select_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -229,9 +229,9 @@ func ExampleSelectBuilder_limit_offset() {
// Presto
// #1: SELECT * FROM user
// #2: SELECT * FROM user OFFSET ?
// #3: SELECT * FROM user LIMIT ? OFFSET ?
// #3: SELECT * FROM user OFFSET ? LIMIT ?
// #4: SELECT * FROM user LIMIT ?
// #5: SELECT * FROM user ORDER BY id LIMIT ? OFFSET ?
// #5: SELECT * FROM user ORDER BY id OFFSET ? LIMIT ?
//
// Oracle
// #1: SELECT * FROM user
Expand Down