Skip to content

Commit ccf738b

Browse files
committed
Add initial draft for the working with sql server using copilot
1 parent 4c51024 commit ccf738b

File tree

1 file changed

+250
-0
lines changed

1 file changed

+250
-0
lines changed
Lines changed: 250 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,250 @@
1+
# Working with SQL Server Using GitHub Copilot
2+
3+
GitHub Copilot for the MSSQL extension brings AI-powered assistance directly into your SQL development workflow within Visual Studio Code. This integration enables developers to work more efficiently with SQL Server, Azure SQL, and Microsoft Fabric databases by:
4+
5+
- **Writing and optimizing queries** - Generate SQL queries from natural language descriptions and receive AI-recommended improvements for performance
6+
- **Exploring and designing schemas** - Understand, design, and evolve database schemas using intelligent, code-first guidance with contextual suggestions for relationships and constraints
7+
- **Understanding existing code** - Get natural language explanations of stored procedures, views, and functions to help you understand business logic quickly
8+
- **Generating test data** - Create realistic, schema-aware sample data to support testing and development environments
9+
- **Analyzing security** - Receive recommendations to avoid SQL injection, excessive permissions, and other security vulnerabilities
10+
- **Accelerating development** - Scaffold backend components and data access layers based on your database context
11+
12+
This powerful combination allows you to focus on solving problems rather than memorizing SQL syntax, making database development more intuitive and productive.
13+
14+
## Scenario
15+
16+
Now that your application supports multiple database systems including SQL Server, you want to explore how GitHub Copilot can help you interact with your SQL Server database directly from VS Code. You'll use the GitHub Copilot for MSSQL extension to generate queries and explore your data using natural language.
17+
18+
## Prerequisites
19+
20+
Good news! We've already set up everything you need for this exercise:
21+
22+
- SQL Server Express is installed and running locally
23+
- With pets database populated with data
24+
- The **GitHub Copilot for MSSQL** extension is installed in VS Code
25+
- A SQL Server connection has been pre-registered in your environment
26+
27+
You're ready to connect and start querying right away!
28+
29+
## Understanding GitHub Copilot for MSSQL
30+
31+
The GitHub Copilot for MSSQL extension brings AI-powered assistance to your database work. It can:
32+
33+
- Generate SQL queries from natural language descriptions
34+
- Explain existing queries in plain English
35+
- Suggest query optimizations and best practices
36+
- Help explore database schemas and relationships
37+
- Convert natural language questions into executable SQL
38+
39+
This integration makes working with databases more intuitive, especially when you're exploring unfamiliar schemas or need to write complex queries quickly.
40+
41+
## Connect to SQL Server
42+
43+
First, let's establish a connection to your SQL Server instance.
44+
45+
1. [] Open the **SQL Server** view by clicking on the SQL Server icon in the Activity Bar (left sidebar).
46+
- ![MSSQL server extension](images/5-mssql-extension.png)
47+
2. [] For your convenience we have already registered **LocalServer** for you.
48+
3. [] Expand **LocalServer** and you should see **Databases**, **Security** and **Server Objects** nodes as a tree. Expand the **Databases** node to see the **PetsDB** database.
49+
50+
## Optional: Create database
51+
52+
> [!NOTE]
53+
> We've already provided a pre-seeded **PetsDB** database for you. This section is optional if you want to practice creating a database from scratch using Copilot's inline mode.
54+
55+
If you want to create your own database:
56+
57+
1. [] In the SQL Server view, right-click on your server connection and select **New Query**.
58+
2. [] Press <kbd>Control</kbd>+<kbd>I</kbd> to open Copilot inline chat in the query editor.
59+
3. [] Type the following prompt:
60+
61+
```text
62+
Create a database called Pets with recovery mode set to simple
63+
```
64+
65+
4. [] Review the generated SQL and click **Accept** the suggestion if it feels right. It should be very similar to this:
66+
67+
```sql-nocopy
68+
CREATE DATABASE Pets;
69+
ALTER DATABASE Pets SET RECOVERY SIMPLE;
70+
```
71+
72+
5. [] Execute the query by clicking **Run** or pressing <kbd>Control</kbd>+<kbd>Shift</kbd>+<kbd>E</kbd>.
73+
6. [] Refresh the SQL Server view to see your new **Pets** database.
74+
75+
Typically we would now seed the just created database by calling the **seed-database.ps1** (or **seed-database.sh** on Linux/Mac), but let's skip this so we are not distracted by non-Copilot activities.
76+
77+
## Query the database using natural language using agent mode
78+
79+
Now let's use GitHub Copilot to query our database using natural language. This is where the power of AI-assisted SQL really shines!
80+
81+
1. [] Open GitHub Copilot Chat if it's not already open and start a new chat by clicking the **+** button and make sure you are in **Agent** mode.
82+
2. [] Select **GPT-4.1** from the list of available models.
83+
3. [] Click on the tools icon on the bottom left corner of the chat window, this will open the **Configure Tools** window.
84+
4. [] Scroll down and expand the **Extension: SQL Server (mssql)**
85+
![List of tools provided by SQL extension](images/5-sql-tools-list.png)
86+
5. [] Review the tool descriptions. These tools are external services or functions that Copilot can interact with to perform specific tasks, such as retrieving data, running code, or managing resources. By calling these tools, Copilot can provide more accurate, up-to-date, and context-aware assistance, going beyond its built-in knowledge to deliver tailored solutions for your needs.
87+
6. [] Dismiss the window by clicking **OK**.
88+
7. [] Let's execute our first prompt in the chat window:
89+
90+
```text
91+
connect to the PetsDB database using my LocalServer connection
92+
```
93+
8. [] Copilot is going to ask our permission to execute **mssql: List Connections tool**. Every time Copilot needs to execute something, it will ask your permission. In this case let's click on the dropdown selector and pick **Always allow**. This will add this tool to the auto-approve list; in the future if Copilot wants to run this tool, you will not be asked for confirmation.
94+
![always allow list connection tool execution](images/5-always-allow-tool-execution.png)
95+
9. [] Now it will ask to connect to the server, select **Always Allow** as well.
96+
10. [] We are now connected to the database. Let's see what tables the database has by running the prompt (click allow on tool execution confirmation):
97+
```text
98+
show me the list of tables
99+
```
100+
You should see two tables: **dogs** and **breeds**.
101+
102+
11. [] Now we know our database has two tables, so let's understand the schema by running the prompt:
103+
```text
104+
show me the schema
105+
```
106+
The schema designer will open, showing the structure of the database, including tables, columns, and relationships. This is possible because tool calling allows interaction with the extension itself.
107+
108+
12. [] Great, we are now ready to run a query on our **PetsDB** database. Use the prompt in the chat window:
109+
110+
```text
111+
How many "Golden Retrievers" do we have available for adoption in the Database?
112+
```
113+
12. [] When asked permission to run **mssql: Run query**, before allowing it, click on the **show more** to preview the SQL statement Copilot wants to execute to see that it was able to join tables and set the right predicates to count the number of Golden Retrievers, if you click again on the show more you can see the inputs that will be passed to the tool (**connectionId** and **query**). When a tool is executed you can always see the inputs and if you choose to execute it the output as well. The query should be similar to:
114+
115+
```sql-nocopy
116+
SELECT COUNT(*) as available_golden_retrievers
117+
FROM dogs d
118+
JOIN breeds b ON d.breed_id = b.id
119+
WHERE b.name = 'Golden Retriever'
120+
AND d.available = 'Available';
121+
```
122+
123+
12. [] Click Allow to execute the query. Copilot will tell how many golden retrievers are available for adoption.
124+
125+
> [!TIP]
126+
> Notice how Copilot understands the context of your database and generates a SQL query that:
127+
> - Joins the necessary tables (dogs and breeds)
128+
> - Filters by breed name
129+
> - Filters by availability status
130+
> - Counts the results
131+
132+
> [!TIP]
133+
> To avoid repeated approval prompts, you can configure auto-approval for tools and commands. Use the `chat.tools.autoApprove` setting to enable automatic approval per workspace, or set it globally for all workspaces. Be aware of the [security implications][copilot-tools-auto-approve] before enabling this feature, but you have control which tools you want to auto-approve.
134+
135+
> [!IMPORTANT]
136+
> Because LLMs are probabilistic, not deterministic, the exact SQL generated can vary. The query should accomplish the same goal even if the syntax differs slightly.
137+
138+
## Exercise: Explore more queries (optional)
139+
140+
If you want to get some ideas about some more complex queries that Copilot can generate, try asking Copilot these questions:
141+
142+
1. [] **Find all available dogs with their breed names**: Ask Copilot to generate a query that shows dog names, ages, and breed names for all dogs that are available for adoption.
143+
144+
> [!Hint]
145+
> Try a prompt like: "Show me all available dogs with their names, ages, and breed names"
146+
147+
2. [] **Group dogs by breed**: Ask Copilot to count how many dogs of each breed are in the database.
148+
149+
> [!Hint]
150+
> Try: "Count the number of dogs for each breed and show the breed name"
151+
152+
3. [] **Find the oldest dog**: Ask Copilot to find the name and age of the oldest dog in the shelter.
153+
154+
> [!Hint]
155+
> Try: "Find the oldest dog in the database"
156+
157+
4. [] **Complex filtering**: Ask Copilot to find all available dogs that are younger than 5 years old, grouped by breed.
158+
159+
> [!Hint]
160+
> Try: "Show me available dogs younger than 5 years old, grouped by breed with counts"
161+
162+
## Understanding query explanations
163+
164+
Copilot can also help you understand existing SQL queries. This is incredibly useful when working with complex queries or legacy code.
165+
166+
1. [] Copy a complex query from your previous exercises into the query editor.
167+
168+
2. [] Select the entire query. (or you can use this one):
169+
```sql
170+
SELECT b.name AS BreedName, COUNT(d.id) AS DogCount
171+
FROM dbo.dogs d
172+
JOIN dbo.breeds b ON d.breed_id = b.id
173+
WHERE d.status = 'available' AND d.age < 5
174+
GROUP BY b.name
175+
ORDER BY DogCount DESC;
176+
```
177+
3. [] In Copilot inline Chat, type `/explain` and press <kbd>Enter</kbd>.
178+
4. [] Read through Copilot's explanation of what the query does, including details about joins, filters, and aggregations.
179+
180+
> [!TIP]
181+
> If the text is too big and hard to read because of the scrolling, click on **View Chat** to see the explanation in the chat panel.
182+
183+
> [!NOTE]
184+
> This feature is particularly helpful when inheriting code from other developers or when returning to queries you wrote months ago.
185+
186+
## Exercise: Generate test data with the @mssql chat participant
187+
188+
GitHub Copilot can help you generate realistic test and mock data for your database. This is especially useful when you need to test your application with meaningful data, create demos, or simulate edge cases. Let's use the **@mssql** chat participant to generate test data.
189+
190+
> [!NOTE]
191+
> The **@mssql** chat participant is specifically designed for SQL Server operations and requires an active database connection to understand your schema context.
192+
193+
Before starting, type in the chat window `@mssql /` to see the available slash commands the **@mssql** chat participant offers.
194+
195+
### Generate edge case test data
196+
197+
Testing edge cases is crucial for building robust applications. Let's generate data to test boundary conditions or uncover other issues our code might have with odd data shapes.
198+
199+
1. [] Open GitHub Copilot Chat and start a new chat by clicking the **+** button.
200+
2. [] Ask Copilot to generate edge case data:
201+
202+
```text
203+
@mssql Generate insert statements for the dogs table to test edge cases. Include:
204+
- A dog with age 0 (newborn puppy)
205+
- A dog with age 20 (very old)
206+
- Dogs with very short names (1-2 characters)
207+
- Dogs with longer names (15+ characters)
208+
- Other edge case variations you can think of
209+
All should reference valid breed IDs.
210+
```
211+
212+
3. [] Review the generated SQL to see how Copilot handles these edge cases.
213+
4. [] Execute the statements.
214+
215+
> [!IMPORTANT]
216+
> Edge case testing helps you discover potential issues before they affect real users. Pay attention to how your UI displays very long names, ages at boundaries, etc.
217+
218+
## Summary and next steps
219+
220+
You've successfully used GitHub Copilot with the MSSQL extension to interact with SQL Server using natural language! You learned how to:
221+
222+
- Connect to SQL Server from VS Code
223+
- Generate SQL queries from natural language questions
224+
- Execute and validate query results
225+
- Use Copilot to explore and understand database queries
226+
227+
This integration dramatically reduces the friction of working with databases, allowing you to focus on the questions you want to answer rather than the syntax required to answer them.
228+
229+
## What's next?
230+
231+
Continue exploring more advanced Copilot capabilities:
232+
233+
- Using GitHub Copilot for Azure - Learn how to interact with Azure resources directly from VS Code
234+
235+
## Resources
236+
237+
- [GitHub Copilot for MSSQL documentation][copilot-mssql]
238+
- [SQL Server extension for VS Code][mssql-extension]
239+
- [Quickstart: Use GitHub Copilot Agent Mode (Preview)][mssql-extension-agent-mode-quickstart]
240+
- [Quickstart: Generate data for testing and mocking (Preview)][mssql-extension-data-testing-mocking-quickstart]
241+
- [Writing queries with GitHub Copilot][copilot-sql-guide]
242+
- [SQL Server T-SQL reference][tsql-reference]
243+
244+
[copilot-mssql]: https://learn.microsoft.com/en-us/sql/tools/visual-studio-code-extensions/github-copilot/overview?view=sql-server-ver17
245+
[mssql-extension]: https://marketplace.visualstudio.com/items?itemName=ms-mssql.mssql
246+
[mssql-extension-agent-mode-quickstart]: https://learn.microsoft.com/en-us/sql/tools/visual-studio-code-extensions/github-copilot/agent-mode?view=sql-server-ver17
247+
[mssql-extension-data-testing-mocking-quickstart]: https://learn.microsoft.com/en-us/sql/tools/visual-studio-code-extensions/github-copilot/test-and-mocking-data-generator?view=sql-server-ver17
248+
[copilot-sql-guide]: https://code.visualstudio.com/docs/copilot/copilot-chat
249+
[tsql-reference]: https://docs.microsoft.com/en-us/sql/t-sql/language-reference
250+
[copilot-tools-auto-approve]: https://code.visualstudio.com/docs/copilot/chat/chat-agent-mode#_autoapprove-all-tools-and-commands

0 commit comments

Comments
 (0)