Skip to content

C9: Optimize the DB with GitHub Copilot (coach)

Scope
Member
Time box
60 min

The DB perf kit (db/perf-kit) plants five issues in ContosoUniversity. They live in database objects and settings, so they’re there on the source SQL Server and, after cutover, on SQL MI. Attendees run the workload, find the issues in Query Store, fix them with GitHub Copilot’s help (Copilot Chat in VS Code with the MSSQL extension, or Copilot in SSMS if it’s installed), and show Query Store before and after.

The numbers on this page were measured in the workload subscription on 2026-09-25: vm-app01 on Standard_D8as_v6 with SQL Server 2022 Developer, and one default workload run (15 minutes, 8 connections) from vm-dev01 before the fixes and one after. Attendees run 5 minutes, at 8 connections, against a 4-vCore General Purpose SQL MI, so their absolute numbers differ a lot. The kit’s smoke run on a General Purpose MI (5 minutes, 8 connections, before any fix) made 146 calls, with the view at about 114 seconds a call and every other query 4 to 6 times slower than the source figures below. Compare ratios and the ranking of the queries, not the figures. A run can finish later than its set duration, because the slow view finishes the call it’s in: the member’s window ends at the Finished at time, not the until time.

Attendees run the 5-minute workload twice (baseline and after applying all five fixes P1–P5). The challenge page has the pacing.

Set up

  1. Demo-only: put the issues back and clear Query Store with ./db/perf-kit/Reset-PerfKit.ps1 -MemberIndex <n>. Run it for your own rehearsal or demo, not as a member’s first step: the attendee page says not to run it in C9 unless they start over, because it clears Query Store and wipes their baseline. See the perf kit README.
  2. Run the workload: ./db/perf-kit/Start-Workload.ps1 -MemberIndex <n>. On MI after cutover, add -Server '<sql-mi-host-name>' -Authentication ActiveDirectoryInteractive (on vm-dev01, ActiveDirectoryInteractive signs in as you with a browser prompt).
  3. In SSMS, open ContosoUniversity > Query Store > Top Resource Consuming Queries. Look at Duration and then CPU Time, with the Total statistic, over the last hour.

Before

Query Store after the “before” run, top queries by total duration. Calls are over 15 minutes, and CPU rank is the query’s place by total CPU time.

QueryIssueCallsAvg duration (ms)Total duration (s)Avg CPU (ms)CPU rankAvg logical readsMax DOP
vw_EnrollmentStatistics for one departmentP4, P537117,5336,50511,56517,5391
usp_SearchStudentsP247741119626846,3111
App student search (count)App’s own Contains49036718025051,8821
usp_GetStudentEnrollmentsP3, P146227012548327,6372
App student search (page)App’s own Contains4901728430231,9792
App student detailsP1655815313167,6352
App instructor pageNone3071685211181,9561
App enrollment statisticsP1513753813177,6372

The workload’s own summary for the same run, client side, so it includes the network and reading the rows:

QueryCallsAvg msP95 ms
P2 dbo.usp_SearchStudents477413720
P3 dbo.usp_GetStudentEnrollments462272376
P4 dbo.vw_EnrollmentStatistics37117,53625,931
App: student search490542865
App: student details65583116
App: enrollment statistics51377108
App: instructor page307186303

What the plans in Query Store showed for the “before” run:

QueryEvidence in the plan
vw_EnrollmentStatisticsSerial plan, NonParallelPlanReason="TSQLUserDefinedFunctionsNotParallelizable"; scan of Enrollment; compiled at compatibility level 110
usp_GetStudentEnrollmentsCONVERT_IMPLICIT(sql_variant, ...StudentID...) on the column, and a scan of Enrollment
App student details and enrollment statisticsScan of Enrollment, and a missing index suggestion on Enrollment (StudentID)
usp_SearchStudentsScan of Person: the leading % rules out a seek

The issues

P1: missing index on Enrollment.StudentID

  • Symptom: a student’s details page, and anything else per student, reads about 7,600 pages, the whole Enrollment table, to return about 10 rows. It gets slower as enrollments grow.

  • Find it: the app’s student details and enrollment statistics queries in Query Store. Their plans scan PK_Enrollment and carry a green Missing Index suggestion on Enrollment (StudentID). sys.dm_db_missing_index_details says the same.

  • Copilot prompt: “Here’s the execution plan of the student details query in ContosoUniversity. Why does it scan the Enrollment table, and which index would fix it? Check the existing indexes on dbo.Enrollment first.”

  • Fix:

    CREATE INDEX IX_Enrollment_StudentID ON dbo.Enrollment (StudentID) INCLUDE (CourseID, Grade);

    A plain index on StudentID works too. INCLUDE saves the key lookups.

  • Note: SQL Server doesn’t index foreign key columns automatically. EF Core adds the index when it creates the table, and the kit drops it: a realistic “someone dropped it” story.

P2: non-sargable search in usp_SearchStudents

  • Symptom: the search procedure is one of the top queries by duration, and it’s slow whatever the search term.

  • Find it: usp_SearchStudents in Query Store. The plan scans Person: LIKE '%' + @Term + '%' has a leading wildcard, so no index can seek.

  • Copilot prompt: “dbo.usp_SearchStudents is slow. Explain why LIKE ’%’ + @Term + ’%’ can’t use an index, and rewrite it so it can, with the indexes it needs. Tell me what changes for the user.”

  • Fix: search on the start of the name, with an index per name column:

    CREATE INDEX IX_Person_LastName ON dbo.Person (LastName, FirstName) INCLUDE (Discriminator, EnrollmentDate);
    CREATE INDEX IX_Person_FirstName ON dbo.Person (FirstName, LastName) INCLUDE (Discriminator, EnrollmentDate);

    In the procedure, match each name with LIKE @Term + N'%' in two queries combined with UNION, so each can seek its own index, then page the result.

  • Note: “starts with” isn’t “contains”: mar no longer finds Omar. That’s a product decision, and a good attendee says so. A full-text index with a prefix term (CONTAINS(..., '"mar*"')) keeps word-prefix matching and is also a full answer. The app’s own search (Contains in LINQ, CHARINDEX in SQL) has the same problem but lives in the app. The new indexes make its scan cheaper, but fixing it properly is a bonus, not part of P2.

P3: implicit conversion in usp_GetStudentEnrollments

  • Symptom: a procedure that returns about 10 rows reads the whole Enrollment table, and ranks second by CPU.

  • Find it: usp_GetStudentEnrollments in Query Store. The plan has a warning on the SELECT operator, Type conversion in expression may affect “SeekPlan”, and CONVERT_IMPLICIT(sql_variant, ...) around StudentID in the scan’s predicate. The parameter is sql_variant, which wins data type precedence, so SQL Server converts the column on every row instead of the parameter once.

  • Copilot prompt: “Look at dbo.usp_GetStudentEnrollments and its execution plan. Why is there a CONVERT_IMPLICIT on StudentID, and how do I fix it without changing its results?”

  • Fix: make the parameter match the column, int:

    ALTER PROCEDURE dbo.usp_GetStudentEnrollments @StudentID int AS ...
  • Note: the P1 index alone doesn’t fix P3. With the conversion on the column, SQL Server scans the new index instead of seeking it. Attendees who fix P1 first and see P3 barely move have found the lesson.

P4: scalar UDF in vw_EnrollmentStatistics

  • Symptom: the statistics view is by far the slowest query: about 17.5 seconds per department, mostly on CPU. It dominates Query Store’s totals.

  • Find it: the view’s query in Query Store. The plan is serial, with NonParallelPlanReason="TSQLUserDefinedFunctionsNotParallelizable" in its properties, and a Compute Scalar that calls dbo.ufn_GradePoint once for every enrollment row.

  • Copilot prompt: “dbo.vw_EnrollmentStatistics is slow and its plan is serial. What does dbo.ufn_GradePoint cost per row, and how do I rewrite the view without it, keeping the same results?”

  • Fix: inline the function’s logic in the view:

    AVG(CAST(CASE e.Grade WHEN 0 THEN 4.0 WHEN 1 THEN 3.0 WHEN 2 THEN 2.0 WHEN 3 THEN 1.0 WHEN 4 THEN 0.0 END AS decimal(3, 2))) AS AverageGradePoint

    An inline table-valued function also works. Keep ufn_GradePoint if other code uses it.

  • Note: P5 partly fixes P4. From compatibility level 150, SQL Server inlines scalar UDFs that qualify (sys.sql_modules.is_inlineable is 1 for this one), so raising the level alone makes the view much faster (see P5). Rewriting the view is still the right fix: it doesn’t depend on the level, or on the function staying inlineable.

P5: compatibility level 110

  • Symptom: nothing on its own: it’s a setting. Attendees find it in the database properties, in sys.databases, in the compatibility_level column of sys.query_store_plan, or when Copilot asks.

  • Find it: SELECT name, compatibility_level FROM sys.databases; gives 110 (SQL Server 2012) on SQL Server 2022, whose default is 160. At 110 the optimizer uses the legacy cardinality estimator and turns off scalar UDF inlining, batch mode on rowstore and the other Intelligent Query Processing features.

  • Copilot prompt: “What’s the compatibility level of ContosoUniversity, what does it turn off on SQL Server 2022, and how do I raise it safely with Query Store?”

  • Fix:

    ALTER DATABASE ContosoUniversity SET COMPATIBILITY_LEVEL = 160;

    The safe way, which is what to look for: Query Store on first, capture a baseline, raise the level, compare, and force the old plan for any query that regresses.

  • Measured on its own, with P4 still unfixed: the view for one department averaged 8,706 ms over 20 departments at level 110, and 98 ms at level 160, because the scalar UDF is inlined.

  • Note: MI link keeps the compatibility level, so the database arrives on SQL MI at 110 and the fix applies there too. Microsoft’s migration guide recommends raising it after the migration.

After

The five fixes applied, Query Store cleared, then one more default workload run. The fixes made the database fast enough that the same 8 connections made 67,079 calls instead of 3,275, so compare averages, not totals. Top queries by total duration:

QueryIssueCallsAvg duration (ms)Total duration (s)Avg CPU (ms)CPU rankAvg logical readsMax DOP
App student search (count)App’s own Contains10,1003033,05823911,5811
vw_EnrollmentStatistics for one departmentP4, P56,6701981,32115625,4921
App student search (page)App’s own Contains10,1001191,1979334581
App instructor pageNone6,53214796011641,9561
usp_SearchStudentsP210,082403993155,2801
usp_GetStudentEnrollmentsP3, P110,2620.11.20.16231
App student detailsP113,4390.11.10.17251
App enrollment statisticsP19,9940.10.80.18231

The workload’s own summary:

QueryCallsAvg msP95 ms
P2 dbo.usp_SearchStudents10,0824178
P3 dbo.usp_GetStudentEnrollments10,2621.44.2
P4 dbo.vw_EnrollmentStatistics6,670200354
App: student search10,100423909
App: student details13,4391.44.2
App: enrollment statistics9,9941.44.2
App: instructor page6,532174284

Before and after, per issue (average Query Store duration per call):

IssueQueryBefore (ms)After (ms)Improvement
P1App student details810.1Reads 7,635 → 25 pages per call
P1App enrollment statistics750.1Reads 7,637 → 23 pages per call
P2usp_SearchStudents41140About 10×
P3usp_GetStudentEnrollments2700.1Reads 7,637 → 23 pages per call
P4vw_EnrollmentStatistics17,533198About 90×
P5vw_EnrollmentStatistics, P4 unfixed, measured on its own8,70698About 90×, from scalar UDF inlining

After the fixes, the top of Query Store is the app’s own search, which C9 doesn’t cover: a good point to close on, because the next fix is in the app, not the database.

A 1-hour C9

Expected order of work. Attendees run the 5-minute workload twice (baseline and after applying all five fixes):

TimeStep
0–8 minSet up and run the 5-minute baseline workload (8 connections)
8–15 minInspect Top Resource Consuming Queries in Query Store and capture baseline
15–45 minDiagnose and apply all five fixes (p1-*.sql to p5-*.sql) with Copilot
45–55 minRun the 5-minute after workload and capture the after Query Store comparison
55–60 minCommit the five .sql scripts and before/after comparison in factory/evidence/c09/ on main

Business outcome check

The outcome is reliability at enrollment peaks. Ask for one line that names a fixed query and its before and after average duration, taken from Query Store.

Expected evidence

  • The five .sql fix scripts (p1-*.sql to p5-*.sql) committed in factory/evidence/c09/ on main.
  • Query Store baseline vs after comparison showing the duration/CPU and logical-read improvements across the tuned queries.

Common mistakes

  • Clearing Query Store between baseline and after, losing the comparison.
  • Comparing totals when the faster run makes more calls; compare per-call measurements.
  • Treating an index suggestion or an AI answer as proof without reviewing the plan and rerunning the workload.

Reset

./db/perf-kit/Reset-PerfKit.ps1 -MemberIndex <n> puts all five issues back and clears Query Store. On MI after cutover, add -Server '<sql-mi-host-name>' -Authentication ActiveDirectoryInteractive (on vm-dev01, use that rather than ActiveDirectoryDefault; it signs in as you). Don’t reset in the middle of a member’s before-and-after capture: it clears the Query Store numbers they need.