In a recent Azure SQL Database support case, the application logged error 40613 while opening new connections during a failover. The connection errors lasted a few seconds. After the application reconnected, some requests still took tens of seconds, and Data I/O continued to spike. That left a question we could investigate in Query Store: which queries were slow or aborted when the application started using the database again?
In a recent Azure SQL Database support case, the application logged error 40613 while opening new connections during a failover. The connection errors lasted a few seconds. After the application reconnected, some requests still took tens of seconds, and Data I/O continued to spike. That left a question we could investigate in Query Store: which queries were slow or aborted when the application started using the database again?
I now start with the UTC time when the affected application first connected successfully. From there, I look at the first recorded completion for each query, its outcome, and the rest of the executions in the same window. This helps me see whether the slowdown was concentrated in the first execution or persisted as traffic returned.
Start with the reconnection time
- Find the first successful SQL connection in the application logs. Use its UTC timestamp as @WindowStartUtc. To include commands that ended during the interruption, start the window earlier. The application logs also provide evidence of connection attempts that failed before a command could run. Troubleshoot common Azure SQL connection issues
- Run the diagnostic script in the affected user database. Start with @WindowMinutes = 15 and set @QueryId if you already know which query to investigate. The script reads Query Store and returns one row per query ID across its captured plans.
Read the first completion and the window together
| Field | What it tells you |
|---|---|
| first_completed_utc, first_outcome | When the first identifiable execution ended, and whether it succeeded, was aborted by the client, or ended with an exception. An execution that began before the window can still finish inside it. |
| first_duration_seconds, first_completion_evidence | The elapsed time for that first completion, when the Query Store data supports it, and how the value was derived. |
| execution_count, avg_duration_seconds, max_duration_seconds | How many executions contributed to the summary, the execution-count-weighted mean, and the longest elapsed time. The report also shows counts by outcome. |
| recorded_wait_ms, wait_categories_ms | The accumulated recorded waits for the included executions and the breakdown by wait category. |
| first_execution_wait_ms | The waits attributable to the first completion when its plan, interval, and outcome group has a single execution and wait data is available. |
| excluded_boundary_groups | How many groups could include executions outside the requested window. The count, average, maximum, and wait totals cover the groups fully contained in the window. |
Query Store aggregates by plan, runtime interval, and execution type. When its earliest row contains two executions with distinct completion times, the script can recover the first duration from the minimum, maximum, and last duration. It labels that result TwoExecutionsResolved. If the duration remains ambiguous, the report can still show the first outcome when the available data supports it. Query Store runtime statistics
I use six seconds as an initial review threshold when the application normally responds much faster. I also inspect client aborts and exceptions, even when the recorded elapsed time is short. ClientAborted can represent a command timeout or another cancellation. Match it to the error recorded by the client to confirm the cause. Troubleshoot query timeouts
Try it in a test database
In a test database with Query Store enabled, record lab_start_utc once and execute the hash batch three times. It hashes two million generated rows, which gives the report a measurable query without any application tables. GENERATE_SERIES normally requires compatibility level 160 or later. Set @WindowStartUtc in the diagnostic script to the time you recorded before the test. GENERATE_SERIES
SELECT SYSUTCDATETIME() AS lab_start_utc;
GO
DECLARE @RowCount int = 2000000;
SET STATISTICS TIME ON;
SELECT CHECKSUM_AGG( BINARY_CHECKSUM(HASHBYTES( 'SHA2_256', CONCAT(CONVERT(varchar(20), g.value), REPLICATE('X', 4000)) )) )
AS demo_checksum
FROM GENERATE_SERIES(1, @RowCount) AS g
OPTION (MAXDOP 1);
SET STATISTICS TIME OFF;
GO
What one lab run showed
| Metric | Observed value for query ID 4 |
|---|---|
| First recorded outcome | Succeeded |
| First duration | 12.933 s |
| First completion evidence | TwoExecutionsResolved |
| Executions | 3, all successful |
| Average and maximum duration | 13.294 s and 13.928 s |
| Total recorded waits | 31,840 ms |
| Recorded waits by category | CPU 16,419 ms and Unknown 15,421 ms |
| Wait time for the first execution | NULL |
The result that caught my attention was 16.419 seconds of CPU waits next to a 12.933-second first execution. The first number accumulates waits across the three captured executions. The second measures the elapsed time of a single execution. Query Store's CPU category includes SOS_SCHEDULER_YIELD waits. To measure CPU consumed, check CPU time separately. Query Store wait statistics and category mapping
The first execution finished slightly faster than the average in this lab run. In a real incident where the first execution is much slower and later executions settle back near their usual duration, I compare the same plan and representative parameters before and after the event. When Query Store shows Buffer IO waits, I check physical reads and Azure Monitor Data I/O to see whether storage reads explain the slowdown. If later executions stay slow, I extend the analysis to plan changes, concurrency, and other wait categories. Monitor Azure SQL Database metrics
My lesson learned: Record the first completion alongside the count, mean, and maximum. After a failover, that gives you a way to distinguish one costly execution from a sustained slowdown and to pick the next query to investigate.
Diagnostic script
Set @WindowStartUtc and execute the script in the user database. The default 15-minute window is a starting point. If several groups cross its boundaries, review excluded_boundary_groups and adjust the analysis period as needed.
/*
Azure SQL Database | First recorded outcome and execution summary
Run in the user database with Query Store read permissions. Set
@WindowStartUtc to the reconnection time for a recovery report, or to an
earlier time to include executions that ended during the incident.
The window includes its start and excludes its end. @QueryId is optional.
The first recorded completion uses Query Store's completion timestamps.
It is reported across all captured plans and outcomes for each query_id.
An execution can start before this window and finish inside it.
First completion evidence
SingleCapturedCompletion: The earliest Query Store row contains one
execution.
TwoExecutionsResolved: The earliest row has two distinct completion
times. The recorded last duration identifies
which of the minimum and maximum durations
belongs to the first completion.
UniformDuration: The earliest row has the same minimum and maximum
duration, so that duration applies to every execution.
OutcomeOnly: The first outcome is identifiable, with insufficient
information to isolate its duration.
CompletionTimeTie: Different outcomes have the same earliest timestamp.
WindowStartOverlap: A group spans the start of the window, so the first
in-window completion cannot be ordered reliably.
The grouped count, weighted average and maximum use only groups whose
first and last completions fall inside the window. An excluded boundary
group means these figures can cover only part of the window's executions.
The elapsed-duration summary includes successful, aborted and exception
executions. A client abort can be a timeout or another cancellation.
Use client telemetry to confirm its cause.
Wait statistics are in milliseconds. Query Store adds them by plan,
interval, outcome and wait category. The report sums the waits for
the same fully contained groups used in the execution summary.
First-execution waits are shown only when the earliest group contains
exactly one execution and its waits were captured. NULL means the wait
statistics were unavailable or could not be attributed to that execution.
See wait_stats_capture_mode_desc in sys.database_query_store_options
for the current capture setting.
*/
SET NOCOUNT ON;
DECLARE @WindowStartUtc datetimeoffset(7) = '2026-12-01'; -- Example: '2026-12-02T17:49:00+00:00'
DECLARE @WindowMinutes int = 15;
DECLARE @QueryId bigint = NULL;
IF @WindowStartUtc IS NULL
THROW 50000, N'Set @WindowStartUtc to the UTC start of the analysis window.', 1;
IF @WindowMinutes IS NULL OR @WindowMinutes < 1
THROW 50001, N'Set @WindowMinutes to a positive number of minutes.', 1;
SET @WindowStartUtc = SWITCHOFFSET(@WindowStartUtc, '+00:00');
DECLARE @WindowEndUtc datetimeoffset(7) = DATEADD(MINUTE, @WindowMinutes, @WindowStartUtc);
;WITH runtime_rows AS
(
SELECT
p.query_id,
rs.plan_id,
rs.runtime_stats_interval_id,
rs.execution_type,
rs.first_execution_time,
rs.last_execution_time,
rs.count_executions,
rs.avg_duration,
rs.min_duration,
rs.max_duration,
rs.last_duration,
CASE
WHEN rs.count_executions = 1 THEN 'SingleCapturedCompletion'
WHEN rs.min_duration = rs.max_duration THEN 'UniformDuration'
WHEN rs.count_executions = 2 AND rs.first_execution_time < rs.last_execution_time
AND rs.last_duration IN (rs.min_duration, rs.max_duration)
THEN 'TwoExecutionsResolved'
END AS duration_evidence,
DENSE_RANK() OVER (
PARTITION BY rs.plan_id, rs.runtime_stats_interval_id, rs.execution_type
ORDER BY rs.first_execution_time
) AS completion_order,
COUNT_BIG(*) OVER (
PARTITION BY rs.plan_id, rs.runtime_stats_interval_id,
rs.execution_type, rs.first_execution_time
) AS rows_with_same_first_completion
FROM sys.query_store_runtime_stats_interval AS i
JOIN sys.query_store_runtime_stats AS rs
ON rs.runtime_stats_interval_id = i.runtime_stats_interval_id
JOIN sys.query_store_plan AS p ON p.plan_id = rs.plan_id
WHERE i.start_time < @WindowEndUtc
AND i.end_time > @WindowStartUtc
AND rs.execution_type IN (0, 3, 4)
AND rs.count_executions > 0
AND (@QueryId IS NULL OR p.query_id = @QueryId)
),
runtime_groups AS
(
-- Preserve the earliest row for duration, and combine active interval
-- rows for the grouped execution count and weighted duration.
SELECT
r.query_id,
r.plan_id,
r.runtime_stats_interval_id,
r.execution_type,
MIN(r.first_execution_time) AS first_completion,
MAX(r.last_execution_time) AS last_completion,
SUM(r.count_executions) AS executions,
SUM(r.avg_duration * r.count_executions) AS total_duration_us,
MAX(r.max_duration) AS max_duration_us,
MAX(CASE WHEN r.completion_order = 1 AND r.rows_with_same_first_completion = 1 THEN
CASE r.duration_evidence
WHEN 'SingleCapturedCompletion' THEN r.max_duration
WHEN 'UniformDuration' THEN r.min_duration
WHEN 'TwoExecutionsResolved' THEN
CASE WHEN r.last_duration = r.max_duration
THEN r.min_duration ELSE r.max_duration END
END
END) AS first_duration_us,
MAX(CASE WHEN r.completion_order = 1 AND r.rows_with_same_first_completion = 1
THEN r.duration_evidence END) AS first_duration_evidence
FROM runtime_rows AS r
GROUP BY r.query_id, r.plan_id, r.runtime_stats_interval_id, r.execution_type
),
window_groups AS
(
SELECT
g.*,
CASE WHEN g.first_completion >= @WindowStartUtc AND g.last_completion < @WindowEndUtc
THEN 1 ELSE 0 END AS fully_contained,
MIN(CASE WHEN g.first_completion >= @WindowStartUtc THEN g.first_completion END)
OVER (PARTITION BY g.query_id) AS earliest_in_window
FROM runtime_groups AS g
WHERE g.last_completion >= @WindowStartUtc
AND g.first_completion < @WindowEndUtc
),
query_summary AS
(
SELECT
g.query_id,
MIN(g.earliest_in_window) AS earliest_in_window,
COUNT_BIG(CASE WHEN g.first_completion < @WindowStartUtc THEN 1 END) AS groups_crossing_start,
COUNT_BIG(CASE WHEN g.fully_contained = 0 THEN 1 END) AS excluded_boundary_groups,
COUNT_BIG(CASE WHEN g.first_completion = g.earliest_in_window THEN 1 END) AS earliest_group_count,
MIN(CASE WHEN g.first_completion = g.earliest_in_window THEN g.execution_type END) AS earliest_min_type,
MAX(CASE WHEN g.first_completion = g.earliest_in_window THEN g.execution_type END) AS earliest_max_type,
MAX(CASE WHEN g.first_completion = g.earliest_in_window
THEN g.first_duration_us END) AS earliest_duration_us,
MAX(CASE WHEN g.first_completion = g.earliest_in_window
THEN g.first_duration_evidence END) AS earliest_duration_evidence,
SUM(CASE WHEN g.fully_contained = 1 THEN g.executions ELSE 0 END) AS execution_count,
SUM(CASE WHEN g.fully_contained = 1 AND g.execution_type = 0
THEN g.executions ELSE 0 END) AS succeeded_count,
SUM(CASE WHEN g.fully_contained = 1 AND g.execution_type = 3
THEN g.executions ELSE 0 END) AS client_aborted_count,
SUM(CASE WHEN g.fully_contained = 1 AND g.execution_type = 4
THEN g.executions ELSE 0 END) AS exception_count,
SUM(CASE WHEN g.fully_contained = 1 THEN g.total_duration_us END) AS total_duration_us,
MAX(CASE WHEN g.fully_contained = 1 THEN g.max_duration_us END) AS max_duration_us
FROM window_groups AS g
GROUP BY g.query_id
),
waits_by_category AS
(
SELECT
g.query_id,
w.wait_category_desc,
SUM(w.total_query_wait_time_ms) AS recorded_wait_ms,
SUM(CASE WHEN g.first_completion = g.earliest_in_window AND g.executions = 1
THEN w.total_query_wait_time_ms END) AS first_execution_wait_ms
FROM window_groups AS g
JOIN sys.query_store_wait_stats AS w
ON w.plan_id = g.plan_id
AND w.runtime_stats_interval_id = g.runtime_stats_interval_id
AND w.execution_type = g.execution_type
WHERE g.fully_contained = 1
GROUP BY g.query_id, w.wait_category, w.wait_category_desc
),
wait_summary AS
(
SELECT
w.query_id,
SUM(w.recorded_wait_ms) AS recorded_wait_ms,
SUM(w.first_execution_wait_ms) AS first_execution_wait_ms,
STRING_AGG(CONVERT(nvarchar(max),
CONCAT(w.wait_category_desc, N': ', w.recorded_wait_ms, N' ms')), N' | ')
AS wait_categories_ms
FROM waits_by_category AS w
GROUP BY w.query_id
)
SELECT
s.query_id,
CASE WHEN s.groups_crossing_start = 0
THEN SWITCHOFFSET(s.earliest_in_window, '+00:00') END AS first_completed_utc,
CASE WHEN s.groups_crossing_start = 0 AND s.earliest_min_type = s.earliest_max_type THEN
CASE s.earliest_min_type
WHEN 0 THEN 'Succeeded'
WHEN 3 THEN 'ClientAborted'
WHEN 4 THEN 'Exception'
END
END AS first_outcome,
CASE WHEN s.groups_crossing_start = 0 AND s.earliest_group_count = 1
THEN CAST(s.earliest_duration_us / 1000000.0 AS decimal(19, 3))
END AS first_duration_seconds,
CASE
WHEN s.groups_crossing_start > 0 THEN 'WindowStartOverlap'
WHEN s.earliest_min_type <> s.earliest_max_type THEN 'CompletionTimeTie'
WHEN s.earliest_group_count = 1 AND s.earliest_duration_us IS NOT NULL
THEN s.earliest_duration_evidence
ELSE 'OutcomeOnly'
END AS first_completion_evidence,
s.execution_count,
s.succeeded_count,
s.client_aborted_count,
s.exception_count,
CAST(s.total_duration_us / NULLIF(s.execution_count, 0) / 1000000.0
AS decimal(19, 3)) AS avg_duration_seconds,
CAST(s.max_duration_us / 1000000.0 AS decimal(19, 3)) AS max_duration_seconds,
CASE WHEN s.groups_crossing_start = 0 AND s.earliest_group_count = 1
THEN w.first_execution_wait_ms END AS first_execution_wait_ms,
w.recorded_wait_ms,
w.wait_categories_ms,
s.excluded_boundary_groups,
qt.query_sql_text
FROM query_summary AS s
JOIN sys.query_store_query AS q ON q.query_id = s.query_id
JOIN sys.query_store_query_text AS qt ON qt.query_text_id = q.query_text_id
LEFT JOIN wait_summary AS w ON w.query_id = s.query_id
ORDER BY s.max_duration_us DESC, s.query_id;
Related reading
- Understand why Azure SQL Database can return error 40613 during a reconfiguration and how to identify when it happened. Lesson Learned #207: Hands-On Labs — Error 40613
- See how a cold cache can affect query timings when comparing performance across environments. Lesson Learned #437: Why Does Your SQL Query Run Faster Here Than There?
- Correlate client-reported command timeouts with Query Store and Extended Events to investigate why an execution was aborted. Lessons Learned #559: Understanding Query Timeouts in Azure SQL Database
- Compare execution plans, runtime intervals, and weighted averages when investigating a query slowdown. Lessons Learned #560: SQL Is Slow — What Can Query Store and SSMS Copilot Uncover?
Published Dec 02, 2026
Version 1.0Jose_Manuel_Jurado
Microsoft
Joined November 29, 2018
Azure Database Support Blog
Follow this blog board to get notified when there's new activity