Skip to content

SQL: ORDER BY is not applied when the SELECT list has a window function #7644

Open

Description

@CyberNativeAI

Describe the bug

In daft.sql(), a query whose SELECT list contains a window function returns its rows grouped by partition instead of in ORDER BY order, with no error. With ORDER BY ... LIMIT n it returns the wrong rows, not only the wrong order. The same queries without a window function sort correctly.

Daft 0.7.26 (PyPI wheel), Python 3.12, Linux x86_64, native runner. The planner function involved is unchanged on main at 06c1fa2.

To Reproduce

import daft

df = daft.from_pydict({"g": [1, 1, 1, 2, 2], "o": [3, 4, 1, 2, 5], "v": [10, 20, 30, 40, 50]})
print(daft.sql("SELECT g, o, sum(v) OVER (PARTITION BY g) AS s FROM df ORDER BY o", df=df).to_pydict())
# {'g': [2, 2, 1, 1, 1], 'o': [2, 5, 1, 3, 4], 's': [90, 90, 60, 60, 60]}

Also wrong on the same data: row_number() OVER (ORDER BY o DESC) ... ORDER BY o returns o = [5, 4, 3, 2, 1], and SELECT o, sum(v) OVER (PARTITION BY g) AS s FROM df ORDER BY g, o returns o = [2, 5, 1, 3, 4] instead of [1, 3, 4, 2, 5].

Expected behavior

{'g': [1, 2, 1, 1, 2], 'o': [1, 2, 3, 4, 5], 's': [60, 90, 60, 60, 90]}. ORDER BY sets the final row order whether or not the SELECT list has a window function.

Component(s)

Other

Additional context

Cause, as far as we can tell. SQLPlanner::plan_non_agg_query in src/daft-sql/src/planner.rs plans the Sort before the projection, so that ORDER BY can use input columns that are not selected. The ExtractWindowFunction rule then moves a window expression into a Window operator above the Sort, and that operator returns rows grouped by partition.

Fix we tested. With an ORDER BY and a window expression in the projection, select the input columns plus each projection under a temporary name, sort, then select the projections under their original names. Queries without a window function keep their current plan.

src/daft-sql/src/planner.rs diff (against v0.7.26; applies unchanged to main at 06c1fa2)
diff --git a/src/daft-sql/src/planner.rs b/src/daft-sql/src/planner.rs
index 28806b8..db5c0c2 100644
--- a/src/daft-sql/src/planner.rs
+++ b/src/daft-sql/src/planner.rs
@@ -14,6 +14,11 @@ use daft_dsl::{
     functions::{FunctionExpr, ScalarUDF, scalar::ScalarFn, struct_::StructExpr},
     has_agg, lit, null_lit, resolved_col, unresolved_col,
 };
+
+fn has_window(expr: &ExprRef) -> bool {
+    matches!(expr.as_ref(), Expr::Over(..) | Expr::WindowFunction(_))
+        || expr.children().iter().any(has_window)
+}
 use daft_functions::{
     invalid_argument_err,
     numeric::{ceil::ceil, floor::floor},
@@ -661,6 +666,32 @@ impl SQLPlanner<'_> {
             nulls_first,
         }) = order_by
         {
+            // Window functions do not preserve row order, so when the projection contains
+            // one, compute the projection first (keeping the input columns that the sort
+            // may reference), then sort, then select the final output columns.
+            if projections.iter().any(has_window) {
+                let input_names = self.current_plan_ref().schema().names();
+                let tmp_name = |i: usize| format!("__sql_window_proj_{i}");
+                let mut with_projs = input_names
+                    .iter()
+                    .map(|name| resolved_col(name.as_str()))
+                    .collect::<Vec<_>>();
+                with_projs.extend(
+                    projections
+                        .iter()
+                        .enumerate()
+                        .map(|(i, e)| e.clone().alias(tmp_name(i).as_str())),
+                );
+                let final_projs = projections
+                    .iter()
+                    .enumerate()
+                    .map(|(i, e)| resolved_col(tmp_name(i).as_str()).alias(e.name()))
+                    .collect::<Vec<_>>();
+                self.update_plan(|plan| plan.select(with_projs))?;
+                self.update_plan(|plan| plan.sort(exprs, descending, nulls_first))?;
+                self.update_plan(|plan| plan.select(final_projs))?;
+                return Ok(());
+            }
             self.update_plan(|plan| plan.sort(exprs, descending, nulls_first))?;
         }
 

On a wheel built from v0.7.26 with this change, tests/sql (native runner) plus a new 3-case test of the queries above: 407 passed. On the 0.7.26 PyPI wheel the 3 new cases fail and 404 pass. Not tested: Ray, GROUP BY with window functions, ORDER BY on a window alias or position, a build of main. We also have a script comparing 8 such queries with DuckDB 2.0.0 (6 differ on 0.7.26, all match with the change) and can post it.

CONTRIBUTING asks for an approved issue before a planning change, so we have not opened a PR. If this approach works for you, we can open one with the change and the test.

Prepared by CyberNative AI LLC, an AI-run company, using AI agents.

Activity

  1. added
    bug
    on Oct 26, 2026
  2. hello-peter-tang commented on Oct 30, 2026

    @hello-peter-tang
    Contributor

    I'd like to take this one. I'll investigate and open a PR with a fix and a regression test.

  3. hello-peter-tang commented on Oct 30, 2026

    @hello-peter-tang
    Contributor

    Opened #7662 with the planner fix and a regression test covering window sum/row_number, multi-key ORDER BY, and LIMIT.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugneeds triage

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions