# LogicTest: local

statement ok
CREATE TABLE t (k INT PRIMARY KEY, v INT, w INT, INDEX v(v))

# TopK added when ordering by a non-index.
query T
EXPLAIN (VERBOSE) SELECT * FROM t ORDER BY w LIMIT 10
----
distribution: local
vectorized: true
·
• top-k
│ columns: (k, v, w)
│ estimated row count: 10 (missing stats)
│ order: +w
│ k: 10
│
└── • scan
      columns: (k, v, w)
      estimated row count: 1,000 (missing stats)
      table: t@t_pkey
      spans: FULL SCAN

# No TopK when ordering by an index.
query T
EXPLAIN (VERBOSE) SELECT * FROM t ORDER BY v LIMIT 10
----
distribution: local
vectorized: true
·
• index join
│ columns: (k, v, w)
│ ordering: +v
│ estimated row count: 10 (missing stats)
│ table: t@t_pkey
│ key columns: k
│
└── • scan
      columns: (k, v)
      ordering: +v
      estimated row count: 10 (missing stats)
      table: t@v
      spans: LIMITED SCAN
      limit: 10

# TopK descending.
query T
EXPLAIN (VERBOSE) SELECT * FROM t ORDER BY w DESC LIMIT 10
----
distribution: local
vectorized: true
·
• top-k
│ columns: (k, v, w)
│ estimated row count: 10 (missing stats)
│ order: -w
│ k: 10
│
└── • scan
      columns: (k, v, w)
      estimated row count: 1,000 (missing stats)
      table: t@t_pkey
      spans: FULL SCAN

# TopK added in subquery.
query T
EXPLAIN (VERBOSE) SELECT k FROM (SELECT k, v FROM T ORDER BY w LIMIT 2)
----
distribution: local
vectorized: true
·
• project
│ columns: (k)
│
└── • top-k
    │ columns: (k, w)
    │ estimated row count: 2 (missing stats)
    │ order: +w
    │ k: 2
    │
    └── • scan
          columns: (k, w)
          estimated row count: 1,000 (missing stats)
          table: t@t_pkey
          spans: FULL SCAN

# TopK with filter.
query T
EXPLAIN (VERBOSE) SELECT * FROM t WHERE w >= 1 AND w <= 10 ORDER BY w LIMIT 10
----
distribution: local
vectorized: true
·
• top-k
│ columns: (k, v, w)
│ estimated row count: 10 (missing stats)
│ order: +w
│ k: 10
│
└── • filter
    │ columns: (k, v, w)
    │ estimated row count: 100 (missing stats)
    │ filter: (w >= 1) AND (w <= 10)
    │
    └── • scan
          columns: (k, v, w)
          estimated row count: 1,000 (missing stats)
          table: t@t_pkey
          spans: FULL SCAN

# When partial ordering is available, choose topk.
query T
EXPLAIN (VERBOSE) SELECT * FROM t@v ORDER BY v, w LIMIT 10
----
distribution: local
vectorized: true
·
• top-k
│ columns: (k, v, w)
│ estimated row count: 10 (missing stats)
│ order: +v,+w
│ k: 10
│
└── • index join
    │ columns: (k, v, w)
    │ ordering: +v
    │ estimated row count: 1,000 (missing stats)
    │ table: t@t_pkey
    │ key columns: k
    │
    └── • scan
          columns: (k, v)
          ordering: +v
          estimated row count: 1,000 (missing stats)
          table: t@v
          spans: FULL SCAN (SOFT LIMIT)
