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 transforms this practice radically 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, you can generate perfectly structured SELECT, INSERT, UPDATE, or DELETE queries. ChatGPT also excels at line-by-line explanations of generated queries, making it a valuable learning tool for beginners and professionals alike who wish to explore advanced SQL features like CTEs, window functions, or recursive queries.
Paste in your AI
Paste this prompt in ChatGPT, Claude or Gemini and customize the variables in brackets.
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 achieve. Generate the corresponding SQL query following these rules:
-
SQL dialect: [MYSQL / POSTGRESQL / SQL_SERVER / SQLITE]
-
Table schema:
[Paste your table structure with columns, types, and relations here] -
What I want:
[Describe the expected result precisely] -
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 in a readable way 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 this prompt 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 essential technical context to generate a syntactically correct query tailored to your environment. The formatting constraints, comments, and explanation transform a simple code generation into a documented and maintainable deliverable.
Use Cases
Variants
Expected Output
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, and a list of common errors to avoid when executing this query.
Frequently Asked Questions
Can ChatGPT generate SQL queries for any database system?
ChatGPT is proficient in major SQL dialects: MySQL, PostgreSQL, SQL Server, Oracle, SQLite, and MariaDB. It understands the syntactic nuances of each, such as PostgreSQL-specific window functions or SQL Server's TOP statements. For best results, always specify your desired dialect in your prompt so the AI can adapt the syntax, data types, and built-in functions accordingly.
How can I ensure ChatGPT-generated SQL queries are secure?
Queries generated by ChatGPT should always be reviewed and tested before production use. For security, explicitly ask ChatGPT to use parameterized queries instead of string concatenation to prevent SQL injections. Also verify table access permissions, avoid executing DELETE or UPDATE statements directly without a WHERE clause, and test first on a development environment. ChatGPT can also help audit your existing queries to detect 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 output of EXPLAIN or EXPLAIN ANALYZE. The AI can identify bottlenecks such as full table scans, inefficient joins, or correlated subqueries, and then propose optimized alternatives with appropriate indexes. It can also suggest restructuring, like replacing subqueries with CTEs or lateral joins, to significantly improve execution times.
Improve this prompt
Run this prompt through the Optimizer to strengthen its context, constraints and expected format.
Improve this prompt with the OptimizerComments
- LéaAI
Pour les UPDATE/DELETE, demande une clause RETURNING (PostgreSQL, SQL Server) pour récupérer directement les lignes affectées sans deuxième requête. Cela évite les écarts de lecture et réduit le nombre d'appels.
📬 Get new prompts every week
Join our newsletter and never miss a prompt.
Go further
Similar Prompts
Write an ORM query
Write efficient ORM queries
Stable Diffusion Prompt to Generate JavaScript Code
Stable Diffusion is an AI image generation model, not a proper code generation tool. However, it can be used creatively in the context of JavaScript development. Stable Diffusion excels at creating code-related visuals: stylized screenshots of JavaScript snippets, illustrations of programming concepts, software architecture diagrams, or educational images for tutorials and technical documentation. By combining well-crafted prompts, you can generate visual representations of JavaScript code on screen, infographics explaining algorithms, or illustrations for your technical blog posts. This approach is particularly useful for tech content creators, web development instructors, and marketing teams who need professional visuals around JavaScript programming. In this guide, we offer optimized prompts for achieving high-quality visual renderings featuring JavaScript code in various visual contexts.
Implement property-based testing
Add property-based tests
Implement rate limiting
Protect APIs from abuse