# SQL Server string statistics

> The string summary of a SQL Server statistics object, decoded: a sample of strings stored in a trie, how it estimates LIKE predicates, and what bypasses it.
>
> Source : https://www.pachadata.com/en/docs/articles/sql-server/performance/string-statistics/
> Author : Rudi Bruchez · published 2026-10-20 · updated 2026-11-21
> Markdown version of the page, for tools and LLMs. The HTML page is the reference.


*Co-written with Claude, who ran much of the testing and research.*

> TL;DR :
>
> String statistics have existed in SQL Server since version 2005. They are used to estimate the cardinality of `LIKE` searches, such as `Email LIKE '%.org'`. When the first column of a statistics object is a character type, the statistics object holds a string summary in addition to the histogram. You can see it in `DBCC SHOW_STATISTICS`, where the `String Index` property is then `YES`.
> 
> This summary is a sample of the column values, taken from 5% of the rows read by the statistics, up to about 56,000 rows read. After that, the sample size stays around 2,800 strings, whatever the size of the table. There are slightly fewer still for `nvarchar` and for long strings. The strings are stored in a [trie](https://en.wikipedia.org/wiki/Trie) (prefix tree): each node holds a piece of a string, and strings that start the same way share the nodes of that beginning.
> 
> To estimate a `LIKE` with wildcards, the optimizer applies the pattern to each string of the sample, then multiplies the proportion found by the number of rows in the table. When no string in the sample matches the pattern, the proportion would be zero, and so would the estimate. The optimizer then acts as if a tenth of a string matched: on the million rows of the `Contact.ProspectUS` table of my sample database, whose sample holds 2,825 strings, a pattern not found in the sample is estimated at 1,000,000 × 0.1 / 2,825, or 35.4 rows. That is the floor of the estimate.
> 
> Frequent patterns are estimated correctly, and rare patterns get the floor value, roughly the number of rows divided by 28,000. The summary is not used for cardinality estimation when the column is wrapped in an expression, such as a function call, when the pattern uses `ESCAPE`, comes from a local variable or is `nvarchar` against a `varchar` column (hence an implicit conversion), or when the column is a `varchar` with a UTF-8 collation. In those cases, a pattern that starts with a wildcard is estimated at 9% of the table rows, and a prefix is estimated from the histogram (for a UTF-8 column, only from SQL Server 2025 on, at compatibility level 170). Beyond 80 characters, only the first 40 and the last 40 are kept, joined together. Finally, on a column that repeats a character, such as zero-padded references, a pattern with several `%` can cost several seconds of compile time.


## String statistics

Statistics are what cardinality estimation works from. They have three parts: the header, the density vector and a histogram. I described them in the chapter [Les statistiques et la cardinalité](/docs/optimiser-sql-server/chapitres/065.statistiques-et-cardinalite/) of my book *Optimiser SQL Server* (in French), and in the video [Introduction aux statistiques dans SQL Server](https://youtu.be/a-0JJNXdVsw) (in French).

The histogram of a statistics object splits the values of the first column into at most 200 steps. It answers `Nom = 'Dupont'` or `Nom >= 'Ma' AND Nom < 'Mb'` well, and `Email LIKE '%.org'` badly: the end of a string says nothing about its place in sort order. For these predicates, SQL Server 2005 added a second object, stored with the statistics, which the documentation calls *string summary statistics*.

`DBCC SHOW_STATISTICS` is the historical command to read a statistics object. It returns three result sets: the header, the density vector and the histogram; the options `WITH STAT_HEADER`, `DENSITY_VECTOR` and `HISTOGRAM` limit the output to one of them. Since SQL Server 2012 SP1, `SELECT` permission on the table and on all the columns of the statistics is enough; before that, you had to own the table or be a member of `sysadmin`, `db_owner` or `db_ddladmin`. Two dynamic management functions partly replace it, and lend themselves better to queries over a whole database: [`sys.dm_db_stats_properties`](https://learn.microsoft.com/sql/relational-databases/system-dynamic-management-views/sys-dm-db-stats-properties-transact-sql) (SQL Server 2008 R2 SP2 and 2012 SP1) for the header, and [`sys.dm_db_stats_histogram`](https://learn.microsoft.com/sql/relational-databases/system-dynamic-management-views/sys-dm-db-stats-histogram-transact-sql) (SQL Server 2016 SP1 CU2) for the histogram. Neither returns the density vector, the `String Index` property or the content of the string summary: for string statistics, `DBCC SHOW_STATISTICS` remains the only documented command.

The [`DBCC SHOW_STATISTICS`](https://learn.microsoft.com/sql/t-sql/database-console-commands/dbcc-show-statistics-transact-sql) documentation page is practically the only place where Microsoft documents string statistics today.
It says that they are stored separately from the histogram, that they are used for `LIKE` predicates, and that they are created on the first key column of the statistics when it is `char`, `varchar`, `nchar`, `nvarchar`, `varchar(max)`, `nvarchar(max)`, `text` or `ntext`. It excludes `char` and `varchar` columns with a UTF-8 collation. No documented command shows the content of the summary.

The rest comes from two white papers, [Statistics Used by the Query Optimizer in Microsoft SQL Server 2005](https://learn.microsoft.com/previous-versions/sql/sql-server-2005/administrator/cc966419(v=technet.10)) and [its 2008 version](https://learn.microsoft.com/previous-versions/sql/sql-server-2008/dd535534(v=sql.100)). They mention a "patented technology" that summarizes the frequency distribution of substrings for pattern forms such as `'abc%'`, `'%abc'`, `'%abc%'`, `'a_c'`, `'a[bc]d'`, state that an explicit `ESCAPE` defeats these statistics, and that a string longer than 80 characters is reduced to its first 40 and last 40 characters.

Erland Sommarskog introduces string statistics through a real case where they meet row goals, in [String Summary Statistics and Row Goals](https://www.sommarskog.se/Short%20Stories/stringstats.html).

The patent is [US 6,829,602](https://patents.google.com/patent/US6829602B2/en), "System and method for using a compressed trie to estimate like predicates", filed by Microsoft in 2002. No Microsoft source in the SQL Server documentation cites it, but when you look at the summary stored in a statistics object, you find exactly the structure the patent describes.
Moreover, the engine names the selectivity calculator that uses this summary `CSelCalcTrieBased` (output of trace flag 2363, see "Reading the calculator"). As in the patent, the summary is a compressed trie of whole strings, with a count per node. The patent builds the trie from a representative set of strings, and scales the estimate up to the whole table: if a quarter of the rows were inserted, the estimate is multiplied by four. Likewise, SQL Server only stores part of the table's strings in this trie. To estimate a `LIKE`, the optimizer counts the strings of this sample that match the pattern, and multiplies the proportion by the number of rows in the table: on the `Contact.ProspectUS` table of `PachaDataFormation`, the sample database I use in my training courses and articles, 241 of the 2,825 strings in the sample end with `.org`, and the estimate is 1,000,000 × 241 / 2,825, or 85,310 rows. The section "Reading the summary" shows how to check it.

A trie (the word comes from *retrieval*) is a tree in which each path, from the root to a node, spells a string. The strings `Martin`, `Martinez` and `Marty` share a node `Mart`, which has two children, `in` and `y`; `in` has a child of its own, `ez`. A node counts how many strings of the sample end on it: 1 for `Martin`, 1 for `Martinez`, 1 for `Marty`, 0 for `Mart`. In a plain trie, each node holds a single character: `Mart` would take four nodes in a row, `M`, `a`, `r` and `t`, each with a single child. A compressed trie (also called a [radix tree](https://en.wikipedia.org/wiki/Radix_tree), or PATRICIA tree) merges these runs of single-child nodes into one node holding the whole sequence of characters: `Mart` then fits in one node instead of four. That is the shape of the SQL Server summary, where the pieces of all nodes are stored end to end in a single sequence of characters, and each node gives the position and length of its own piece in that sequence. Strings that share their beginning, such as family names or codes with a common prefix, take little space this way.

```mermaid
flowchart TD
    R(("root")) --> M["Mart<br/>0 strings"]
    M --> I["in<br/>1 string: Martin"]
    M --> Y["y<br/>1 string: Marty"]
    I --> E["ez<br/>1 string: Martinez"]
```

Everything below was measured on SQL Server 2025 CU7 (17.0.4065.4), compatibility level 170, unless the legacy estimator is mentioned. The measurements added on November 21, 2026 were made on SQL Server 2025 CU10 (17.0.5035.5), in a lab where the engine runs under a debugger, which let me read some constants in the code; I say so each time.

## Finding the string statistics

The examples use the `Contact.ProspectUS` table of `PachaDataFormation`: a million prospects, `Nom` (last name) and `Email` as `varchar`, collation `French_CI_AS`. The table has auto-created statistics on these two columns (`_WA_Sys_...`). The database load script recomputed them with `UPDATE STATISTICS ... WITH FULLSCAN`: they read the million rows (`rows_sampled` equals `rows` in `sys.dm_db_stats_properties`), not the sample an automatic creation would have taken. On a million rows, the default sampling reads enough rows to fill the string summary: `FULLSCAN` does not change its size, but it changes the strings kept, hence the estimates. Here I call `DBCC SHOW_STATISTICS` with the column name in place of the statistics name, which is supported and convenient:

```sql
USE [PachaDataFormation];
GO
-- The String Index column is YES or NO
DBCC SHOW_STATISTICS ('Contact.ProspectUS', Email) WITH STAT_HEADER;
DBCC SHOW_STATISTICS ('Contact.ProspectUS', Nom) WITH STAT_HEADER;
```

No system view shows this information: neither [`sys.stats`](https://learn.microsoft.com/sql/relational-databases/system-catalog-views/sys-stats-transact-sql) nor [`sys.dm_db_stats_properties`](https://learn.microsoft.com/sql/relational-databases/system-dynamic-management-views/sys-dm-db-stats-properties-transact-sql), nor [`sys.dm_db_stats_histogram`](https://learn.microsoft.com/sql/relational-databases/system-dynamic-management-views/sys-dm-db-stats-histogram-transact-sql). To review all the statistics of a database, you have to run `DBCC SHOW_STATISTICS ... WITH STAT_HEADER` one statistics object at a time, for instance in a cursor with `INSERT ... EXEC`.

Looking at a column, by type and by collation, with statistics on the same 100,000 values, computed with `FULLSCAN`:

| Column | `String Index` |
|---|---|
| `char`, `varchar`, `nchar`, `nvarchar`, `varchar(max)`, `nvarchar(max)`, `text`, `ntext` | `YES` |
| collations `_CS_AS`, `_BIN2`, `Latin1_General_BIN`, `SQL_Latin1_General_CP1_CI_AS`, `French_CI_AS` | `YES` |
| `nvarchar` in `Latin1_General_100_CI_AS_SC_UTF8` | `YES` |
| `varchar` in `Latin1_General_100_CI_AS_SC_UTF8` | `NO` |
| `varbinary` | `NO` |

The UTF-8 exclusion therefore only affects `char` and `varchar`, as the documentation says: an `nvarchar` declared with the same collation keeps its summary. For it, the `_UTF8` suffix changes nothing anyway: `nchar` and `nvarchar` stay in UTF-16 whatever the collation ([Collation and Unicode support](https://learn.microsoft.com/sql/relational-databases/collations/collation-and-unicode-support)), and only the comparison rules of the rest of the name apply (`Latin1_General_100_CI_AS_SC`). The suffix only changes the encoding of `char` and `varchar`, which become UTF-8. The same holds for an auto-created statistics object (`_WA_Sys_...`), with the default sampling.

The storage of the table changes nothing: a clustered columnstore index, a memory-optimized table (In-Memory OLTP) and a temporary table give the same estimate as a rowstore table on the same 200,000 strings: 781.5 rows for 899 actual with `'%A1B%'`, and `String Index` is `YES` for the columnstore and the memory-optimized table (2025 CU10). A statistics object built in parallel can take another sample, and give another estimate (see "The sample"). A table variable has no column statistics, and gets the 9% guess.

## The predicates that benefit

The cardinality estimator hands each predicate to a selectivity calculator, a specialized internal component. The ones that matter here are `CSelCalcColumnInInterval` for an interval read from the histogram, `CSelCalcHistogramComparison` for a comparison, `CSelCalcTrieBased` for the string summary and `CSelCalcFixedFilter` for a fixed guess. An undocumented trace flag shows this information, as the section "Reading the calculator" explains. If the string summary was used, the calculator is `CSelCalcTrieBased`.

On `Contact.ProspectUS`, plan estimates, actual counts and the calculator used:

```sql
USE [PachaDataFormation];
GO
-- Three ways to write the same prefix filter
SELECT Nom FROM Contact.ProspectUS WHERE Nom LIKE 'Mc%';
SELECT Nom FROM Contact.ProspectUS WHERE Nom >= 'Mc' AND Nom < 'Md';
SELECT Nom FROM Contact.ProspectUS WHERE LEFT(Nom, 2) = 'Mc';

-- A suffix
SELECT Nom FROM Contact.ProspectUS WHERE Email LIKE '%.org';
SELECT Nom FROM Contact.ProspectUS WHERE RIGHT(Email, 4) = '.org';
SELECT Nom FROM Contact.ProspectUS WHERE CHARINDEX('.org', Email) > 0;
```

| Predicate | Estimate | Actual | Calculator |
|---|---|---|---|
| `Nom LIKE 'Mc%'` | 17,699 | 17,620 | `CSelCalcTrieBased` |
| `Nom >= 'Mc' AND Nom < 'Md'` | 16,079 | 17,620 | `CSelCalcColumnInInterval` |
| `LEFT(Nom, 2) = 'Mc'` | 12,008 | 17,620 | `CSelCalcHistogramComparison(INTERVAL)` |
| `Email LIKE '%.org'` | 85,310 | 85,060 | `CSelCalcTrieBased` |
| `RIGHT(Email, 4) = '.org'` | 1 | 85,060 | `CSelCalcFixedFilter (0.1)`, then `CSelCalcPointPredsFreqBased` |
| `CHARINDEX('.org', Email) > 0` | 300,000 | 85,076 | `CSelCalcFixedFilter (0.3)` |

Surprisingly, the prefix search (`Nom LIKE 'Mc%'`) goes through the string summary rather than the histogram, and gets a better result: for the equivalent interval, the histogram has to spread the rows of the steps where the bounds fall, whereas the summary counted the strings of its sample. `LEFT` is estimated as an interval, by another computation on the histogram. On another test table, the gap becomes huge. It has a million rows, and the 1,000 values starting with `QA1` are the highest of the column: they all fall into the last step of the histogram. The interval `s >= 'QA1' AND s < 'QA2'` is estimated there at 2 rows. `LIKE 'QA1%'`, which goes through the summary, is estimated at 710 or 1,065 rows, depending on the statistics rebuild (see "The sample").

For `RIGHT`, the output of trace flag 2363 shows two computations: a fixed guess of 10%, then an equality estimate drawn from the density of the `Email` column, which is nearly unique, and gives one row for 85,060 actual rows. `CHARINDEX` gets a fixed guess of 30%: no statistics describe its result, and the optimizer applies 30% to any `>`, `>=`, `<` or `<=` comparison it cannot estimate, such as `LEN(Email) > 10` or `Email > @v` with a local variable. `Email <> @v` gets 90%; `Email = @v` is estimated from the density. On a function of the column, `=` goes through 10% then through the density, like `RIGHT` (`LEN(Email) = 10`: one row), and `<>` is estimated like a `<` or a `>` (`LEN(Email) <> 10`: 510,000).

On the test set, with three-character strings placed at the start, middle or end of the string, the patterns `'abc%'`, `'%abc'`, `'%abc%'`, `'a_c%'`, `'%a[bc]_%'` and `NOT LIKE` all go through the summary. It follows the collation: `'%Vill%'` and `'%vïll%'` give the same estimate on a `French_CI_AI` column; with `_CS_AS` or `_BIN2`, `'%zqw'` and `'%ZQW'` are estimated separately, each fairly close to reality.

The walk of the summary applies the collation character by character, when it sees characters, and this leaves three gaps, measured on 20,000-row test tables (2025 CU10):

- an equivalence between one character and two is not applied. In `Latin1_General_100_CI_AI`, `ß` equals `ss`. On a column where half the rows contain `straße` and the other half `strasse`, `'%ß%'` does return all 20,000 rows, but the estimate only counts the strings of the sample written with `ß`: 10,317. The same goes for `Æ` and `ae`: 9,941 and 10,059 for 20,000;
- in a `varchar` column in `Japanese_CI_AS`, the walk compares bytes, not characters. `ア` is written 0x83 0x41, and 0x41 is the code of `A`. On a column where a quarter of the rows contain `ア` and none contains an `A`, `'%A%'` is estimated at 4,990 rows for 0;
- with an `_SC` collation, `LIKE` counts `_` as one character, even outside the Basic Multilingual Plane, whereas the walk counts it as one UTF-16 code unit. With Gothic letters, which take two units each, `N'%𐌰_𐌱%'`, which returns 5,000 rows, is estimated at the floor, and `N'%𐌰__𐌱%'`, which returns none, at 4,990.

A pattern with several wildcards is estimated as a whole, with no independence assumption between its pieces. On 100,000 rows, with `AAA` and `BBB` each present in half of the strings: when they never appear in the same string, `'%AAA%BBB%'` is estimated at 3.6 rows for 0; when they always appear together, at 49,982 for 50,000.

The legacy estimator (`USE HINT ('FORCE_LEGACY_CARDINALITY_ESTIMATION')`) reads the same summary: same estimates, to the decimal, for all the measured `LIKE` predicates on literals that it estimates through the summary. Its estimates without the summary do differ (see below). `NOT LIKE` is the exception: on 100,000 rows of which one in ten is `NULL`, `s NOT LIKE '%A1%'` returns 83,409 rows. The current estimator estimates 83,634, by removing the `NULL` values of the sample; the legacy estimator estimates 93,637, that is 100,000 minus the estimate of the `LIKE`, as if the `NULL` values satisfied `NOT LIKE` (2025 CU10).

## Reading the calculator

The calculator names come from trace flag 2363, which is undocumented. Together with trace flag 3604, it writes the details of the current estimator's selectivity computation to the messages tab:

```sql
USE [PachaDataFormation];
GO
SELECT Nom
FROM Contact.ProspectUS
WHERE Email LIKE '%.org'
OPTION (RECOMPILE, QUERYTRACEON 3604, QUERYTRACEON 2363);
```

```text
Plan for computation:
  CSelCalcTrieBased
      Column: QCOL: [PachaDataFormation].[Contact].[ProspectUS].Email
Selectivity: 0.0853097
```

> Note :
>
> [`QUERYTRACEON`](https://learn.microsoft.com/sql/t-sql/queries/hints-transact-sql-query) enables a trace flag for one query, like [`DBCC TRACEON`](https://learn.microsoft.com/sql/t-sql/database-console-commands/dbcc-traceon-transact-sql). Like `DBCC TRACEON`, it requires sysadmin on the instance. With the legacy cardinality estimator, the engine rejects this trace flag (error 10781). The `query_optimizer_estimate_cardinality` extended event gives the same information, in its `calculator` field (`CalculatorName="CSelCalcTrieBased"`). The `OptimizerStatsUsage` property of the plan lists the statistics used without saying whether their string summary was involved.


## The limits of the summary

The string summary cannot be used in the following cases:

- The column is used in an expression or passed to a function;
- The pattern is in a local variable, alone or concatenated with wildcards, unless `OPTION (RECOMPILE)` is used;
- The pattern is `nvarchar` while the column is `varchar`, whether it is an `N'...'` literal or a parameter;
- The `LIKE` has an `ESCAPE` clause, even a useless one;
- The column is `char` or `varchar` with a UTF-8 collation: its statistics have no summary;
- The column is not the first column of any statistics object;
- The pattern contains no wildcard: it is then an equality, estimated from the histogram;
- A piece of the pattern, before, between or after the `%` signs, exceeds 40 characters, `_` included: the summary calculator fails, and the output of trace flag 2363 says so (`Calculator failed. Replanning.`). A prefix then falls back on the histogram, a pattern with a leading wildcard on the 9% guess. On a million strings, `'%' + REPLICATE('A', 40) + '%'` is estimated at the floor, 35.4, and the same pattern with 41 `A` at 90,000 (measured on `varchar`, 2025 CU10);
- The `LIKE` compares two columns, as in a join `ON a.s LIKE b.motif`: the current estimator applies 9% to the product of the two tables, without exceeding the larger one, and the legacy estimator returns the row count of the larger one. A pattern taken from a subquery gets 9%, and the local variable formula with the legacy estimator (see below) (2025 CU10);
- The search uses `REGEXP_LIKE`, new in SQL Server 2025 and available at compatibility level 170: 9% in my tests, and 30% with the legacy estimator (2025 CU10). The [documentation](https://learn.microsoft.com/sql/t-sql/functions/regexp-like-transact-sql) describes two hints that change this default selectivity, `ASSUME_FIXED_MIN_SELECTIVITY_FOR_REGEXP` and `ASSUME_FIXED_MAX_SELECTIVITY_FOR_REGEXP`, which *CE feedback* can apply on its own.

The following table shows the estimate of various predicates on a test table of a million random hexadecimal strings, where 1,000 strings start with `QA1`, 10,000 contain `QB2` and 100,000 end with `QC3`. All the forms look for the 10,000 strings that contain `QB2`, and all were measured with the same statistics. In the table, CE 170 is the current estimator and CE 70 the legacy estimator.

| Form | Estimate, CE 170 | Estimate, CE 70 | Actual |
|---|---|---|---|
| `s LIKE '%QB2%'` | 9,936 | 9,936 | 10,000 |
| `s LIKE '%QB2%' ESCAPE '\'` (useless escape) | 90,000 | 204,072 | 10,000 |
| `LOWER(s) LIKE '%qb2%'` | 90,000 | 179,744 | 10,000 |
| `s LIKE @m`, local variable | 90,000 | 51,018 | 10,000 |
| `s LIKE '%' + @m + '%'` | 90,000 | not measured | 10,000 |
| `s LIKE '%' + 'QB2' + '%'`, concatenated literals | 9,936 | not measured | 10,000 |
| `s LIKE @m OPTION (RECOMPILE)` | summary estimate | not measured | 10,000 |
| `s LIKE @m` in `sp_executesql` or a procedure | summary estimate, for the compiled value | not measured | 10,000 |
| `varchar` column with a UTF-8 collation | 90,000 | 204,072 | 10,000 |
| `s LIKE N'%QB2%'`, `nvarchar` literal or parameter on a `varchar` column | 90,000 | not measured | 10,000 |

In practice:

- To search for a wildcard character, escape it with brackets rather than with `ESCAPE`: `'%K[_]9%'` is estimated through the summary (`CSelCalcTrieBased`), `'%K\_9%' ESCAPE '\'` gets the 9% guess; even a useless `ESCAPE`, `'%QB2%' ESCAPE '\'`, goes from 9,936 to 90,000. The 2005 white paper already stated that an `ESCAPE` causes the selectivity to be estimated without the summary, and this is still true on SQL Server 2025, with a literal pattern.
- A function around the column (`LOWER`, `UPPER`, `RTRIM`) loses the summary. On a case-insensitive collation, `LOWER` adds nothing to the result and costs the estimate: 90,000 for `'%qb2%'`, and 3 rows for `LOWER(s) LIKE 'qa1%'`, estimated from the histogram, against 1,065 for `s LIKE 'QA1%'` (1,000 actual). On `Contact.ProspectUS`, `LOWER(Email) LIKE '%.org'` also gets the guess of 90,000.
- A local variable is not sniffed at compile time: the 9% guess applies, unless `OPTION (RECOMPILE)` is used. A parameter is sniffed, for its first value only: a procedure compiled for `'%QA1%'` (estimated at 1,065) kept that plan for `'%QC3%'`, which returns 100,000 rows.
- An `nvarchar` pattern compared with a `varchar` column also loses the summary: on `Contact.ProspectUS`, `Email LIKE N'%.org'` gets the 9% guess (`CSelCalcFixedFilter (0.09)`), as does an `@m nvarchar(20)` parameter passed through `sp_executesql`, whereas a `varchar(20)` parameter gets the summary estimate. An `nvarchar` prefix goes through the histogram, and fares badly: `Email LIKE N'ab%'` is estimated at 430 rows, against 2,478 for `'ab%'`, for 2,669 actual rows. SqlClient infers `NVarChar` from a .NET `String` when the parameter type is not specified ([Configuring parameters](https://learn.microsoft.com/sql/connect/ado-net/configure-parameters)), and the JDBC driver sends strings as Unicode as long as `sendStringParametersAsUnicode` is `true`, its default ([connection properties](https://learn.microsoft.com/sql/connect/jdbc/setting-the-connection-properties)). So you have to declare the parameter with the column's type, which is nothing new.
- Switching a `varchar` column to a UTF-8 collation removes the summary from its statistics. `LIKE` patterns that start with a wildcard are estimated at 9%, prefixes go through the histogram (`'QA1%'`: 2 rows estimated for 1,000), but only on SQL Server 2025 at compatibility level 170. Erik Darling noticed that this is an optimizer hotfix (in a message to Erland Sommarskog, November 2026): at level 160 the prefix gets the 9% guess, unless the `ENABLE_QUERY_OPTIMIZER_HOTFIXES` hint is used, and SQL Server 2022 stays at 9% even with the hint. I checked it on 2025 CU11 and 2022 CU26: on a million strings, `'AB%'` (3,934 actual rows) is estimated at 3,656 at level 170 or with the hint, and at 90,000 otherwise. On a UTF-8 copy of the test set, `'%QC3'` went from 100,852 (for 100,000) to 90,000, and `'%QB2%'` from 9,233 (for 10,000, on another build of the statistics) to 90,000. The hotfix estimates only pure prefixes from the histogram alone: on 100,000 UTF-8 strings, `'AB%'` is estimated at 489.5 rows for 408, whereas `'AB_%'`, `'AB%C%'` and even `'[A]B%'`, which is equivalent to `'AB%'`, get that interval multiplied by 9%, or 44.1 (`CSelCalcFilterWithResidualGuess`, 2025 CU10).
- A multi-column statistics object only has a summary for its first column, as with its histogram.
- Trailing spaces are stored in the summary. On 100,000 `char(20)` rows of which one in 40 ends with `qrs`, `'%qrs'` does return these 2,500 rows, padded with spaces, but the summary finds none of them: estimate at the floor, 3.55. A `varchar` that holds a trailing space behaves the same way. With `nchar`, the same pattern returns no rows and gets the floor, 4.17 rows: `LIKE` and the summary then both take the trailing spaces into account (2025 CU10). This is the rule of [`LIKE`](https://learn.microsoft.com/sql/t-sql/language-elements/like-transact-sql): trailing spaces of the matched expression are ignored for non-Unicode data, and significant for `nchar` and `nvarchar`.

These estimates without the summary differ by estimator. The current estimator applies 9% to any `LIKE` with a leading wildcard that it cannot estimate (`CSelCalcFixedFilter (0.09)`), whatever the length of the pattern. A prefix with `ESCAPE` is estimated from the histogram (`'QA1%' ESCAPE '\'`: 2 rows for 1,000); on a UTF-8 column, a prefix without `ESCAPE` is estimated that way only under the version conditions given above.

The legacy estimator depends on the length of the pattern: on this million-row set, without the summary, `'%Q%'` gives 612,216, `'%QB%'` 306,108, `'%QB2%'` 204,072, an eleven-character pattern 55,656. Erik Darling found the formula (in the same message), which I checked to the decimal on SQL Server 2025 CU11 and 2022 CU26: the selectivity is 0.18 × ln(L) / n, where n is the length of the pattern without the wildcards and L a string length. For the bare column, L is the average length given by the statistics, in bytes, rounded down to the integer: on a million 20-character strings, `'%QZQZQZQZ%' ESCAPE '\'` is estimated at 67,404, that is 0.18 × ln(20) / 8, and at 92,122.8 on 60-character strings, whatever the declared length of the column. The 61.2% of `'%Q%'` thus corresponds to an average length of 30 characters, and the 41% to 74% measured on other sets to lengths of 10 to 60. A suffix `'%QC3'` gets half the estimate, 102,036.

The factor 0.18 is twice 0.09, because the pattern contains two `%`. The function that does this computation is called `CCardUtilSQL7::ProbLikeGuess`. Under the debugger, it receives the number of counted characters of the pattern, the number of `%` and the average length of the column in bytes (2025 CU10), and, when the pattern has at least one counted character and does not exceed the maximum length of the column, the selectivity is 0.09 × k × ln(L) / n, capped at 1, where k is the number of `%` (at least 1) and where ln(L) is replaced by 1 when it is smaller. A pattern longer than the column gets 0, a pattern with no counted character 1 or 9% depending on whether it contains a `%` or not. A suffix has only one `%`, hence the half. `'%Q%Z%'` has three: on 100,000 strings of 20 characters, it is estimated at 40,442, that is 0.27 × ln(20) / 2. n counts all the characters of the pattern except `%`, `_` and `[`, so that `'%Q[AB]Z%'` counts five characters (`Q`, `A`, `B`, `]` and `Z`). With `nvarchar`, L is also counted in bytes: 40 for 20-character strings. For a pattern in a local variable, which the optimizer does not know, the function receives n = 6 and k = 0, which gives 0.09 × ln(L) / 6: this is the formula [Paul White gave on DBA Stack Exchange](https://dba.stackexchange.com/a/153618), and it gives the 51,018 of the table for strings of 30 characters on average.

When the column is inside an expression (`COLLATE`, `LEFT`, `LOWER`), L also depends on the optimization level, as Erik Darling noticed and as Erland Sommarskog reports ([String Summary Statistics and the Legacy Cardinality Estimator](https://www.sommarskog.se/Short%20Stories/stringstats.html#legacyestimator)). With full optimization, L is half the declared length of the column; in a trivial plan, it is the average length from the statistics. On these 20-character strings in a `varchar(80)`, `s COLLATE Latin1_General_CI_AS LIKE '%QZQZQZQZ%'` is estimated at 82,999.8 with full optimization (0.18 × ln(40) / 8), and at 67,404 in a trivial plan. In a `varchar(160)`, full optimization gives 98,595.6 (0.18 × ln(80) / 8). The optimization level shows in the `StatementOptmLevel` property of the plan. With `cost threshold for parallelism` at 5, all these queries were fully optimized; at 50, they got a trivial plan.

The values of the CE 70 column of the table are therefore specific to this set, while the 90,000 of the current estimator show up everywhere.

## Reading the summary

The summary is stored in the statistics blob, along with the histogram. `DBCC SHOW_STATISTICS ... WITH STATS_STREAM` returns the whole blob, preceded by a 64-byte header, and it can be captured in T-SQL with `INSERT ... EXEC` into a `varbinary(max)` column. The small table example below does just that.

The format is undocumented. I used Claude to work it out, and it did so by building tables of a few rows whose every byte it knew, changing only one thing from one table to the next, then comparing the blobs.

The summary follows the histogram, after a fixed marker. Its header gives:

- the number of NULLs met by the sampling;
- the number of sampled values, NULLs included;
- the number of distinct values in the sample, where NULL counts as one;
- 40 twice, the truncation lengths;
- eight zero bytes;
- the number of characters that follow.

Then come the characters of the sample, end to end, then the nodes of the trie.

The easiest way is to see it on a small table. This one has eight names, with `Martin` twice; under eleven rows, the sample keeps them all:

Measurement details:

```sql
USE [PachaDataFormation];
GO
CREATE TABLE dbo.DemoTrie (Nom varchar(50) COLLATE French_CI_AS);
INSERT dbo.DemoTrie (Nom)
VALUES ('Martin'), ('Martinez'), ('Marty'), ('Martin'),
       ('Dupont'), ('Durand'), ('Dubois'), ('Dupuis');
CREATE STATISTICS st_Nom ON dbo.DemoTrie (Nom) WITH FULLSCAN;
GO
-- The statistics blob, in hexadecimal
DECLARE @stream TABLE (stats_stream varbinary(max), [rows] bigint, data_pages bigint);
INSERT @stream EXEC ('DBCC SHOW_STATISTICS (''dbo.DemoTrie'', st_Nom) WITH STATS_STREAM');
SELECT CONVERT(varchar(max), stats_stream, 2) AS blob FROM @stream;
GO
DROP TABLE dbo.DemoTrie;
```


The summary header announces 0 NULLs, 8 sampled values, 7 distinct, then 26 characters, which are the pieces of all the nodes end to end: `DuboispontuisrandMartinezy`. Eleven five-byte nodes follow, in preorder:

| Node | Bytes | Flags | Piece | Position | Count | String |
|---|---|---|---|---|---|---|
| 0 | `40 00 00 00 00` | has children | (empty) | 0 | 0 | root |
| 1 | `c0 02 00 00 00` | next sibling, has children | `Du` | 0 | 0 | `Du` |
| 2 | `81 04 02 00 00` | next sibling | `bois` | 2 | 1 | `Dubois` |
| 3 | `c0 01 06 00 00` | next sibling, has children | `p` | 6 | 0 | `Dup` |
| 4 | `81 03 07 00 00` | next sibling | `ont` | 7 | 1 | `Dupont` |
| 5 | `01 03 0a 00 00` | last child | `uis` | 10 | 1 | `Dupuis` |
| 6 | `01 04 0d 00 00` | last child | `rand` | 13 | 1 | `Durand` |
| 7 | `40 04 11 00 00` | has children | `Mart` | 17 | 0 | `Mart` |
| 8 | `c2 02 15 00 00` | next sibling, has children | `in` | 21 | 2 | `Martin` |
| 9 | `01 02 17 00 00` | last child | `ez` | 23 | 1 | `Martinez` |
| 10 | `01 01 19 00 00` | last child | `y` | 25 | 1 | `Marty` |

The first byte holds the flags: `0x80` when the node has a sibling after it, `0x40` when the next node is its first child. Its four low bits store the count when it does not exceed 15: 2 for `Martin`, 1 for the other strings, 0 for nodes where no string ends, such as `Du` or `Mart`. A larger count adds one byte after the node, flagged by `0x10`, or four, flagged by `0x20` (249 is the largest one-byte count I have seen, 295 the smallest four-byte one). The second byte gives the length of the piece, the next three its position in the character sequence. The string of a node is the sequence of its ancestors' pieces, then its own: you read `Du`, then `p`, then `ont`, and get `Dupont`.

```mermaid
flowchart TD
    R(("root")) --> DU["Du · 0"]
    R --> MART["Mart · 0"]
    DU --> BOIS["bois · 1: Dubois"]
    DU --> P["p · 0"]
    DU --> RAND["rand · 1: Durand"]
    P --> ONT["ont · 1: Dupont"]
    P --> UIS["uis · 1: Dupuis"]
    MART --> IN["in · 2: Martin"]
    MART --> Y["y · 1: Marty"]
    IN --> EZ["ez · 1: Martinez"]
```

The summary stores no substrings: these are whole strings, as `varchar` in the column's code page, as `nvarchar` in UTF-16. With a case-insensitive collation, `MiXeD`, `mixed` and `Mixed` make a single entry, with a count of 3.

So there is only one trie per statistics object, and it stays small: about 2,800 strings at most, of 80 characters at most, some 224 KB before the sharing of common beginnings, and the summary weighs around 200 KB (194 KB for `varchar`, 212 KB for `nvarchar` in my tests) when SQL Server halves the sample, because of a memory space limit during the build (see "The sample"). Nor is the trie used as a search engine. For `LIKE '%.org'`, the estimate equals exactly the number of strings of the sample that match the pattern. Judging by the functions the call stacks show, the optimizer walks the tree applying the pattern, piece by piece, to each path from the root to the leaves; the section "Compile time" shows the cost of this walk. A trie only speeds up searching by the start of a string anyway, which is of no use for a pattern starting with `%`. It serves mainly to store the sample compactly and to count duplicates.

The script [`string-summary.sql`](https://github.com/rudi-bruchez/tsql-scripts/blob/main/database-information/statistics/string-summary.sql) decodes the summary of a statistics object, lists the sampled strings and computes the estimate the summary gives for a pattern, provided the predicate uses it (pattern of the column's type, no function around the column). Run as is, on the statistics of `Contact.ProspectUS.Email`, it finds 2,825 sampled values, 29 of them NULL, and 241 strings matching `'%.org'`: 1,000,000 × 241 / 2,825 = 85,309.7, the plan estimate.

## The sample

A 10,000-row table of values `0000001` to `0010000` gives a summary of 510 strings, 19 or 20 values apart in sort order. The same values inserted in reverse order, or in random order, give the same 510 strings: the sample is taken at a fixed step in the sorted stream of the build, whatever the physical order of the rows. A value present in 30% of the rows takes 153 of the 510 places, which is 30%.

Its size is 5% of the rows read by the statistics plus 10, without exceeding the number of rows (a four-row table keeps them all): 510 strings for 10,000 rows, 1,010 for 20,000, 2,510 for 50,000. With sampling, it is 5% of the sampled rows: on a table of 40,000 wide rows, `SAMPLE 2 PERCENT` reads 984 rows, and the summary keeps 59 strings, against 2,018 with `FULLSCAN`. A filtered statistics object applies the sampling rate of the whole table to the rows that pass its filter, in my test: on 100,000 rows, a statistics object `WHERE id <= 20000` with `FULLSCAN` keeps 565 strings, that is 2,824 × 20%, and not the 1,010 that 5% of the 20,000 rows plus 10 would give (2025 CU10).

The size then levels off around 2,820: the cap is reached around 56,000 rows, and it holds up to 3,000,000, the largest table measured (2,814 to 2,830 depending on the data and on parallelism).

The cap is also a space limit, not only a number of strings: when the sample does not fit in the summary, SQL Server keeps one string out of two. On 200,000 distinct and dissimilar strings, with `MAXDOP = 1`, the sample keeps 2,824 strings of 65 characters, and drops at once to 1,412 strings of 66 characters; just before the cut, at 65 characters, the stored statistics weighed 211 KB and its summary 193 KB. What counts is the space taken in the trie, not the length: 200-character strings that share their beginning keep all 2,824.

The limit can be read in the build code (2025 CU10): a new node is refused when a counter, which adds up the stored characters and 48 bytes per node, reaches 327,680 bytes (320 KiB), and the build starts again with a sampling rate divided by two.

Measurement details:

A split also creates a node: when a string shares the beginning of an existing node, that node is split in two. With 66-character strings, the counter stood at 327,663 bytes when the node was refused: 179,983 characters (strings are stored without the beginning they share), 2,806 string nodes and the root, and 271 nodes created by splits, at 48 bytes each, minus 64 bytes. The roughly 194 KB of the summary are the compact form of the same trie: five bytes per node as long as its count does not exceed 15, instead of 48 in memory.


With `nvarchar`, the starting cap is lower, 2,409 strings, and it drops to 1,205 between 43 and 44 characters (86 and 88 bytes), for a summary of about 212 KB against 194 KB for `varchar` at the same point. This starting cap only depends on the character width: 2,824 for `char`, `varchar` and `varchar(max)`, 2,409 for `nchar`, `nvarchar` and `nvarchar(max)`, whatever the declared length of the column, its collation (`BIN2`, SQL collation, Japanese or UTF-8) or the length of the strings below the threshold. These two caps are constants in the SQL Server 2025 code: 2,409 for two-byte characters, and 2,409 + 415 = 2,824 for one-byte characters.

The target size is the smallest of three values: the cap, 5% of the rows read plus 10, and the number of rows read. It is used to compute an acceptance rate, and the final count can exceed it by a few strings: 2,825 on `Contact.ProspectUS`, up to 2,830 in parallel. I see this as a rounding effect of the draw, without having checked it in the code. The sample of the e-mail addresses of the demo database holds 2,410 strings as `nvarchar`, against 2,825 as `varchar`.

The estimate of a `LIKE` with a wildcard can then be computed exactly: the number of rows in the table, multiplied by the number of strings of the sample that match the pattern, divided by the size of the sample. When no string matches, the count is 0.1. On ten patterns (`'%x%'`, `'x%'`, `'%x'`, `_`, `[bc]`, two internal `%`), the computation done on the decoded sample gave the plan estimate to the decimal. An equality without wildcard goes through the histogram.

Estimates therefore move in steps of one sampled string, 354 rows on the million prospects (1,000,000 / 2,825), with a floor of 35.4:

```sql
USE [PachaDataFormation];
GO
-- Estimate against actual count, for names of different frequencies
SELECT Nom FROM Contact.ProspectUS WHERE Nom LIKE '%Aguila';
SELECT Nom FROM Contact.ProspectUS WHERE Nom LIKE '%Baldwin';
SELECT Nom FROM Contact.ProspectUS WHERE Nom LIKE '%Wilson';
```

| Pattern | Actual | Estimate | Sampled strings |
|---|---|---|---|
| `'%Abajian'` | 1 | 35.4 | 0 (floor) |
| `'%Aguila'` | 38 | 35.4 | 0 (floor) |
| `'%Baldwin'` | 150 | 354 | 1 |
| `'%Castro'` | 391 | 708 | 2 |
| `'%Campbell'` | 421 | 708 | 2 |
| `'%Wilson'` | 712 | 708 | 2 |
| `'%Johnson'` | 1,105 | 1,062 | 3 |

The same floor shows on tables of different sizes:

| Table rows | Lowest estimate | Rows / lowest estimate |
|---|---|---|
| 10,000 | 1.96 | 5,100 |
| 30,000 | 1.99 | 15,100 |
| 100,000 | 3.55 | 28,140 |
| 1,000,000 | 35.51 | 28,160 |
| 3,000,000 | 106.50 | 28,170 |

The ratio is ten times the sample size: 5,100 for 510 strings, 15,100 for 1,510, 28,140 for 2,814. On the three-million-row table, a substring present 1, 10 or 100 times is estimated at 106.5, like an absent substring; at 999 occurrences, it is estimated at 1,065, one string of the sample; at 10,000, at 11,719, eleven strings of a sample of 2,816, built another time. For 200-character strings that are all different, the sample drops to about 1,410 strings as `varchar` (1,200 as `nvarchar`), and the floor to about the number of rows divided by 14,000.

Such a small sample still estimates frequent patterns well, because its precision depends on the number of strings that match the pattern, not on the fraction of the table it represents. That is the principle of polling: a thousand people interviewed give the same margin of error for a small town as for a large country. For a proportion p measured on n strings, the typical relative error is about √((1 − p) / (n × p)). With `'%.org'`, 241 strings of the sample match the pattern, and the expected error is about 6%: the estimate of 85,310 for 85,060 actual rows is therefore partly luck, a 10% gap would have been just as normal.

The fixed step in sort order also favors prefixes. The rows matching `'Mc%'` form a contiguous block in that order, and a step of 354 rows always lands in it 49 or 50 times: the error does not exceed one sampled string, or 354 rows, and you get 17,699 estimated rows for 17,620. A suffix or a substring, scattered across the sort order, has no such advantage, and the sample behaves for them roughly like a random draw.

For a rare pattern, the precision is that of a sample of a few dozen strings. A substring present in 1% of a million rows, so 28 strings expected in the sample, appeared 27, 32, 28 then 27 times over four successive `UPDATE STATISTICS ... WITH FULLSCAN`, with no change to the data: estimates of 9,585, 11,356, 9,947 and 9,581 for 10,000. In parallel, the sample size also varied, from 2,815 to 2,818 strings. With `MAXDOP = 1`, the rebuilds all give the same sample, of 2,824 strings, which here held the substring 22 times: 7,790 estimated rows. Parallelism changes the sample: according to the debugger, each thread of the build takes its own sample, at the rate computed for the whole table, and builds its own trie, then a fifth trie, which only receives the rate, probably merges those of the threads. On a million rows at `MAXDOP 4`, the debugger shows these four threads and this fifth trie, and the summary holds 2,822 strings instead of 2,824. Each thread rounds its own step, and the distribution of rows between threads changes from one build to the next, hence different samples (this is my interpretation of the counts: the debugger did not show me the distribution). On three rebuilds of another table, the same effect had given 5,329, 10,653 and 6,392 for 10,000.

The SQL Server 2005 documentation ([Index Statistics](https://learn.microsoft.com/previous-versions/sql/sql-server-2005/ms190397(v=sql.90))) warned that the summary is not kept when it exceeds what the engine can maintain, with the example of 85,000 unique and dissimilar `varchar(80)` values, with `FULLSCAN`. The example no longer reproduces: with 85,000 unique 80-character values, `String Index` is `YES`, and the sample is reduced to 1,413 strings.

## Beyond 80 characters

The white paper rule still holds. A table of 100,000 strings of 200 characters, with a three-character substring placed at position 5, 60, 100 or 190, a quarter of the rows each:

| Substring position | `varchar` | `nvarchar` | Actual |
|---|---|---|---|
| 5 | 24,645 | 24,083 | 25,000 |
| 60 | 7 | 8 | 25,000 |
| 100 | 7 | 8 | 25,000 |
| 190 | 24,503 | 26,000 | 25,000 |

Positions 60 and 100 fall outside the first 40 and the last 40 characters: the sample does not contain them, and they get the floor. With strings of 79 to 82 characters and a substring straddling the 40th and 41st characters, the estimate is right at 79 and 80 characters (25,710 and 25,994), and drops to 1,634 then 1,136 at 81 and 82, for Latin1 `varchar` as for `nvarchar`; these two values come from chance occurrences elsewhere in my hexadecimal strings, and a substring found nowhere else drops to the floor.

The summary stores the first 40 and the last 40 characters joined together, so a pattern can match across the junction. On 100,000 strings of 200 characters with a `Q` at position 40 and a `W` at position 161, `'%QW%'`, which appears in no row, is estimated at 100,000; `'%Qm%'` and `'%mW%'`, present in every row, are estimated at 3.5.

For `varchar`, the threshold is counted in bytes. On a `varchar` column in `Japanese_CI_AS` whose first ten characters take two bytes each, a substring at characters 39 to 41 stays visible in a 76-character string (86 bytes), and disappears in a 79-character string (89 bytes): 3.6 rows estimated for 25,000. The same value as `nvarchar` is still estimated at 24,230.

For `nvarchar`, the threshold is counted in two-byte UTF-16 code units. A character outside the Basic Multilingual Plane, stored as a surrogate pair, counts twice. On 500,000 strings in `Czech_100_CI_AS_SC` made of Gothic letters, a GUID, then Gothic letters, `'%123%'` is estimated at 2,502 for 2,464 rows when the Gothic prefix is 30 units long (15 characters), and falls to the floor, 20.6 for 2,448, at 40 units, only 20 characters. For letters of the Basic Multilingual Plane, such as the Latin alphabet, Greek or Japanese, a unit is a character.

On `varchar(max)` columns of 100 to 20,000 characters, a prefix and a suffix are well estimated, with the imprecision of a sample of about 1,400 strings; everything in between is invisible. For a comments or descriptions column, a `LIKE '%word%'` whose occurrences are only in the middle of the texts can therefore get the estimate of an absent pattern, as in these tests. To search for words in long text, full-text search (`CONTAINS`) is the intended tool; it finds words and word prefixes, and misses a fragment taken from the middle of a word.

## Compile time

Walking the summary has a cost, usually invisible: on a million hexadecimal strings, a pattern of one to ten pieces separated by `%` compiles in a few milliseconds. This cost changes scale when the column repeats a character and the pattern contains several `%` followed by that character. Zero-padded order references are enough:

Measurement details:

```sql
USE PachaDataFormation;
GO
SET NOCOUNT ON;
CREATE TABLE dbo.DemoCommande (
    CommandeId int NOT NULL PRIMARY KEY,
    Reference varchar(30) NOT NULL
);
-- 200,000 zero-padded references: CMD00000000000000000001, ...
INSERT dbo.DemoCommande (CommandeId, Reference)
SELECT n, 'CMD' + RIGHT(REPLICATE('0', 20) + CAST(n AS varchar(20)), 20)
FROM (SELECT TOP (200000) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS n
      FROM sys.all_columns AS a CROSS JOIN sys.all_columns AS b) AS t;
CREATE STATISTICS st_Reference ON dbo.DemoCommande (Reference) WITH FULLSCAN;
GO
-- The compile time shows in the messages tab
SET STATISTICS TIME ON;
GO
SELECT COUNT(*) FROM dbo.DemoCommande WHERE Reference LIKE '%0%0%9%' OPTION (RECOMPILE);
GO
SELECT COUNT(*) FROM dbo.DemoCommande WHERE Reference LIKE '%0%0%0%0%0%9%' OPTION (RECOMPILE);
GO
SELECT COUNT(*) FROM dbo.DemoCommande WHERE Reference LIKE '%0%0%0%0%0%0%0%0%9%' OPTION (RECOMPILE);
GO
SET STATISTICS TIME OFF;
GO
DROP TABLE dbo.DemoCommande;
```


The three queries return the same 81,902 rows. On SQL Server 2025 CU10, with a database at compatibility level 160 and the `French_CI_AS` collation, three runs of the script (in a database with `SQL_Latin1_General_CP1_CI_AS` at level 170, compilation takes 1.3 to 1.6 s and 5.8 to 6.8 s for the last two patterns, and execution 30 to 50 ms):

| Pattern | Compilation (CPU) | Execution (CPU) |
|---|---|---|
| `'%0%0%9%'` | 60 to 63 ms | 210 to 224 ms |
| `'%0%0%0%0%0%9%'` | 2.35 to 2.53 s | 221 to 243 ms |
| `'%0%0%0%0%0%0%0%0%9%'` | 10.9 to 11.1 s | 239 to 260 ms |

All this time is spent in cardinality estimation, before a single row is read. The call stacks taken during compilation show, under `CTrieInMemCore::FFilterLike`, two functions of the summary walk that call each other, `ConsumeChildren` and `ConsumeNodeString`. I interpret this as backtracking: each `%` can absorb any number of characters, and when the rest of the pattern fails, the walk goes back to the previous `%` to try another position. In a reference that holds up to nineteen zeros, there are many ways to place five `0`, and the walk tries them before concluding that no `9` follows. On a test table of 50,000 strings made of 30 to 79 `A` followed by a number, `'%A%A%B%'` compiles in 0.7 s, `'%A%A%A%B%'` in 14 s, and with one more `%A` the compilation takes more than two minutes.

The behavior is old: the same table, created in a new database at the default compatibility level of each version, compiles `'%0%0%0%0%0%9%'` in 1.7 to 2.3 s on SQL Server 2017 CU31, 2019 CU32, 2022 CU27 and 2025 CU10 (1.9 s at level 170 for the latter).

SQL Server 2025 contains a bound, enabled by default, but which the optimizer only applies at compatibility level 170 or with the `ENABLE_QUERY_OPTIMIZER_HOTFIXES` hint. It stops the walk after 11 billion calls, which still lets compilations of several seconds through: my measurements at level 170 were made with the bound active.

The walk does, however, check regularly whether the query must stop: a `KILL` interrupted it at once in my tests. I did not check separately that the work stops on the server after a client timeout.

A procedure parameter is estimated through the summary for its compile-time value, and so pays this cost at each compilation: 6.5 s for eight `%0` on a set of the same shape, at level 170. A local variable without `OPTION (RECOMPILE)`, or `OPTION (OPTIMIZE FOR UNKNOWN)`, avoids it, at the price of the 9% guess. The realistic case is an application that builds a pattern with several `%` from user input, on a column of codes.

The problem is known outside SQL Server. Russ Cox measured it in 2017 on shell wildcards, in [Glob Matching Can Be Simple And Fast Too](https://research.swtch.com/glob): with backtracking, the pattern `a*a*a*b` applied to a run of `a` takes time exponential in the number of `*`. By resuming the search only at the last `*` met, there is no more backtracking on the earlier `*`, and the cost, according to the code he publishes, is at most proportional to the length of the pattern times the length of the string. The case of the strings of `A` has the same shape.

## Key points

- A `LIKE` that compares the column, without a function around it, to a literal is often better estimated than you would think, `'%abc%'` included. Write it that way rather than with `LEFT`, `RIGHT`, `CHARINDEX` or `LOWER`.
- Escape a wildcard with brackets, not with `ESCAPE`.
- A pattern in a local variable gets a fixed guess; `OPTION (RECOMPILE)` brings back the summary estimate, and a parameter of the column's type gets it for its compiled value.
- A `varchar` with a UTF-8 collation has no string summary; an `nvarchar` with the same collation has one.
- Pass the pattern in the column's type: an `nvarchar` literal or parameter against a `varchar` column loses the summary (9% for a pattern that starts with a wildcard, the histogram for a prefix).
- The summary is a sample of 5% of the rows read plus 10, capped around 2,800 strings from about 56,000 rows on (2,400 for `nvarchar`, half as many for long, dissimilar strings). A pattern present in fewer than about one row in 2,800 can be estimated as absent, and a rare pattern is estimated with the imprecision of a small sample.
- Of a long string, the summary only keeps the first 40 and the last 40 characters (bytes for `varchar`, UTF-16 code units for `nvarchar`), joined together.
- The summary applies the case and accent rules of the collation, but not the equivalences of one character to two (`ß` and `ss`), and it compares bytes in a `varchar` column in `Japanese_CI_AS`, the only double-byte code page I have measured.
- On a column that repeats a character, such as zero-padded codes, a pattern with several `%` can cost seconds of compile time, before any execution.

## Possible improvements

Now that the format can be read, one may wonder how it could evolve. The following ideas are a reader's opinion, without any measurement of the cost of each change: Microsoft has constraints that cannot be seen from here, such as compile time, blob size or format compatibility between versions.

Four cases lose the summary or mislead it, while the fix seems within reach. On a 100,000-row table where 2,000 rows end with `.org`, the `varchar` pattern is estimated at 1,954 rows, and each of the first three cases at 9,000:

- an `nvarchar` pattern against a `varchar` column, `N'...'` literal or parameter, loses the summary, and a pattern that starts with a wildcard gets the 9% guess. Converting it to the column's type, when the conversion loses nothing, would be enough. .NET drivers send strings as `nvarchar` by default, which makes this case common;
- `ESCAPE` also loses the summary, although the estimate already consists in applying a `LIKE` to the strings of the sample;
- `LOWER(column)` changes nothing in the result on a case-insensitive collation, and could be ignored for the estimate;
- the 40 + 40 character truncation joins the beginning and the end of the string. On 100-character strings where a `Q` ends the first 40 and a `W` starts the last 40, `'%QW%'`, which matches no row, is estimated at 100,000. A junction marker, which the pattern could not cross, would avoid these false matches. The opposite effect, a substring taken from the dropped part and estimated at the floor, is the price of the truncation itself.

Other ideas touch the core of the mechanism, and their value depends on the data:

- the trie already counts duplicates, but only in the sample. For a column of a few distinct values over a million rows, the values and their exact row counts would fit in a few bytes, and the estimate would become exact;
- all patterns absent from the sample get the same floor, a tenth of a string, although an absent two-character pattern is far more likely than an absent twelve-character one. The literature on substring estimation, such as pruned suffix trees ([Krishnan, Vitter and Iyer, 1996](https://doi.org/10.1145/233269.233341)) or the work of [Chaudhuri, Ganti and Gravano (2004)](https://doi.org/10.1109/ICDE.2004.1319999) on underestimation, proposes breaking the absent pattern into pieces that are present;
- the sample size does not follow the table size: on a hundred million rows, if the cap holds, the arithmetic gives a floor of 3,500 rows. A sample that grew a little with the table, within the space limit, would reduce this jump;
- the walk of the summary backtracks on each `%`, and its cost explodes on repetitive data (see "Compile time"). The method Russ Cox describes for shell wildcards, resuming only at the last `*` met, is a lead for avoiding the retries on the earlier `%`. It would still have to be adapted to walking a trie, to counting matches and to collation rules, which would be better than the 11-billion-call bound of SQL Server 2025;
- comparing characters rather than bytes in double-byte code pages, and applying the collation's equivalences, would remove the false estimates of `'%A%'` in Japanese or of `'%ß%'`;
- with parallelism, two successive `UPDATE STATISTICS ... WITH FULLSCAN`, with no change to the data, give different samples, hence different estimates. Sampling at the same step, whatever the split between threads, would make plans reproducible.

There remains the lack of a summary for `varchar` columns with a UTF-8 collation. [Erland Sommarskog](https://www.sommarskog.se/Short%20Stories/stringstats.html) suggests a reason: the truncation is counted in bytes, and in UTF-8 a Greek or Cyrillic letter takes two bytes, a Chinese or Japanese ideograph three. The first 40 bytes would then keep only 20 Greek letters or 13 ideographs. This is a hypothesis, which I have not measured: the same reduction already exists for a `varchar` with a Japanese collation, which still keeps its summary.

The current trade-off is still defensible: a sample of 2,800 strings in a compressed trie fits in about 200 KB, applies quickly at compile time, except on repetitive data (see "Compile time"), estimates frequent patterns well, and its errors on rare patterns seldom change the plan.


---

## About the author

Rudi Bruchez, independent SQL Server consultant since 2006: performance audits, tuning, migrations, high availability and training. For an audit or hands-on help on your server: https://www.pachadata.com/en/contact/ (remote audit: https://www.pachadata.com/en/services/remote-sql-server-audit/).
