P

Prompt ChatGPT to Generate SQL Queries

Generating SQL queries is an essential skill for any developer, data analyst, or database administrator. However, writing complex queries involving multiple joins, nested subqueries, or aggregate functions can be time-consuming and error-prone. ChatGPT radically transforms this practice by allowing you to describe your needs in natural language to obtain optimized and functional SQL queries in seconds. Whether you work with MySQL, PostgreSQL, SQL Server, or SQLite, the AI adapts to the specific syntax of your database management system. By providing your table schema and a clear description of what you want to obtain, you can generate perfectly structured SELECT, INSERT, UPDATE, or DELETE queries. ChatGPT also excels at line-by-line explanations of the generated queries, making it a valuable learning tool for beginners and professionals alike who want to explore advanced SQL features like CTEs, window functions, or recursive queries.

The prompt

ChatGPT

You are an expert in relational databases and SQL. I will provide you with my database schema and a natural language description of what I want to get. Generate the corresponding SQL query following these rules:

  1. SQL Dialect: [MySQL / PostgreSQL / SQL Server / SQLite]

  2. Table Schema:
    [Paste here the structure of your tables with columns, types, and relationships]

  3. What I want to get:
    [Describe precisely the expected result]

  4. Constraints:

  • Use explicit aliases for each table
  • Add SQL comments explaining each section
  • Optimize the query for performance (use indexes if relevant)
  • Handle NULL values appropriately
  • Format the query readably with indentation

After the query, provide:

  • A line-by-line explanation
  • Recommended indexes to optimize this query
  • Potential pitfalls to watch out for

Personalize this prompt with Léa

Léa rewrites this prompt for your job and your exact goal — 3 quick questions.

Why it works

This prompt works by assigning an expert role that activates the model's specialized knowledge in SQL and database optimization. Specifying the SQL dialect and table schema provides the indispensable technical context for generating a syntactically correct query tailored to your environment. The formatting, comments, and explanation constraints transform simple code generation into a documented, maintainable deliverable.

Expected result

You will get a complete SQL query, properly formatted and commented, adapted to your database dialect. The response will also include a detailed explanation of each clause, indexing recommendations to improve performance, as well as a list of common mistakes to avoid when executing this query.

Variants by level

FAQ

Can ChatGPT generate SQL queries for any database system?
ChatGPT masters the main SQL dialects: MySQL, PostgreSQL, SQL Server, Oracle, SQLite, and MariaDB. It knows the syntactic specifics of each, such as PostgreSQL-specific window functions or SQL Server's TOP statements. For best results, always specify the desired dialect in your prompt so that the AI adapts the syntax, data types, and built-in functions accordingly.
How can I ensure SQL queries generated by ChatGPT are secure?
Queries generated by ChatGPT should always be reviewed and tested before production use. For security, explicitly ask ChatGPT to use parameterized queries rather than string concatenation to prevent SQL injection. Also check table access permissions, avoid executing DELETE or UPDATE queries directly without a WHERE clause, and test first on a development environment. ChatGPT can also help audit your existing queries for potential vulnerabilities.
Can I use ChatGPT to optimize existing slow SQL queries?
Absolutely. Paste your slow query into ChatGPT, specifying the SQL dialect, data volume, and, if possible, the result of EXPLAIN or EXPLAIN ANALYZE. The AI can identify bottlenecks like full table scans, inefficient joins, or correlated subqueries, then propose optimized alternatives with appropriate indexes. It can also suggest restructuring, such as replacing subqueries with CTEs or lateral joins, to significantly improve execution times.

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 4800+ 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

Prompt ChatGPT to Prepare for an Interview

Preparing for a job interview is a decisive step in any job search. ChatGPT becomes a formidable ally for anticipating questions, structuring your answers, and building confidence before the big day.

Prompt Claude for Analyzing Customer Reviews

Analyzing customer reviews has become a strategic lever for any company looking to improve its products, services, and customer experience.

Prompt Claude for Analyzing Market Trends

Market trend analysis is a strategic exercise that requires cross-referencing economic, behavioral, and sectoral data to identify weak signals and underlying movements. Claude excels at this task thanks to its ability to synthesize large amounts of information, structure multi-dimensional analyses, and formulate well-argued hypotheses.

Prompt Claude for Automating Tasks

Task automation is one of the most powerful uses of Claude. Whether you are an entrepreneur, developer, or corporate professional, you waste considerable time each day on repetitive tasks: sorting emails, extracting data, generating reports, reformatting documents, or classifying information. Claude excels in these scenarios thanks to its ability to understand complex instructions, process structured data, and produce consistent results at scale. Unlike a rigid script, Claude adapts to format variations, handles edge cases, and can explain its decisions. By crafting a well-structured automation prompt, you turn Claude into an operational assistant capable of processing dozens of tasks in seconds with consistent quality. This guide provides optimized prompts to effectively delegate your recurring tasks to Claude, from raw data processing to formatted deliverable generation, including conditional decision-making on information flows.

Prompt Claude for Competitive Monitoring

Competitive monitoring is a strategic pillar for any company seeking to maintain its competitive edge. Traditionally time-consuming and costly, this activity can be significantly accelerated with Claude. By using structured prompts, you can ask Claude to analyze your competitors' positioning, synthesize their marketing strategies, identify their strengths and weaknesses, and spot untapped market opportunities. Claude excels at structuring disparate information into coherent and actionable analyses. Whether you are an entrepreneur, marketing manager, or strategic analyst, the prompts below will turn Claude into a true competitive monitoring assistant. AI does not replace fieldwork data collection, but it helps you organize your observations, formulate relevant hypotheses, and produce professional monitoring reports in a fraction of the usual time. Learn how to structure your requests to obtain rich and actionable competitive analyses.

Prompt Claude for Creating a Resume

Creating a powerful resume is a delicate exercise that requires synthesizing your career path while capturing recruiters' attention in just a few seconds.

Go further

Get new prompts every week

Join our newsletter.