Uploaded image for project: 'MariaDB Server'
  1. MariaDB Server
  2. MDEV-40581

A second window OVER (PARTITION BY <constant> ORDER BY …) drops the first window's ORDER BY sort

    XMLWordPrintable

Details

    Description

      When a SELECT has two window functions and the second one uses OVER (PARTITION BY <constant> ORDER BY …), MariaDB's window-function computation coalesces both windows into a single filesort keyed only by the second window's (constant) ORDER BY and drops the first window's own ORDER BY. This might be unexpected behavior.

      Please see the repro below:

      CREATE TABLE t (id BIGINT);
      INSERT INTO t VALUES (-3),(-1),(0),(1),(2),(2),(NULL),(7);
       
      -- (1) THE BUG: window A = SUM(41) OVER (ORDER BY id<1 DESC) is corrupted by the presence of window B.
      --     Correct (RANGE peers over key id<1: 3 rows key=1 ->123, 4 rows key=0 ->287, 1 NULL ->328):
      --         {123,123,123, 287,287,287,287, 328}   <- MySQL returns exactly this.
      --     MariaDB actual: wrong AND run-order-dependent, e.g. {41,82,123, 246,246,246, 287, 328}.
      SELECT id,
             SUM(41) OVER (ORDER BY id < 1 DESC)                        AS a,
             MAX(id) OVER (PARTITION BY '3' ORDER BY '3' DESC)          AS b
      FROM t;
      -- Expected column a multiset = {123 x3, 287 x4, 328}; MariaDB gives garbage (frame sizes 1..8).
       
      -- (2) CONTROL -- window A ALONE is correct (and equals MySQL):
      SELECT id, SUM(41) OVER (ORDER BY id < 1 DESC) AS a FROM t;
      -- a = {123 x3, 287 x4, 328}  ✓
       
      -- (3) CONTROL -- window B PARTITION BY a REAL column (not a constant): window A is correct again:
      SELECT id,
             SUM(41) OVER (ORDER BY id < 1 DESC)          AS a,
             MAX(id) OVER (PARTITION BY id ORDER BY '3' DESC) AS b
      FROM t;
      -- a = {123 x3, 287 x4, 328}  ✓  (the constant partition is the trigger)
       
      -- (4) CONTROL -- window B with NO ORDER BY: window A is correct again:
      SELECT id,
             SUM(41) OVER (ORDER BY id < 1 DESC)  AS a,
             MAX(id) OVER (PARTITION BY '3')      AS b
      FROM t;
      -- a = {123 x3, 287 x4, 328}  ✓  (window B needs both PARTITION-BY-constant AND its own ORDER BY)
      

      Attachments

        Activity

          People

            psergei Sergei Petrunia
            jesse0623 Junwen An
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

            Dates

              Created:
              Updated:

              Git Integration

                Error rendering 'com.xiplink.jira.git.jira_git_plugin:git-issue-webpanel'. Please contact your Jira administrators.