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

DISTINCT with GROUP BY and a correlated HAVING subquery loses a surviving value

    XMLWordPrintable

Details

    Description

      Description

      MariaDB Server 12.3.2 drops a value that survives HAVING when DISTINCT is combined with GROUP BY and a correlated scalar subquery. Evaluating the grouped query without DISTINCT returns `R` and `Z`; applying DISTINCT should preserve both, but the combined query returns only `Z`.

      Adding a redundant aggregate HAVING condition or applying DISTINCT in an outer query returns both values. This is observable wrong-result behavior, not a collation representative or client comparison issue.

      How to repeat

       
      CREATE TEMPORARY TABLE having_distinct (id INT PRIMARY KEY,k VARCHAR(10),x INT);
      INSERT INTO having_distinct VALUES (1,'R',43),(2,'R',1),(3,'Z',10);
       
      SELECT DISTINCT k FROM having_distinct o GROUP BY k,id
      HAVING (SELECT 1 FROM having_distinct i WHERE i.x<o.id LIMIT 1)<36;
      

      Expected result

      Two rows: `R` and `Z` (order unspecified).

      Each group has a unique id and contains one row. For id=1, no x is less than 1, so the scalar subquery is NULL and HAVING removes that group. For id=2 and id=3, the subquery finds x=1 and returns constant 1, so both groups survive. Their projected k values are `R` and `Z`, which are distinct. The LIMIT subquery always returns constant 1 when any row qualifies; row selection cannot affect its value.

      Actual result

      Only `Z` is returned. The surviving `R` value is lost.

      Attachments

        Issue Links

          Activity

            People

              psergei Sergei Petrunia
              chen7897 cl hl
              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.