Skip to content

opt: Unnecessary sort operator added by SELECT with WHERE clause #33023

@andy-kimball

Description

@andy-kimball

Repro:

CREATE TABLE xyz (x INT PRIMARY KEY, y INT, z INT);
CREATE TABLE abcd (a INT, b INT, c INT, d INT, INDEX ab(a, b) STORING (c, d), INDEX cd(c, d) STORING (a, b));
EXPLAIN (OPT) SELECT * FROM [INSERT INTO xyz SELECT b, c, d FROM abcd ORDER BY c, d LIMIT 100 RETURNING *] WHERE x=y ORDER BY y;

Expected: No explicit sort should be necessary
Actual: An explicit sort is added.

  sort
   ├── columns: x:5(int!null) y:6(int!null) z:7(int)
   ├── ordering: +(5|6) [provided: +5]
   └── select
        ├── columns: b:5(int!null) c:6(int!null) d:7(int)
        ├── insert xyz
        │    ├── columns: b:5(int!null) c:6(int) d:7(int)
        │    ├── insert-mapping:
        │    │    ├──  b:5(int!null) => x:1(int)
        │    │    ├──  c:6(int) => y:2(int)
        │    │    └──  d:7(int) => z:3(int)
        │    ├── internal-ordering: +6,+7
        │    └── scan abcd@cd
        │         ├── columns: b:5(int) c:6(int) d:7(int)
        │         ├── limit: 100
        │         ├── stats: [rows=100, distinct(5)=65.132156, null(5)=1, distinct(6)=65.132156, null(6)=1]
        │         └── ordering: +6,+7
        └── filters
             └── eq [type=bool, outer=(5,6), constraints=(/5: (/NULL - ]; /6: (/NULL - ]), fd=(5)==(6), (6)==(5)]
                  ├── variable: b [type=int]
                  └── variable: c [type=int]

Jira issue: CRDB-4704

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-performancePerf of queries or internals. Solution not expected to change functional behavior.T-sql-queriesSQL Queries Team

    Type

    No type

    Projects

    Status

    Backlog

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions