ADO.NET interview questions and answers for .NET developers

ADO.NET interview questions check whether you can talk to a relational database from .NET without an ORM hiding the details: opening and disposing connections, running parameterized commands, streaming rows with a DataReader, and editing data offline in a DataSet before a DataAdapter writes it back. Interviewers also probe connection pooling, transactions and SQL injection, because those are where hand-written data access breaks in production. Strong answers tie each API to its cost in round trips, memory or locks.

By Published 10 min read

Why ADO.NET still shows up in .NET interviews

Plenty of business software still runs on .NET Framework with data layers written directly against ADO.NET, and teams hiring to maintain or migrate that code ask about it by name. It also matters on modern stacks: Dapper is a thin layer of extension methods over an ADO.NET connection, and EF Core talks to the database through an ADO.NET provider. So a question like "what happens when you call Open on a connection?" is really a question about pooling, which affects every .NET service that touches SQL. For the wider runtime, ASP.NET Core and EF Core, see .NET interview questions; for language topics such as async and IDisposable, see C# interview questions.

  1. Model questionsConnected versus disconnected access, the provider classes, and which Execute method fits which query.
  2. Read and fix some codeCommonly a method that builds SQL by string concatenation, leaks a connection or reads columns by name in a tight loop.
  3. Write a small data methodFetch rows into objects, or update two tables inside one transaction, with parameters and proper disposal.
  4. Production scenariosPool timeouts, slow reports, deadlocks, and how you would modernize a legacy data layer without a big-bang rewrite.

ADO.NET fundamentals questions

First-round ADO.NET questions
QuestionWhat it testsWhat a strong answer shows
What is ADO.NET?OrientationThe set of .NET classes for working with data sources: provider objects (connection, command, reader, adapter) for talking to a database, plus in-memory DataSet and DataTable that work without one.
Connected versus disconnected access?Core modelConnected code keeps a connection open while it reads rows forward-only through a DataReader. Disconnected code fills a DataSet, closes the connection, works on the copy and reconnects only to save changes.
What is a data provider?ArchitectureA family of classes for one database: SqlClient for SQL Server, others for Oracle, PostgreSQL, SQLite or ODBC and OLE DB. They implement shared base classes such as DbConnection and DbCommand, so code can target the abstraction.
ExecuteReader, ExecuteScalar or ExecuteNonQuery?Command APIReader for row sets, Scalar for the first column of the first row (a COUNT or a new identity value), NonQuery for INSERT, UPDATE, DELETE or DDL, where it returns rows affected.
DataSet versus DataTable?In-memory modelA DataTable is one table of rows with columns and constraints. A DataSet holds several tables plus the relations between them, like a small offline database.
Why wrap a connection in a using block?Resource handlingDispose closes the connection even when an exception is thrown, which returns the physical connection to the pool. A forgotten Close leaks pool slots until the garbage collector finalizes the object.
What does a connection string contain?ConfigurationServer, database, authentication, and options such as pooling, timeouts and encryption. Keep it out of source code; read it from configuration or a secret store.
How do you call a stored procedure?CommandsSet CommandType to StoredProcedure, use the procedure name as the command text, and add input, output and return-value parameters.
What is DBNull.Value?NullsThe marker for a database NULL. It is not the same as C# null, so check with IsDBNull on a reader or compare to DBNull.Value before casting a column.
Is a DataReader thread-safe or reusable?Reader behaviorNo. It is forward-only and read-only, tied to one open connection, and that connection cannot run another command while the reader is open unless MARS is enabled.
First-round ADO.NET questions. Scroll sideways on a small screen.

Commands, parameters and transactions

public static int CountOrders(string connectionString, int customerId)
{
    const string sql = "SELECT COUNT(*) FROM dbo.Orders WHERE CustomerId = @customerId";
    using (var conn = new SqlConnection(connectionString))
    using (var cmd = new SqlCommand(sql, conn))
    {
        cmd.Parameters.Add("@customerId", SqlDbType.Int).Value = customerId;
        conn.Open();
        return (int)cmd.ExecuteScalar();
    }
}

public static void MoveStock(string connectionString, int fromBin, int toBin, int qty)
{
    using (var conn = new SqlConnection(connectionString))
    {
        conn.Open();
        using (SqlTransaction tx = conn.BeginTransaction())
        {
            try
            {
                Exec(conn, tx, "UPDATE dbo.Bins SET Qty = Qty - @q WHERE Id = @id", qty, fromBin);
                Exec(conn, tx, "UPDATE dbo.Bins SET Qty = Qty + @q WHERE Id = @id", qty, toBin);
                tx.Commit();
            }
            catch
            {
                tx.Rollback();
                throw;
            }
        }
    }
}

static void Exec(SqlConnection conn, SqlTransaction tx, string sql, int qty, int id)
{
    using (var cmd = new SqlCommand(sql, conn, tx))
    {
        cmd.Parameters.Add("@q", SqlDbType.Int).Value = qty;
        cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;
        cmd.ExecuteNonQuery();
    }
}
Parameterized query and a two-statement transaction with SqlClient. Compiled with the .NET Framework C# compiler; not run, because it needs a live SQL Server.
  • Why are parameters better than building the SQL string? Values travel separately from the statement text, so a quote in user input cannot change the query. The database can also reuse one cached plan for every value instead of compiling a new statement each time.
  • What is wrong with AddWithValue? It infers the SQL type from the .NET value. A C# string becomes nvarchar with a length taken from the value, which can force an implicit conversion against a varchar column, turn an index seek into a scan and fill the plan cache with near-duplicate plans. Declaring the type and size avoids that.
  • Why must every command in a transaction get the transaction object? SqlClient refuses to run a command on a connection that has a pending local transaction unless the command is enlisted in it, so you pass the SqlTransaction to each command.
  • SqlTransaction or TransactionScope? SqlTransaction is explicit and bound to one connection. TransactionScope is ambient: connections opened inside it enlist automatically. Opening a second connection inside a scope can escalate it to a distributed transaction, which is slower and may not be supported everywhere, so keep one connection per scope.
  • How do you read an output parameter alongside a result set? Output and return-value parameters are populated only after the reader has been fully read and closed. Reading them earlier gives you null.
  • How do you read two result sets from one command? Read the first set, call NextResult(), and read the second on the same reader. It saves a round trip for dashboards that need a header row and detail rows.
  • How do you read a large binary column without loading it all into memory? Use CommandBehavior.SequentialAccess and stream it with GetBytes or GetStream, reading columns strictly in order.
  • What does the async API buy you? OpenAsync, ExecuteReaderAsync and ReadAsync release the thread while the database works, which matters in web apps under load. It does not make an individual query faster.

DataSet, DataTable and DataAdapter questions

Disconnected questions are about change tracking. Each DataRow keeps a RowState and, once edited, both an original and a current version of its values. A DataAdapter reads that state to decide which of its InsertCommand, UpdateCommand or DeleteCommand to run for each row. The program below builds the same structures in memory, so it runs without a database.

var ds = new DataSet("Shop");
DataTable customers = ds.Tables.Add("Customers");
customers.Columns.Add("Id", typeof(int));
customers.Columns.Add("Name", typeof(string));
customers.PrimaryKey = new[] { customers.Columns["Id"] };

DataTable orders = ds.Tables.Add("Orders");
orders.Columns.Add("Id", typeof(int));
orders.Columns.Add("CustomerId", typeof(int));
orders.Columns.Add("Total", typeof(decimal));
ds.Relations.Add("CustOrders", customers.Columns["Id"], orders.Columns["CustomerId"]);

customers.Rows.Add(1, "Asha");
customers.Rows.Add(2, "Ben");
orders.Rows.Add(10, 1, 25.50m);
orders.Rows.Add(11, 1, 40.00m);
orders.Rows.Add(12, 2, 15.25m);
ds.AcceptChanges(); // as if Fill() had just loaded it

customers.Rows.Find(2)["Name"] = "Ben K.";
orders.Rows.Add(13, 2, 9.99m);
orders.Rows[0].Delete();

foreach (DataRow c in customers.Rows)
{
    decimal sum = 0;
    foreach (DataRow o in c.GetChildRows("CustOrders"))
        sum += (decimal)o["Total"];
    Console.WriteLine("{0}: {1} ({2})", c["Name"], sum, c.RowState);
}

Console.WriteLine("Changed orders: " + ds.GetChanges().Tables["Orders"].Rows.Count);
Console.WriteLine("Original name: " + customers.Rows.Find(2)["Name", DataRowVersion.Original]);

var view = new DataView(orders, "Total > 10", "Total DESC", DataViewRowState.CurrentRows);
foreach (DataRowView v in view)
    Console.WriteLine("Order {0}: {1}", v["Id"], v["Total"]);

// Asha: 40.00 (Unchanged)
// Ben K.: 25.24 (Modified)
// Changed orders: 2
// Original name: Ben
// Order 11: 40.00
// Order 12: 15.25
Row state, relations, GetChanges and DataView in memory. Compiled and run with the .NET Framework C# compiler; output shown at the end.
  • What are the RowState values? Added, Modified, Deleted, Unchanged and Detached. The deleted order 10 drops out of child rows and the view, but still counts in GetChanges because the adapter must send a DELETE for it.
  • What does AcceptChanges do, and when is calling it a bug? It commits current values as the new originals and clears row states. Called before DataAdapter.Update, it wipes the very changes Update needed to send, so nothing reaches the database.
  • How does DataAdapter.Update decide what to run? Per row: Added rows use InsertCommand, Modified rows UpdateCommand, Deleted rows DeleteCommand. After a successful update the adapter accepts changes on those rows.
  • What does SqlCommandBuilder do and what are its limits? It generates the insert, update and delete commands from a single-table SELECT that includes a key. It cannot handle joins, and its generated WHERE clauses can get long because they compare original values.
  • How does optimistic concurrency work here? The UPDATE compares original values or a rowversion column. If it affects zero rows, someone else changed the row first and the adapter throws DBConcurrencyException, which you resolve by reloading and merging or by asking the user.
  • What is a typed DataSet? A generated class with strongly typed tables and columns, built from a schema. It catches column-name typos at compile time but ties the code to generated files that must be regenerated when the schema changes.
  • What does DataSet.Merge do? It folds rows from another DataSet into this one, matching on primary keys, which is how changes come back from a service tier in older layered apps.

Connection pooling questions

Pooling, timeouts and errors
QuestionWhat it testsWhat a strong answer shows
What happens when you call Open?PoolingWith pooling on (the default in SqlClient), Open takes an idle physical connection from a pool keyed by the exact connection string, or creates one if none is free. Close or Dispose puts it back.
Why might an app create several pools by accident?Pool keysAny difference in the connection string text, such as a different user, an extra option or a different order, makes a separate pool. Integrated security can also split pools per Windows identity.
"Timeout expired ... obtaining a connection from the pool". Cause?DiagnosisEvery pooled connection is in use. Usually a leak (a code path that skips Dispose, often a reader returned without CommandBehavior.CloseConnection), or slow queries holding connections longer under load.
Connection timeout versus command timeout?SettingsConnection timeout limits how long Open waits for a connection. CommandTimeout limits how long a single command may run. They fail differently and are tuned separately.
What does MARS change?Multiple active result setsIt lets one connection keep several readers or commands active at once. It is a fix for specific patterns, not a default; it adds overhead and can hide N+1 query loops.
How would you retry safely?ResilienceRetry only transient errors such as a deadlock victim or a brief network fault, with backoff and a limit, and only for operations that are safe to repeat or wrapped in a transaction that was rolled back.
Pooling, timeouts and errors. Scroll sideways on a small screen.

Senior and scenario questions

Legacy data-layer scenarios
ScenarioWhat to say you would checkLikely fix
A nightly import of a few hundred thousand rows takes hours.Whether it runs one INSERT per row, each in its own round trip and transaction.SqlBulkCopy into a staging table, then one set-based MERGE or INSERT ... SELECT. Table-valued parameters for medium batches.
A report page loads a whole table into a DataSet and filters it in C#.Row counts, memory per request, and the WHERE clause the page actually needs.Filter and page in SQL, stream with a DataReader, and project only needed columns.
Code review finds a search box that concatenates user text into SQL.Every path that builds SQL from input, including ORDER BY and dynamic table names.Parameters for values; an allow-list for identifiers that cannot be parameterized; least-privilege database login.
Pool timeout errors appear only at peak traffic.Pool counters, long-running queries, readers passed out of methods, missing using blocks.Fix the leak or the slow query first. Raising Max Pool Size only hides it.
Intermittent deadlock errors during order updates.Whether two code paths update the same tables in opposite order.Consistent access order, shorter transactions, the right indexes, and a bounded retry on deadlock.
The team wants to move off a DataSet-based layer.Which code paths are hot, which are stable, and test coverage.Move one repository at a time behind an interface to Dapper or EF Core, keeping SQL behavior identical and comparing results.
Legacy data-layer scenarios. Scroll sideways on a small screen.
  • ADO.NET, Dapper or EF Core: how do you choose? Raw ADO.NET gives full control and no mapping layer, at the cost of boilerplate. Dapper keeps your SQL and maps rows to objects with little overhead. EF Core adds change tracking, LINQ and migrations. Many teams mix them: EF Core for most writes, Dapper or raw commands for hot read paths and bulk work.
  • How do you write provider-neutral code? Program against DbConnection, DbCommand and DbProviderFactory, and keep vendor-specific SQL in one place. Parameter prefixes and paging syntax still differ by database.
  • How do you unit test a data layer built on ADO.NET? Put the SQL behind a small interface for the services that use it, and test the SQL itself with integration tests against a real database instance, because mocks cannot check SQL.
  • How would you read millions of rows for an export without running out of memory? A DataReader streamed straight into a file writer, one row at a time, with CommandBehavior.SequentialAccess for wide or binary rows. Never a DataTable.

Fictional example

Answering "What is wrong with this method?"
Interviewer
This method opens a SqlConnection, builds "SELECT * FROM Users WHERE Email = '" + email + "'", calls ExecuteReader and returns the reader to the caller. What do you see?
Candidate
Three problems, worst first. The concatenated email is an injection hole, so I would use a typed parameter with an explicit size. Returning an open reader means the method cannot dispose the connection, so under load the pool drains; I would either map rows into a list inside the method with using blocks, or pass CommandBehavior.CloseConnection and make the caller own disposal. And SELECT * reads columns the page may not need and breaks ordinal-based reads if the schema changes, so I would name the columns. Then I would check whether Email is indexed, since this looks like a login path.

A one-week ADO.NET practice plan

  • Days 1 and 2: write a small console app that reads a table with a DataReader into objects, using parameters, ordinals and IsDBNull. Then deliberately leak connections in a loop and watch the pool timeout appear.
  • Days 3 and 4: build a DataSet with two related tables, edit, add and delete rows, and print RowState and original values before and after AcceptChanges. Wire a DataAdapter with explicit commands.
  • Day 5: write a transaction across two updates, force a failure between them, and confirm the rollback. Add a bounded retry for a simulated transient error.
  • Day 6: load a large file with SqlBulkCopy into a staging table and compare it with row-by-row inserts.
  • Day 7: explain out loud, in under a minute each, pooling, AddWithValue pitfalls, DataReader versus DataSet, and when you would pick Dapper or EF Core.

ADO.NET questions often arrive in the same loop as web questions; ASP.NET MVC interview questions covers controllers, model binding and Razor. If the role touches IBM midrange systems, AS/400 interview questions explains DB2 for i, which .NET apps commonly reach through an ADO.NET or ODBC provider.

Code-review questions reward a calm order: safety, then resources, then performance. Natively, an AI interview assistant for Mac and Windows, writes a transcript of a mock round on your own computer, so afterward you can check whether you named the injection risk before drifting into style points. During practice it can read a snippet of data-access code from a screenshot and suggest what to look at, and with Pro or the free trial it can draw on the résumé and job description you add. Your transcript and notes stay saved for review.

Questions people ask

What ADO.NET questions are asked in interviews?

Connected versus disconnected access, the provider classes, ExecuteReader versus ExecuteScalar versus ExecuteNonQuery, DataSet and DataAdapter, parameterized queries, transactions and connection pooling, plus a piece of legacy data-access code to review.

What is the difference between a DataReader and a DataSet?

A DataReader streams rows forward-only over an open connection and uses little memory. A DataSet holds tables in memory after the connection closes and tracks changes so a DataAdapter can write them back.

Is ADO.NET still used with EF Core and Dapper?

Yes, underneath. Dapper adds mapping methods to an ADO.NET connection, and EF Core sends its SQL through an ADO.NET provider, so pooling and parameter behavior still apply.

How do I prepare for ADO.NET interview questions quickly?

Write a small app that reads with a DataReader, edits a DataSet and updates through a DataAdapter, then practice explaining pooling, parameters and transactions aloud with one real bug you have fixed.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP