SQL Server Profiler: Capture and Analyze Queries
SQL Server Profiler is a tool in SQL Server Management Studio (SSMS) that captures what happens on a SQL Server in real time: every query and stored procedure that runs, how long each took, how much CPU and how many reads it used, which login and application sent it, and which errors and deadlocks occurred.
An execution plan tells you why one query is slow. Profiler answers the step before that: which queries is my application actually running, and which of them are slow?
Think of a CCTV camera at the entrance of your database. Every request that walks in is recorded with the time, who sent it and how long it stayed. When something goes wrong, you replay the recording instead of guessing.
What you can find with Profiler
- Which SQL queries your application executes, including the exact text and parameter values.
- Stored procedure executions, and each statement inside them.
- Slow-running queries, by filtering on Duration.
- Queries generated by Entity Framework Core, so you can see the SQL your LINQ became.
- SQL Server performance issues, such as queries with huge reads or CPU.
- Login activity and database errors.
- Deadlocks and long-running transactions.
Important: Profiler is deprecated for the Database Engine
Microsoft has deprecated SQL Trace and SQL Server Profiler for capturing Database Engine activity. They still work and are still widely used in development, but the recommended replacement is Extended Events (XEvents), which is lighter on the server and can capture far more. SSMS includes an easy Extended Events viewer called XEvent Profiler. This page covers both: Profiler first, because you'll meet it in every company, then the same trace with Extended Events, with real captured output.
Start a trace in SQL Server Profiler
- In SSMS, open Tools > SQL Server Profiler.
- Connect to your server (the same login as in SSMS). You need the ALTER TRACE permission; sysadmin has it.
- The Trace Properties window opens. On the General tab:
- Trace name: for example
EmployeeApp-Debug. - Use the template: Standard (default) for general use, TSQL_Duration for slow queries, Tuning for collecting a workload for the Database Engine Tuning Advisor.
- Optionally tick Save to file or Save to table to keep the trace for later.
- Trace name: for example
- On the Events Selection tab, choose the events and columns (see below). Tick Show all events and Show all columns to see everything available.
- Click Column Filters... and limit the trace (see "Filter the trace"). Always filter: an unfiltered trace on a busy server captures thousands of events per second.
- Click Run. Use the application, or run queries in SSMS, and watch the events appear. Use Pause and Stop on the toolbar; File > Save As saves a trace file (
.trc).
The events you will use most
| Event | Category | Purpose |
|---|---|---|
| SQL:BatchStarting | TSQL | A SQL batch (ad-hoc query) starts |
| SQL:BatchCompleted | TSQL | A SQL batch finishes, with Duration, CPU, Reads and Writes |
| RPC:Starting | Stored Procedures | A stored procedure or parameterised call (RPC) starts |
| RPC:Completed | Stored Procedures | A stored procedure or RPC finishes, with its cost |
| SP:StmtCompleted | Stored Procedures | One statement inside a stored procedure finishes; shows which line is slow |
| Exception / User Error Message | Errors and Warnings | Captures SQL errors and their message text |
| Deadlock graph | Locks | Captures deadlock information as a graph showing both sessions and the locked resources |
For most debugging you only need SQL:BatchCompleted and RPC:Completed: the "Completed" events contain the final duration and resource usage. Add the "Starting" events only when a query never finishes and you need to see that it began.
Batches vs RPC calls: why your application shows up as RPC
A batch is plain SQL text, as you type in SSMS. An RPC (remote procedure call) is how applications send stored procedure calls and parameterised queries. ADO.NET with CommandType.StoredProcedure, Dapper with parameters, and Entity Framework Core all send RPC calls. EF Core's queries appear as RPC:Completed events whose TextData starts with exec sp_executesql N'SELECT ...', followed by the parameter definitions and values. If you trace only SQL:BatchCompleted, you'll miss most of your application's queries.
Columns worth showing
| Column | Shows |
|---|---|
| TextData | The SQL text or procedure call |
| ApplicationName | The application name from the connection string (Application Name=EmployeeApi) |
| LoginName, HostName | Who sent it, and from which machine |
| Duration | Elapsed time. Shown in milliseconds in the Profiler window; saved trace files store microseconds. |
| CPU, Reads, Writes | CPU milliseconds and logical page reads and writes |
| SPID, StartTime, EndTime | Session ID and timing, useful for matching blocking sessions |
Filter the trace
In Column Filters, the most useful filters are:
- DatabaseName Like
EmployeeDB: only your database. - ApplicationName Like
EmployeeApi: only your application. SetApplication Name=EmployeeApiin your connection string so it's easy to filter. - Duration Greater than or equal
1000: only queries slower than one second. - LoginName or HostName: one user or one machine.
- Tick Exclude rows that do not contain values so events without the column aren't let through.
The same trace with Extended Events (real output)
Below, an Extended Events session captures the same three things as a Profiler trace (completed batches, completed RPC calls and errors) only for one client machine. A test "application" then runs four requests, and we read back what was captured.
1. Create and start the session
CREATE EVENT SESSION TrackQueries ON SERVER
ADD EVENT sqlserver.sql_batch_completed
(
ACTION (sqlserver.client_app_name, sqlserver.client_hostname,
sqlserver.username, sqlserver.database_name)
WHERE sqlserver.client_hostname = N'MMC-DEMO-APP'
),
ADD EVENT sqlserver.rpc_completed
(
ACTION (sqlserver.client_app_name, sqlserver.client_hostname,
sqlserver.username, sqlserver.database_name)
WHERE sqlserver.client_hostname = N'MMC-DEMO-APP'
),
ADD EVENT sqlserver.error_reported
(
ACTION (sqlserver.client_hostname, sqlserver.sql_text, sqlserver.database_name)
WHERE sqlserver.client_hostname = N'MMC-DEMO-APP' AND severity >= 11
)
ADD TARGET package0.ring_buffer
WITH (MAX_DISPATCH_LATENCY = 1 SECONDS);
GO
ALTER EVENT SESSION TrackQueries ON SERVER STATE = START;
GO
sql_batch_completed and rpc_completed are the Extended Events versions of SQL:BatchCompleted and RPC:Completed. The WHERE clauses are the filters, and they are applied inside SQL Server before an event is recorded, which is why XEvents is so light. The ring_buffer target keeps events in memory; for longer traces use an event_file target.
2. The application runs some queries
The test uses the EmployeePerformanceDemo table from the execution plans lesson and this small procedure:
CREATE OR ALTER PROCEDURE dbo.usp_GetEmployeesByCity
@City VARCHAR(50)
AS
BEGIN
SET NOCOUNT ON;
SELECT EmployeeId, EmployeeName, City
FROM dbo.EmployeePerformanceDemo
WHERE City = @City;
END;
GO
The "application" (a separate connection from a client machine named MMC-DEMO-APP) then runs:
USE EmployeeDB;
SELECT COUNT(*) AS TotalEmployees FROM dbo.EmployeePerformanceDemo;
SELECT * FROM dbo.EmployeePerformanceDemo WHERE City = 'Indore';
EXEC dbo.usp_GetEmployeesByCity @City = 'Indore';
SELECT 1 / 0 AS Oops;
3. Read what was captured
DECLARE @x XML =
(
SELECT CAST(t.target_data AS XML)
FROM sys.dm_xe_sessions s
JOIN sys.dm_xe_session_targets t ON t.event_session_address = s.address
WHERE s.name = 'TrackQueries' AND t.target_name = 'ring_buffer'
);
SELECT
e.value('@name', 'varchar(30)') AS EventName,
e.value('(data[@name="duration"]/value)[1]', 'bigint') / 1000 AS DurationMs,
e.value('(data[@name="cpu_time"]/value)[1]', 'bigint') / 1000 AS CpuMs,
e.value('(data[@name="logical_reads"]/value)[1]', 'bigint') AS LogicalReads,
e.value('(data[@name="row_count"]/value)[1]', 'bigint') AS RowsReturned,
e.value('(data[@name="error_number"]/value)[1]', 'int') AS ErrorNo,
COALESCE(e.value('(data[@name="batch_text"]/value)[1]', 'nvarchar(max)'),
e.value('(data[@name="statement"]/value)[1]', 'nvarchar(max)'),
e.value('(data[@name="message"]/value)[1]', 'nvarchar(max)')) AS TextOrMessage
FROM @x.nodes('/RingBufferTarget/event') AS x(e)
ORDER BY e.value('@timestamp', 'datetime2');
| EventName | DurationMs | CpuMs | LogicalReads | RowsReturned | ErrorNo | TextOrMessage |
|---|---|---|---|---|---|---|
| sql_batch_completed | 0 | 0 | 0 | 0 | NULL | SET QUOTED_IDENTIFIER ON |
| sql_batch_completed | 0 | 0 | 0 | 0 | NULL | SET TEXTSIZE 4096 |
| sql_batch_completed | 63 | 0 | 797 | 0 | NULL | USE ... |
| sql_batch_completed | 17 | 0 | 1885 | 1 | NULL | SELECT COUNT(*) AS TotalEmployees FROM dbo.EmployeePerformanceDemo; |
| sql_batch_completed | 15 | 0 | 687 | 1000 | NULL | SELECT * FROM dbo.EmployeePerformanceDemo WHERE City = 'Indore'; |
| sql_batch_completed | 4 | 15 | 70 | 1000 | NULL | EXEC dbo.usp_GetEmployeesByCity @City = 'Indore'; |
| error_reported | NULL | NULL | NULL | NULL | 8134 | Divide by zero error encountered. |
| sql_batch_completed | 6 | 0 | 0 | 0 | NULL | SELECT 1 / 0 AS Oops; |
This is exactly what a Profiler window would have shown, and it already tells a story:
- The first two rows are not our queries. The client tool sent
SEToptions when it connected. Traces always show these "invisible" statements; real applications send them too. - SELECT * read 687 pages to return 1,000 rows, while the stored procedure returning the same 1,000 rows with three columns read only 70 (it can use a covering index). Here's your tuning candidate, and the next step is its execution plan.
- The error was captured with its number and message, even though the application only saw an exception.
- The
EXECshows as a batch, not as rpc_completed, because the test client sent it as plain text. An application calling the procedure with ADO.NET or EF Core would produce an rpc_completed event instead.
4. Stop and remove the session
ALTER EVENT SESSION TrackQueries ON SERVER STATE = STOP;
DROP EVENT SESSION TrackQueries ON SERVER;
In SSMS you can also skip the T-SQL: expand Management > Extended Events > Sessions, or use XEvent Profiler > Standard in Object Explorer for a Profiler-like live view in one click.
Profiler vs Extended Events
| SQL Server Profiler | Extended Events | |
|---|---|---|
| Status | Deprecated for the Database Engine (still works) | Recommended, actively developed |
| Overhead | High, especially the GUI on a busy server | Low; filters are applied before events are recorded |
| Events available | A fixed, older set | Many more, including newer features |
| Ease of use | Very easy GUI | Easy with XEvent Profiler; flexible with T-SQL |
| Best for | Quick checks on a development machine | Development and production |
Best practices
- Don't run the Profiler GUI against a busy production server. Every event is sent across the network to your screen, which can slow the server down. Use Extended Events instead.
- Always filter by database, application, login or duration.
- Capture "Completed" events; they contain the duration and resource usage.
- Set Application Name in your connection strings so traces show which application sent each query.
- Keep traces short: start, reproduce the problem, stop.
- Be careful with saved traces: they contain query text and parameter values, which can include personal data.
Interview questions
What is SQL Server Profiler used for?
To capture SQL Server activity in real time: the queries and stored procedures applications run, their duration and resource usage, errors, logins and deadlocks. It's mainly used for debugging and finding slow queries.
What is the difference between SQL:BatchCompleted and RPC:Completed?
SQL:BatchCompleted fires when a plain SQL batch finishes; RPC:Completed fires when a remote procedure call finishes: a stored procedure call or a parameterised query such as those sent by ADO.NET and Entity Framework Core (sp_executesql).
How do you see the SQL generated by Entity Framework Core?
Trace RPC:Completed (or the rpc_completed extended event) filtered by your application name; EF Core queries appear as exec sp_executesql calls. In the application itself you can also log the SQL with EF Core's logging or ToQueryString().
Why is Profiler not recommended on production?
The GUI streams every event to the client, which adds overhead and can slow a busy server, and SQL Trace is deprecated. Extended Events captures the same information with much lower overhead.
How do you capture a deadlock?
Add the Deadlock graph event in Profiler, or read the built-in system_health Extended Events session, which records deadlocks automatically (xml_deadlock_report). See Deadlocks and Blocking.
Summary
- Profiler captures queries, procedures, errors and deadlocks in real time from SSMS (Tools > SQL Server Profiler).
- Use SQL:BatchCompleted and RPC:Completed; applications and EF Core send RPC calls.
- Always filter the trace, and set Application Name in connection strings.
- Profiler is deprecated for the Database Engine; Extended Events and XEvent Profiler are the modern, lightweight replacement.
Next: once you've found a slow query, read its execution plan.