Menu

1 / 4

AddWithValue Looked Harmless. My Index Disagreed

DEV Community: csharp·Umer Farooq·3 days ago
#D4ByEikV
#devtocsharp#devto#dev#email#varchar
Long article (1460 words) — no AI summary yet.
Reading 0:00
15s threshold

AddWithValue is one of the most common lines in ADO.NET code. It's short, it works, and it returns the right rows. So it looks harmless.

I measured it against a typed parameter on a 200,000-row table. Same query, same data, same index. One version read 884 pages. The other read 3.

TL;DR

AddWithValue sends a C# string as NVARCHAR . If the column is VARCHAR , SQL Server converts the column on every row and scans the whole index. In my demo, that meant 884 logical reads instead of 3, and 200 lookups took 7.1 seconds instead of 16 milliseconds. The fix is one line: set the type and size yourself.

The Setup

A simple table. The Email column is VARCHAR , and it has an index.

CREATE TABLE dbo . Customers ( Id INT IDENTITY ( 1 , 1 ) PRIMARY KEY , Email VARCHAR ( 100 ) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL , FullName VARCHAR ( 100 ) NOT NULL ) ;

CREATE INDEX IX_Customers_Email ON dbo .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.