diff --git a/pkg/sql/opt/memo/statistics_builder.go b/pkg/sql/opt/memo/statistics_builder.go index 7a371c2058b4..c6a8d8eda8b6 100644 --- a/pkg/sql/opt/memo/statistics_builder.go +++ b/pkg/sql/opt/memo/statistics_builder.go @@ -2525,11 +2525,12 @@ func (sb *statisticsBuilder) updateDistinctCountsFromConstraint( end := int(*endVal.(*tree.DInt)) // We assume that both start and end boundaries are inclusive. This // should be the case for integer valued columns (due to normalization - // by constraint.PreferInclusive). + // by constraint.PreferInclusive). We must cast each end to a float + // *before* performing the subtraction to avoid overflow. if c.Columns.Get(col).Ascending() { - distinctCount += float64(end - start) + distinctCount += float64(end) - float64(start) } else { - distinctCount += float64(start - end) + distinctCount += float64(start) - float64(end) } } else { // We can't determine the distinct count for this column. For example, diff --git a/pkg/sql/opt/memo/testdata/stats/scan b/pkg/sql/opt/memo/testdata/stats/scan index 6d9d84afdaa0..acb7240d7430 100644 --- a/pkg/sql/opt/memo/testdata/stats/scan +++ b/pkg/sql/opt/memo/testdata/stats/scan @@ -509,3 +509,16 @@ SELECT * FROM empty scan empty ├── columns: x:1(int) └── stats: [rows=1] + +# Regression test: previously, overflow when computing estimated distinct count +# here resulted in a row count of zero being estimated. +opt +SELECT x FROM a WHERE x >= -9223372036854775808 AND x <= 0 ORDER BY x LIMIT 10 +---- +scan a + ├── columns: x:1(int!null) + ├── constraint: /1: [/-9223372036854775808 - /0] + ├── limit: 10 + ├── stats: [rows=10] + ├── key: (1) + └── ordering: +1