P

Claude Prompt for Generating SQL Queries

Generating SQL queries is one of the tasks where Claude particularly excels. Whether you are a backend developer, data analyst, or database administrator, formulating complex queries can be time-consuming and error-prone. Claude understands the subtleties of different SQL dialects (PostgreSQL, MySQL, SQLite, SQL Server, Oracle) and can transform a natural language description into an optimized and functional query. The AI is capable of handling multiple joins, nested subqueries, advanced aggregate functions, CTEs (Common Table Expressions), and even window functions. By providing Claude with your database schema and a clear description of what you want, you receive a ready-to-use query with explanations of the logic used. This significantly accelerates development, reduces SQL syntax bugs, and allows even less technical profiles to confidently manipulate complex data. Claude can also optimize existing queries, detect performance issues, and suggest relevant indexes.

The prompt

Claude

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

  1. Use the following SQL dialect: [PostgreSQL / MySQL / SQLite / SQL Server]
  2. Write an optimized and readable query with explicit aliases
  3. Add SQL comments to explain each complex section
  4. Prefer explicit joins (JOIN ... ON) over implicit joins
  5. Use CTEs (WITH) if the query is complex to improve readability

Database schema:
[Paste your CREATE TABLE or describe your tables with columns and relationships]

What I want to obtain:
[Describe in natural language the desired result]

Additional constraints:

  • Filters to apply: [specify WHERE conditions]
  • Desired sorting: [ORDER BY]
  • Result limit: [LIMIT if applicable]

After the query, provide:

  • A line-by-line explanation of the logic
  • Recommended indexes to optimize performance
  • 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 because it provides Claude with a structured framework including the target SQL dialect, the exact database schema, and precise constraints, eliminating ambiguity. The request for explanations and index recommendations forces the model to reason deeply about optimization rather than producing a naive query. The numbered step format guides Claude towards an organized and complete output.

Expected result

Claude generates a syntactically correct SQL query, optimized for the specified dialect, with inline comments explaining the logic of each block. The response also includes a performance analysis with index suggestions and a detailed explanation allowing you to understand and adapt the query to your needs.

Variants by level

FAQ

Can Claude handle all SQL dialects?
Claude masters the main SQL dialects: PostgreSQL, MySQL, SQLite, SQL Server, Oracle, and MariaDB. It knows the specifics of each dialect, such as PostgreSQL-specific window functions (FILTER, WITHIN GROUP), LIMIT/OFFSET vs TOP syntax, or differences in date handling. For best results, always specify the target dialect in your prompt so Claude uses the appropriate syntax and functions.
How to effectively provide my database schema to Claude?
The most reliable method is to paste your CREATE TABLE statements directly with constraints (PRIMARY KEY, FOREIGN KEY, INDEX). If your schema is too large, focus on the tables involved in your query and mention key relationships. You can also describe your tables in natural language (e.g., 'users table with id, name, email, date_creation') but complete DDL reduces interpretation errors. Remember to include data types, as they influence the functions and conversions Claude will use.
Can Claude optimize an existing SQL query that is too slow?
Yes, this is one of the most powerful use cases. Provide Claude with your current query, the schema of the tables involved, approximate data volume, and if possible, the output of EXPLAIN ANALYZE. Claude will identify bottlenecks (full table scans, inefficient joins, correlated subqueries) and propose an optimized version with indexes to create. It can transform subqueries into joins, rewrite queries with CTEs to improve readability, or suggest alternative approaches like denormalization or materialized views.

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

Claude Prompt for Planning a Product Launch

The launch of a product is a pivotal moment that can determine the success or failure of an offer in the market. Between defining positioning, coordinating marketing teams, planning distribution channels and managing the timeline, there are many variables to orchestrate.

Claude Prompt for Summarizing a Document

Summarizing a document is one of the tasks where Claude excels the most. Whether you have a 50-page report, a dense scientific article, or a complex legal contract, Claude can extract the essentials in seconds. But the quality of the summary directly depends on the precision of your prompt. A vague prompt like 'summarize this text' will produce a generic summary that will likely miss the points that matter to you. In contrast, a well-structured prompt—specifying the target audience, desired level of detail, output format, and aspects to prioritize—transforms Claude into a remarkably efficient synthesis assistant. In this guide, you will find optimized prompts to obtain clear summaries that are faithful to the source document and tailored to your specific needs. Whether you are a student, professional, or researcher, these prompts will save you hours of reading while capturing essential information without distortion or critical omission.

Claude Prompt for Translating a Text

Translation is one of Claude's most powerful use cases. Unlike traditional machine translation tools, Claude understands context,

Claude Prompt for Writing a Business Proposal

Writing a compelling business proposal is a strategic exercise that combines client understanding, structured argumentation, and measured persuasion

Claude Prompt for Writing a Job Offer

Writing an effective job offer requires juggling technical precision, attractiveness, and legal compliance. A poorly written ad can discourage the best candidates or attract unsuitable profiles, significantly lengthening the recruitment process.

Claude Prompt for Writing a Newsletter

Writing an engaging and regular newsletter is a major challenge for content creators, marketers, and entrepreneurs. Between writer's block, maintaining a consistent tone, and the need to captivate an audience solicited from all sides, the process can quickly become time-consuming.

Go further

Get new prompts every week

Join our newsletter.