Skip to content

Commit ccbb699

Browse files
committed
Merge pull request cockroachdb#6380 from RaduBerinde/fix-singlekey-opt
sql: fix single-key optimization bug
2 parents 149b4fb + 19e6754 commit ccbb699

File tree

2 files changed

+26
-5
lines changed

2 files changed

+26
-5
lines changed

sql/index_selection.go

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -219,11 +219,14 @@ func selectIndex(
219219
}
220220

221221
// If we have no filter, we can request a single key in some cases.
222-
if noFilter && analyzeOrdering != nil {
222+
if noFilter && analyzeOrdering != nil && s.isSecondaryIndex {
223223
_, _, singleKey := analyzeOrdering(plan.Ordering())
224224
if singleKey {
225-
s.spans = s.spans[:1]
226-
s.spans[0].count = 1
225+
// We only need to retrieve one key, but some spans might contain no
226+
// keys so we need to keep all of them.
227+
for i := range s.spans {
228+
s.spans[i].count = 1
229+
}
227230
}
228231
}
229232

@@ -412,8 +415,8 @@ func (v *indexInfo) analyzeOrdering(scan *scanNode, analyzeOrdering analyzeOrder
412415
}
413416

414417
if log.V(2) {
415-
log.Infof("%s: analyzeOrdering: weight=%0.2f reverse=%v index=%d",
416-
v.index.Name, weight, v.reverse, fwdIndexOrdering)
418+
log.Infof("%s: analyzeOrdering: weight=%0.2f reverse=%v match=%d",
419+
v.index.Name, weight, v.reverse, match)
417420
}
418421
}
419422

sql/testdata/aggregate

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -399,6 +399,13 @@ CREATE TABLE abc (
399399
statement ok
400400
INSERT INTO abc VALUES ('one', 1.5, true, 5::decimal), ('two', 2.0, false, 1.1::decimal)
401401

402+
# Verify we don't try to apply the single-key optimization to the primary index.
403+
query ITT
404+
EXPLAIN SELECT MIN(a) FROM abc
405+
----
406+
0 group MIN(a)
407+
1 scan abc@primary -
408+
402409
query TRBR
403410
SELECT MIN(a), MIN(b), MIN(c), MIN(d) FROM abc
404411
----
@@ -455,6 +462,17 @@ EXPLAIN SELECT MIN(x) FROM xyz
455462
0 group MIN(x)
456463
1 scan xyz@xy 1:-
457464

465+
query I
466+
SELECT MIN(x) FROM xyz WHERE x in (0, 4, 7)
467+
----
468+
4
469+
470+
query ITT
471+
EXPLAIN SELECT MIN(x) FROM xyz WHERE x in (0, 4, 7)
472+
----
473+
0 group MIN(x)
474+
1 scan xyz@xy 1:/0-/1 1:/4-/5 1:/7-/8
475+
458476
query I
459477
SELECT MAX(x) FROM xyz
460478
----

0 commit comments

Comments
 (0)