C# Interview Question #191

A database query is slow. How would you troubleshoot it?

Senior .NET Practical Scenarios Senior Advanced

Quick Interview Answer

Start by measuring the query and inspecting the generated SQL. Determine whether the delay is in the application, network, connection pool, database execution, or result materialization.

Detailed Explanation

Start by measuring the query and inspecting the generated SQL. Determine whether the delay is in the application, network, connection pool, database execution, or result materialization.

Review the database execution plan and check indexes, scans, joins, statistics, predicates, sorting, and the number of rows processed. In EF Core, inspect whether the query retrieves unnecessary columns, uses excessive Include operations, causes N+1 queries, or materializes before filtering.

Use Select projections, AsNoTracking for read-only data, appropriate indexes, pagination, and server-side filtering. Consider compiled queries or caching only after more significant bottlenecks have been addressed.

Finally, benchmark the change with realistic data and workload rather than assuming that a code change improved performance.