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

Wrong result with DISTINCT and GROUP BY when STD() is wrapped in CASE

    XMLWordPrintable

Details

    • Bug
    • Status: Confirmed (View Workflow)
    • Major
    • Resolution: Unresolved
    • 10.11, 11.4, 11.8, 12.3, 13.1, 11.8.9
    • 10.11, 11.4, 11.8, 12.3, 13.1
    • Optimizer
    • Linux x86_64; MariaDB 11.8.9 binary distribution.
    • Unexpected results

    Description

      A SELECT DISTINCT query with GROUP BY returns an incorrect result when STD(v) is replaced with the equivalent expression CASE WHEN 1 THEN STD(v) ELSE STD(v) END.

      The original query returns two groups. The modified query returns only one row, combining the grouping value from the first group with the average from the second group.

      Reproducer

      CREATE TABLE t (id INT, v INT);
      INSERT INTO t VALUES (1,0),(1,1),(1,2),(2,10),(2,11),(2,12);
       
      SELECT DISTINCT
        CASE WHEN (SELECT 1) THEN id ELSE id END AS grp,
        AVG(v) AS avg_v,
        STD(v) AS std_v
      FROM t GROUP BY id;
       
      SELECT DISTINCT
        CASE WHEN (SELECT 1) THEN id ELSE id END AS grp,
        AVG(v) AS avg_v,
        CASE WHEN 1 THEN STD(v) ELSE STD(v) END AS std_v
      FROM t GROUP BY id;
      

      Actual result

      The first query returns:

      +------+---------+--------+
      | grp  | avg_v   | std_v  |
      +------+---------+--------+
      |    1 |  1.0000 | 0.8165 |
      |    2 | 11.0000 | 0.8165 |
      +------+---------+--------+
      

      The second query returns:

      +------+---------+--------+
      | grp  | avg_v   | std_v  |
      +------+---------+--------+
      |    1 | 11.0000 | 0.8165 |
      +------+---------+--------+
      

      The returned row has grp = 1, but avg_v = 11.0000 is the average for id = 2.

      Expected result

      Both queries should return the same two rows as the first query, ignoring row order.

      CASE WHEN 1 THEN STD(v) ELSE STD(v) END is equivalent to STD(v). CASE WHEN (SELECT 1) THEN id ELSE id END is equivalent to id. Since the grouping values differ, DISTINCT should retain both rows.

      Additional observations

      • Removing DISTINCT from the second query restores the expected two rows.
      • Replacing the first selected CASE expression with id also restores the expected result.
      • Only MariaDB 11.8.9 has been verified. The source-level cause has not been determined.

      Attachments

        Activity

          People

            psergei Sergei Petrunia
            jxgui jinxingui
            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.