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.

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 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 ChatGPT to Write a Report

Report writing is an essential professional skill, whether for activity reports, market analyses, project summaries, or strategic syntheses. Yet structuring ideas, adopting the right tone, and producing a clear, impactful document takes considerable time. ChatGPT radically transforms this process by supporting you at every stage: from defining the outline to the final draft, including rewriting and formatting. With a well-constructed prompt, you get a structured, professional report tailored to your audience in minutes instead of hours. The goal is not to fully delegate writing to AI, but to use it as an intelligent copilot that accelerates your output while keeping your expertise at the center. Whether you are a consultant, manager, analyst, or student, mastering good prompts for report writing gives you a measurable competitive advantage. Discover below the optimized prompt and its variants to produce professional-quality reports with ChatGPT.

Prompt ChatGPT to Write a Thesis

Writing a thesis is one of the most demanding academic exercises: structuring complex thoughts, articulating a research question, synthesizing sources, and producing a coherent argument over dozens of pages. ChatGPT can become a valuable ally in this process, not to write for you, but to support you at every key stage. From defining your research question to building a detailed outline, reformulating your ideas, and writing smooth transitions, the AI helps you overcome writer's block and maintain a rigorous thread. Used intelligently, ChatGPT accelerates the structuring phase, suggests analytical angles you might not have considered, and allows you to produce first drafts of chapters that you will later refine with your expertise. The goal is never to replace your personal reflection, but to catalyze it. This prompt is designed to guide ChatGPT into the role of a virtual thesis supervisor, capable of adapting to your discipline, academic level, and specific institutional requirements.

Prompt Claude for Designing Software Architecture

Software architecture design is a fundamental step that determines a project's maintainability, scalability, and robustness. Claude exce

Prompt Claude for Writing a Cover Letter

Writing a convincing cover letter is a delicate exercise that requires finding the right balance between professionalism, authenticity, and relevance.

Prompt Claude for Writing a Professional Bio

Writing a compelling professional bio is a delicate exercise that requires finding the right balance between highlighting your career and authenticity.

Go further

Get new prompts every week

Join our newsletter.