# LogicTest: fakedist-opt

# Tests that verify we retrieve the stats correctly. Note that we can't create
# statistics if distsql mode is OFF.

statement ok
CREATE TABLE uv (u INT, v INT, INDEX (u) STORING (v), INDEX (v) STORING (u));
INSERT INTO uv VALUES (1, 1), (1, 2), (1, 3), (1, 4), (2, 4), (2, 5), (2, 6), (2, 7)

statement ok
CREATE STATISTICS u ON u FROM uv;
CREATE STATISTICS v ON v FROM uv

# Verify we scan index v which has the more selective constraint.
query TTTTT
EXPLAIN (VERBOSE) SELECT * FROM uv WHERE u = 1 AND v = 1
----
scan  ·       ·            (u, v)  ·
·     table   uv@uv_v_idx  ·       ·
·     spans   /1-/2        ·       ·
·     filter  u = 1        ·       ·

# Verify that injecting different statistics changes the plan.
statement ok
ALTER TABLE uv INJECT STATISTICS '[
  {
    "columns": ["u"],
    "created_at": "2018-01-01 1:00:00.00000+00:00",
    "row_count": 100,
    "distinct_count": 100
  },
  {
    "columns": ["v"],
    "created_at": "2018-01-01 1:00:00.00000+00:00",
    "row_count": 100,
    "distinct_count": 10
  }
]'

query TTTTT
EXPLAIN (VERBOSE) SELECT * FROM uv WHERE u = 1 AND v = 1
----
scan  ·       ·            (u, v)  ·
·     table   uv@uv_u_idx  ·       ·
·     spans   /1-/2        ·       ·
·     filter  v = 1        ·       ·

# Verify that injecting different statistics with null counts
# changes the plan.
statement ok
ALTER TABLE uv INJECT STATISTICS '[
  {
    "columns": ["u"],
    "created_at": "2018-01-01 1:00:00.00000+00:00",
    "row_count": 100,
    "distinct_count": 20,
    "null_count": 0
  },
  {
    "columns": ["v"],
    "created_at": "2018-01-01 1:00:00.00000+00:00",
    "row_count": 100,
    "distinct_count": 10,
    "null_count": 0
  }
]'

query TTTTT
EXPLAIN (VERBOSE) SELECT * FROM uv WHERE u = 1 AND v = 1
----
scan  ·       ·            (u, v)  ·
·     table   uv@uv_u_idx  ·       ·
·     spans   /1-/2        ·       ·
·     filter  v = 1        ·       ·

statement ok
ALTER TABLE uv INJECT STATISTICS '[
  {
    "columns": ["u"],
    "created_at": "2018-01-01 1:00:00.00000+00:00",
    "row_count": 100,
    "distinct_count": 20,
    "null_count": 0
  },
  {
    "columns": ["v"],
    "created_at": "2018-01-01 1:00:00.00000+00:00",
    "row_count": 100,
    "distinct_count": 10,
    "null_count": 90
  }
]'

query TTTTT
EXPLAIN (VERBOSE) SELECT * FROM uv WHERE u = 1 AND v = 1
----
scan  ·       ·            (u, v)  ·
·     table   uv@uv_v_idx  ·       ·
·     spans   /1-/2        ·       ·
·     filter  u = 1        ·       ·
