Use (n)varchar(max) parameters only when you really need to.

The problem:

I was checking the query store of a database where performance testing was done.
The top CPU resource consumer was a simple query on 1 table with a perfect covering index, but the query plan looked more complicated than expected.

The problem? The varchar(max) datatype of parameters in the query didn’t match the data type of the columns in the table.

Example:

Let me show you this with an example.
I adapted the code that Brent Ozar used for his demo about index rebuilds with ADR and RCSI:
https://www.brentozar.com/archive/2025/01/index-rebuilds-make-even-less-sense-with-adr-rcsi/

We’ll create a products table in a database called ‘test’ and load it with about 10 million rows.
Then we’ll add a covering index to support the query we’ll use as an example.

Matching parameters:

First we’ll execute a query where the parameters match the datatype in the database:

When we look at the query plan we see an ‘Index Seek’ that returns 1 row.

A total of 4 pages is read to retrieve the information.

 

With varchar(max) parameters:

SQL Server can’t match varchar(max) parameters directly to the indexed columns.
So instead of doing an equality seek on all three keys (Cuisine, Adjective, Dish), it changes the search into a range seek on only the first key (Cuisine). After that, it still has to check the other conditions (Adjective=@p2 AND Dish=@p3) one row at a time as a filter.

Result: SQL Server has to read through 70101 rows in the range before it finds the right one, 384 pages are read instead of 4.

When we filter on Cuisine = ‘Italian’, we can see that row 70101 is the first one that matches our conditions, hence the 70101 rows read.

summary

Parameter type logical reads cpu time
varchar(100) 4 0 ms
varchar(max) 384 62 ms

conclusion

Using parameters where the data type doesn’t match the actual data types in the database can cause a performance penalty.
The good news? There’s a quick fix: just match your parameter types to your column types.

 

Leave a Comment

Scroll to Top