Repository navigation
ORDER BY inside aggregate calls in the expression API - #713
Open
evertlammerts wants to merge 3 commits into
Open
evertlammerts wants to merge 3 commits into
evertlammerts wants to merge 3 commits into
Conversation
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
The expression API had no way to write an aggregate with an ORDER BY inside its call, such as
first(x ORDER BY t).Funcsupported FILTER and IGNORE NULLS but not ORDER BY. So a deterministicfirst,lastorstring_aggper group had to be raw SQL throughSQLExpression, which is what Narwhals does today (narwhals-dev/narwhals#4099, duckdb/duckdb#19252).The obvious spelling does not work.
fn()passes every keyword through as a named SQL argument, soorder_by=produces the wrong SQL:What changes
Aggregate calls (
FuncandDistinct) get an.order_by(*keys)method. It puts the keys inside the parentheses and works alongside the other clauses, also under.over():Every generated aggregate method also accepts
order_by=as a shortcut for the same thing. Keywords passed tofn()are still named SQL arguments. To order a call built withfn(), use the method.Design choices
fn()has no keyword to spare, because all of its keywords become named SQL arguments. A method also combines withwhere(),ignore_nulls(),n_unique(), the.str()wrappers andover()the same waywhere()does.over()keys. For example, a bare string is a TypeError..order_by()on a node that is not a call, and an empty key list. What only the binder can judge fails at bind time, as it does forwhere(). Examples are ORDER BY on a scalar function, or a DISTINCT aggregate ordered by a key that is not one of its arguments.Tested behavior
col("x").first(order_by=col("t").desc())renders"first"("x" ORDER BY "t" DESC)and gives the same results as that SQL in these cases: