Skip to content

Distinct and order by with different columns #54

Closed

Description

@minouminou

When selecting a distinct rows and ordering by another column I see strange result. Most of RDBMS return error on queries like this, except MySQL (behavior is documented).

create table t1 (a UInt8,b UInt8) ENGINE=Memory;
INSERT INTO t1 VALUES (2,1),(1,2),(3,3),(2,4);
SELECT * FROM t1

┌─a─┬─b─┐
│ 2 │ 1 │
│ 1 │ 2 │
│ 3 │ 3 │
│ 2 │ 4 │
└───┴───┘
SELECT DISTINCT a FROM t1 ORDER BY b ASC
┌─a─┐
│ 2 │
│ 1 │
│ 3 │
└───┘

Correct result if "distinct" after ordering

SELECT DISTINCT a FROM t1 ORDER BY b DESC
┌─a─┐
│ 3 │
│ 1 │
│ 2 │
└───┘

Not correct if "distinct" after ordering

Activity

  1. alexey-milovidov commented on Jul 13, 2016

    @alexey-milovidov
    Member

    There are two possibilities:

    • document that it is implementation specific behavior;
    • throw an exception (and document this behavior).

    I like second variant, but first is more free. Because it is sometimes usable, and also it could be correct (well specified) in subset of cases.

    By the way, it is impossible to specify clear semantic (distinct after order or distinct before order) when doing ORDER BY and DISTINCT by different columns, because in query execution pipeline, there are 'partial sorting' and 'partial distinct' steps, which could be interleaved.

  2. added
    comp-documentation
    on Jul 14, 2018
  3. alexey-milovidov commented on May 16, 2019

    @alexey-milovidov
    Member
  4. alexey-milovidov commented on Sep 24, 2020

    @alexey-milovidov
    Member

    There is one more argument that we should throw an exception: #15249

  5. olgarev commented on Apr 30, 2021

    @olgarev
    Contributor

    @alexey-milovidov The documentation was updated.

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

    comp-documentationsql-compatibility

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions