ExecuteReader vs ExecuteNonQuery vs ExecuteScalar in ADO.NET
SqlCommand offers three ways to run a statement, and the choice depends only on what you expect back: rows to read, a count of rows changed, or one value. Picking the right one makes the code shorter and avoids transferring data you do not need.
At a glance
| Method | Returns | Typical statements |
|---|---|---|
ExecuteReader() | A SqlDataReader over the result set(s) | SELECT returning rows; procedures returning result sets |
ExecuteNonQuery() | int: rows affected, or -1 | INSERT, UPDATE, DELETE, DDL, procedures without result sets |
ExecuteScalar() | object: first column of the first row, or null | COUNT(*), MAX(), a single lookup, a new identity value |
ExecuteReader: stream rows
A data reader is a forward-only, read-only cursor. It holds the connection open while you read, and it is the fastest way to get rows into your own objects.
const string sql = "SELECT ProductId, Name, UnitPrice, Discontinued FROM dbo.Products WHERE CategoryId = @cat";
var products = new List<Product>();
using (var con = new SqlConnection(connectionString))
using (var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add("@cat", SqlDbType.Int).Value = categoryId;
con.Open();
using (SqlDataReader r = cmd.ExecuteReader())
{
int iId = r.GetOrdinal("ProductId"), iName = r.GetOrdinal("Name"),
iPrice = r.GetOrdinal("UnitPrice"), iDisc = r.GetOrdinal("Discontinued");
while (r.Read())
{
products.Add(new Product
{
Id = r.GetInt32(iId),
Name = r.GetString(iName),
UnitPrice = r.IsDBNull(iPrice) ? (decimal?)null : r.GetDecimal(iPrice),
Discontinued = r.GetBoolean(iDisc)
});
}
}
}
- Call
IsDBNullbefore typed getters on nullable columns;GetDecimalon a NULL throws. - Look up ordinals once, outside the loop.
- For several result sets from one batch or procedure, call
r.NextResult()to move to the next. - Pass
CommandBehavior.CloseConnectionif you return the reader to another method, so closing the reader also closes the connection. - Binding directly to a GridView is shown in Bind a GridView with ExecuteReader, and a dedicated example in the ExecuteReader example.
ExecuteNonQuery: change data
const string sql = "UPDATE dbo.Products SET UnitPrice = UnitPrice * 1.05 WHERE CategoryId = @cat";
using (var con = new SqlConnection(connectionString))
using (var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add("@cat", SqlDbType.Int).Value = categoryId;
con.Open();
int changed = cmd.ExecuteNonQuery();
lblInfo.Text = changed + " product(s) repriced.";
}
What the number means:
- For
INSERT,UPDATEandDELETE, the number of rows affected. A trigger's own changes are included in the count. - For other statements (DDL,
SET), -1. - If the batch or procedure runs
SET NOCOUNT ON, SQL Server stops sending row counts and the method returns -1. Many procedures start withSET NOCOUNT ONfor performance, so do not rely on the count unless you control the procedure. - For a batch of several statements, the counts are added together.
Use the count for optimistic concurrency: an UPDATE … WHERE Id = @id AND RowVer = @rv that returns 0 means someone else changed the row first. More in the ExecuteNonQuery example.
ExecuteScalar: one value
using (var con = new SqlConnection(connectionString))
using (var cmd = new SqlCommand("SELECT COUNT(*) FROM dbo.Products WHERE CategoryId = @cat", con))
{
cmd.Parameters.Add("@cat", SqlDbType.Int).Value = categoryId;
con.Open();
int count = (int)cmd.ExecuteScalar();
}
Watch the types and the two kinds of "nothing":
- No row at all:
ExecuteScalarreturnsnull. - A row whose first column is NULL: it returns
DBNull.Value. COUNT(*)returnsint;COUNT_BIGreturnslong;SUMover anintcolumn returnsintand overdecimalreturnsdecimal. A direct cast to the wrong type throwsInvalidCastException;Convert.ToInt32is more forgiving.
object result = cmd.ExecuteScalar();
decimal? maxPrice = (result == null || result == DBNull.Value) ? (decimal?)null : (decimal)result;
Getting a new identity value
const string sql = @"INSERT INTO dbo.Products (Name, CategoryId) VALUES (@name, @cat);
SELECT CAST(SCOPE_IDENTITY() AS int);";
// or: INSERT ... OUTPUT INSERTED.ProductId VALUES (...)
cmd.Parameters.Add("@name", SqlDbType.NVarChar, 100).Value = name;
cmd.Parameters.Add("@cat", SqlDbType.Int).Value = categoryId;
int newId = (int)cmd.ExecuteScalar();
SCOPE_IDENTITY() returns numeric(38,0), which arrives as decimal; the CAST makes the direct (int) cast valid. OUTPUT INSERTED.ProductId is an alternative, but note that it cannot be used without an INTO clause on a table that has enabled triggers. More in the ExecuteScalar example.
Do not use ExecuteScalar to read a whole query "just for the first value": the server still produces the full result even though only one cell is returned. Write the query to return one value.
Async versions
Each method has a task-based version: ExecuteReaderAsync, ExecuteNonQueryAsync, ExecuteScalarAsync, plus ReadAsync on the reader. In Web Forms, use them from a method registered with RegisterAsyncTask on a page marked Async="true", so the request thread is released while SQL Server works.
Choosing in practice
- Need to display or process rows:
ExecuteReader, or aSqlDataAdapterwhen you want a disconnectedDataTable(see DataSet, DataReader, DataAdapter and DataView). - Changing data and want to know how many rows changed:
ExecuteNonQuery. - One number, one name, one id:
ExecuteScalar.
Whatever the method, keep values in parameters: SQL injection does not care which Execute you call.
Common mistakes
- Using
ExecuteReaderand thenwhile (r.Read()) count++to count rows: let SQL Server count withCOUNT(*)andExecuteScalar. - Checking
ExecuteNonQuery() > 0after calling a procedure that setsNOCOUNT ON: the result is always -1. Return a value through an output parameter instead. - Forgetting that a
SELECTrun withExecuteNonQuerystill executes on the server; the rows are discarded but the work is done. - Leaving readers open: a pooled connection with an unread reader cannot run another command, which shows up as "There is already an open DataReader associated with this Command".
Official documentation
- Microsoft Learn: SqlCommand.ExecuteReader, SqlCommand.ExecuteNonQuery, SqlCommand.ExecuteScalar
- Microsoft Learn: SET NOCOUNT, SCOPE_IDENTITY, OUTPUT clause
- Microsoft Learn: Retrieving data using a DataReader