P

GitHub Copilot Prompt to Generate SQL Queries

GitHub Copilot radically transforms how developers write SQL queries daily. Integrated directly into your code editor, this AI assistant understands your project context — table schemas, entity relationships, naming conventions — to generate precise and optimized SQL queries. Whether you work with PostgreSQL, MySQL, SQL Server or SQLite, Copilot adapts to your database engine's specific syntax. The challenge is not merely to generate functional SQL, but to obtain performant, readable, and maintainable queries. A well-structured prompt enables Copilot to produce complex joins, correlated subqueries, window functions, and aggregation queries that follow best practices. By providing your table schema, expected output, and performance constraints, you get production-ready queries rather than drafts to rework. This guide offers an optimized main prompt as well as variants adapted to your skill level, to fully leverage Copilot in generating reliable and performant SQL queries.

The prompt

GitHub Copilot

-- Database schema:
-- Table: users (id INT PK, email VARCHAR, created_at TIMESTAMP, plan VARCHAR)
-- Table: orders (id INT PK, user_id INT FK->users.id, amount DECIMAL, status VARCHAR, created_at TIMESTAMP)
-- Table: order_items (id INT PK, order_id INT FK->orders.id, product_id INT, quantity INT, unit_price DECIMAL)
-- Table: products (id INT PK, name VARCHAR, category VARCHAR, price DECIMAL)

-- Engine: PostgreSQL 15
-- Objective: Generate a query that returns monthly revenue by product category for the last 12 months, with percentage change from previous month, excluding cancelled orders.
-- Constraints: use CTEs for readability, window functions for change calculation, and index filtered columns.
-- Output format: month, category, revenue, change_pct

Personalize this prompt with Léa

Answer 3 questions and Léa tailors the prompt to your situation.

Why it works

This prompt works because it provides Copilot with three essential elements: the complete table schema with types and relationships, the target SQL engine to adapt syntax, and a precise description of the expected output with output columns. By specifying technical constraints (CTEs, window functions), you guide Copilot towards an implementation that follows best practices rather than a naive solution with nested subqueries. The SQL comment format allows natural integration in the editor, where Copilot excels at completing the code that follows.

Expected result

Copilot generates a complete SQL query using CTEs to structure the calculation in clear steps: first monthly revenue by category, then applying LAG() to calculate the change. The query includes filters on order status and period, with readable aliases and consistent ORDER BY. You get a query ready to execute, readable by the whole team, and easily modifiable.

Variants by level

FAQ

How can I make GitHub Copilot understand my database schema?
The most effective way is to place your schema definitions (CREATE TABLE) in a SQL file opened in an adjacent tab or in the same file. Copilot analyzes open files as context. You can also write the schema in SQL comments just before your query, as in the main prompt. For projects using an ORM (Prisma, Drizzle, SQLAlchemy), Copilot can also infer the schema from your model files if they are open in the editor.
Can Copilot optimize an existing SQL query that is too slow?
Yes, paste your slow query and add a comment like '-- Optimize this query: it takes 12s on a 5M row table. Available indexes: idx_orders_created_at, idx_orders_user_id'. Copilot can rewrite the query by replacing correlated subqueries with joins, using materialized CTEs, or restructuring WHERE conditions to better leverage indexes. However, for a true performance diagnosis, combine Copilot with EXPLAIN ANALYZE on your SQL engine.
Does GitHub Copilot handle syntax differences between PostgreSQL, MySQL and SQL Server?
Copilot adapts to the SQL engine if you specify it in the prompt. Without indication, it tends to generate standard SQL or PostgreSQL. To get specific syntax, indicate the engine and its version in a comment (e.g., '-- MySQL 8.0' or '-- SQL Server 2022'). Common differences it handles well include: LIMIT vs TOP, date functions (DATE_TRUNC vs DATEPART), JSONB types (PostgreSQL) vs JSON_VALUE (SQL Server), and recursive CTE syntax which varies by engine.

Related prompts

How to use this prompt

  1. Copy the prompt with the button above.
  2. Paste it into ChatGPT, Claude or your favorite AI assistant.
  3. Replace the bracketed variables with your details, then refine the result.

About Prompt Guide

Prompt Guide is a free library of 2500+ ready-to-use prompts for ChatGPT, Claude and other AIs, with guides to learn prompting and tools to build and optimize your own prompts.

More prompts to explore

GitHub Copilot Prompt to Generate Unit Tests

GitHub Copilot has become an indispensable ally for developers looking to speed up writing unit tests. Thanks to its direct integration into the code editor, it analyzes the context of your source files to suggest relevant tests covering edge cases. However, the quality of generated tests heavily depends on the precision of the prompt used. A vague prompt will produce superficial tests, while a structured prompt will guide Copilot toward exhaustive coverage including normal cases, expected errors, and boundary behaviors. In this guide, we offer an optimized prompt to generate robust unit tests with GitHub Copilot, regardless of your tech stack. You'll discover how to formulate your instructions to obtain tests that respect your project's conventions, use the right test framework, and cover critical scenarios you might forget. Whether you work with JavaScript using Jest, Python with pytest, or Java with JUnit, these prompts adapt to your development environment.

GitHub Copilot Prompt to Optimize a Conversion Rate

GitHub Copilot, the AI-powered coding assistant, is not limited to classic code generation. In the context of conversion rate optimization...

GitHub Copilot Prompt to Optimize a Landing Page

GitHub Copilot, the AI-powered coding assistant from GitHub, is not limited to writing functions or unit tests. Used intelligently, it becomes a formidable ally for optimizing landing pages—those crucial pages that turn visitors into customers.

GitHub Copilot Prompt to Optimize a Workflow

GitHub Copilot has become an essential assistant for developers looking to optimize their development workflows. Whether you are working on

GitHub Copilot Prompt to Refactor Code

Code refactoring is a crucial step in software development that involves restructuring existing code without changing its external behavior.

Midjourney Prompt for Analyzing a Contract

Midjourney, as an AI image generation tool, cannot analyze the textual content of a contract in the legal sense. However, it excels at creating impactful visuals to illustrate complex contractual concepts: negotiation process infographics, visual representations of key clauses, decision flow diagrams, or professional illustrations for legal presentations. These visuals transform dry documents into engaging communication materials, making them easier to understand for non-legal audiences. Whether you are a lawyer preparing a client presentation, a legal officer training your teams, or an entrepreneur looking to simplify your terms and conditions, Midjourney allows you to create professional-quality visual representations. The following prompts are designed to generate clear, structured illustrations that are appropriate for the legal and contractual context, respecting the visual codes of the sector: sobriety, clarity, and professionalism. Discover how to turn contract analysis into a visual experience with optimized prompts for Midjourney.

Go further

Get new prompts every week

Join our newsletter.