14 AI Prompts for SQL Queries

The best SQL Queries prompts in the Data Analysis library. Tested on ChatGPT, Claude, Gemini and every major model.

Browse the prompts

You are a SQL query generator that translates plain-English questions into correct, readable SQL.

# Task
Given a natural-language question about data, produce a SQL query that answers it. If the user has not specified table or column names, infer them from context or ask clarifying questions. State your assumptions about the schema so the user can verify them.

# Requirements
- Use explicit JOIN syntax (INNER JOIN, LEFT JOIN, etc.) with ON conditionsโ€”never implicit comma joins
- Alias tables with short, meaningful names (e.g., `customers AS c`, `orders AS o`)
- Write standard SQL that works across PostgreSQL, MySQL, and SQL Server unless told otherwise
- Include a brief explanation below the query: one line per major clause (SELECT, FROM, JOIN, WHERE, GROUP BY, HAVING, ORDER BY) describing what it does in plain English

# Input
Question: {{question}}

Database context (optionalโ€”table na

Plain English to SQL Query Converter

Generate SQL queries from plain-English questions with assumptions and explanations.

50
## Role

You are a database modernization specialist transforming legacy SQL into clean, maintainable SQL:2016 standard code.

## Task

Modernize the provided SQL queries by:

- Replacing correlated subqueries with window functions
- Implementing common table expressions (CTEs) for complex logic
- Converting nested conditionals to clean CASE expressions
- Eliminating comma-separated FROM clauses with proper JOIN syntax
- Standardizing string concatenation
- Restructuring complex queries into logical, step-by-step CTEs with descriptive names that explain business purpose
- Replacing proprietary database functions with SQL:2016 standard equivalents

## Context

These legacy queries contain outdated syntax patterns, proprietary extensions, and complex nested logic that create technical debt, break during upgrades, and confuse developers.

{{modernization-priorities}}

## Input

{{legacy-sql

Modernize Legacy SQL Queries

Transforms outdated SQL into clean SQL:2016 standard code by replacing correlated subqueries, nested logic, and proprietary syntax with CTEs, window functions, and modern JOIN patterns. Runs on ChatGPT, Claude, Gemini, and Grok.

18

SQL Query Optimization Prompt for Database Performance

Guides you through creating optimized SQL queries using Baron Schwartz's principles, adapting from 3 to 15 phases based on complexity. Runs on ChatGPT, Claude, Gemini, and Grok to analyze schemas, design efficient joins, and improve query performance across MySQL, PostgreSQL, SQL Server, and Oracle.

14

SQL Query Explainer for Non Engineers

Translate an SQL query into plain language, allowing non-technical users to understand its purpose and functionality.

5
You are a senior analytics engineer specializing in event-driven conversion funnels and user journey analysis.

Write a SQL query that calculates a **sequential, ordered multi-step conversion funnel** from an events table. The query must:

- **Enforce step order per user**: count only the first occurrence of each step in sequence; a user must complete step N before step N+1 is recognized
- **Apply an attribution window**: events must fall within {{attribution-window}} of the user's first step to count toward the funnel
- **Handle edge cases**: users who repeat steps (count only the first), skip steps (do not credit them for later steps), or never complete the funnel
- **Calculate and return**:
  1. Count of unique users reaching each step
  2. Drop-off count and drop-off % between consecutive steps
  3. Overall conversion rate from first step to final step

**Context:**
{{funnel-definiti

Funnel Conversion Analysis Query

Generate a SQL query for analyzing multi-step conversion funnels from an events table, enforcing step order and handling various user journey scenarios.

4
You are a SQL data quality engineer. Generate a comprehensive audit suite for a database table that checks for common data integrity and quality issues.

# Table to Audit
{{table-schema}}

# Requirements
Produce a set of standalone SQL queries (SELECT statements) that identify data quality problems. Each query should:
- Return both a count of affected rows and a sample (up to 10 rows) of the offending records
- Include helpful column aliases that describe the issue found
- Be runnable independently for focused troubleshooting

Cover these checks:
1. **Null rate per column** โ€“ count and percentage of nulls in each column, show sample rows with nulls
2. **Duplicate rows** โ€“ duplicates based on {{primary-key}}, with count per duplicate group and sample records
3. **Orphaned foreign keys** โ€“ foreign key values that don't exist in parent tables (specify the parent table and key for each FK in

SQL Data Quality Audit Query Set

Generates a set of SQL queries for auditing data quality in a database table, producing focused reports on various common issues.

3

Database Schema Design Assistant

Generates a normalized relational schema, ready for production, from application requirements, with detailed CREATE TABLE and INDEX statements.

2
You are an expert SQL database engineer specializing in cross-dialect query translation.

Translate the provided SQL query from the source dialect to the target dialect. Ensure the translated query is functionally equivalent and idiomatic in the target dialect.

**Source Dialect:** {{source-dialect}}
**Target Dialect:** {{target-dialect}}
**Query to Convert:**
```sql
{{sql-query}}
```

**Translation Requirements:**

1. **Dialect-Specific Functions:** Convert all date/time functions (DATEADD, DATE_SUB, EXTRACT, etc.), string functions (CONCAT, STRING_AGG, GROUP_CONCAT, LISTAGG, etc.), and aggregation functions to their target dialect equivalents.

2. **Syntax Adjustments:** Translate identifier quoting (backticks, double quotes, square brackets), LIMIT/OFFSET vs TOP vs FETCH FIRST syntax, boolean literals (TRUE/FALSE vs 1/0), and type casting (CAST vs :: vs CONVERT).

3. **Schema & Data T

SQL Dialect Migration Converter

Convert SQL queries from one dialect to another, ensuring functional equivalency across different database systems.

2
You are an expert SQL analyst writing production-grade revenue reports.

Write a SQL query that produces a revenue report from `orders` and `customers` tables with the following requirements:

**Schema context**
{{schema-details}}

**Report specification**
- Group by: {{grouping}}
- Metrics: total revenue, order count, average order value, unique customer count
- Explicitly handle refunds and cancelled orders (state your treatment: exclude, include as negative, or separate column)
- Clearly state whether tax and shipping are included in revenue and document your decision in a comment
- Use consistent date-boundary logic: periods must not overlap and must not leave gaps (e.g., month boundaries at midnight on the 1st, week start on Monday 00:00:00)

**Output the query with:**
1. Opening comment block documenting:
   - Revenue definition (what is included/excluded)
   - Refund and cancellat

Revenue and Sales Reporting Query Builder

Generate sophisticated SQL queries for production-grade revenue reports, tailored to your database schema context and groupings.

2

SQL Window Function Builder

Generate SQL queries using window functions for analytical tasks involving ranking, running totals, and comparisons over time, with detailed explanations and examples.

2

Recursive CTE Hierarchy Query

Generate a recursive common table expression (CTE) for hierarchical queries with cycle protection, suitable for SQL databases.

1

SQL Cohort Retention Analysis Query

Generate a SQL query for cohort retention analysis, producing both raw counts and retention percentages. Tailor the query for different SQL dialects and period grains.

0

What are AI prompts for SQL Queries?

AI prompts for SQL Queries are engineered instructions that already work. These are not one-line questions. Each one fixes the role, the context, the task and the output format before you type a word, so you get a usable result on the first run instead of the fourth.

They cover the work SQL Queries actually get asked for: research and briefs, copy and content, analysis and reporting, planning, outreach and the admin that eats the day. Open a card to see the full prompt and the output it returns.

Popular on this page right now: "Plain English to SQL Query Converter", "Modernize Legacy SQL Queries", "SQL Query Optimization Prompt for Database Performance".

14 on this page, every one scoped to SQL Queries. Free to read, free to copy.

Why these prompts work for SQL Queries

A weak prompt costs you the hour you were trying to save: you rewrite it three times, get something generic, then finish the job by hand. An engineered prompt front-loads that thinking once.

In SQL Queries that means first drafts you can send, analysis you can act on, and the repetitive work handed off, so the time goes into judgement instead of typing.

Every prompt here was written for a real job and tested against the models people actually use. Nothing scraped from a thread.

How to use these prompts

Open a prompt, copy it, and replace the [bracketed] variables with your own product, audience or topic. The structure around them stays as is. That structure is the part doing the work.

Paste it into ChatGPT, Claude, Gemini, Grok or the model you already use. If the output drifts, tighten the context line instead of rewriting the whole prompt.

No account needed to copy one. No setup, no extension, nothing to install.

Which AI tool works best for SQL Queries prompts?

Text prompts here run well in ChatGPT, Claude, Gemini and Grok; image prompts target Midjourney and Nano Banana. Each card lists the models it was tested with.

Are these AI prompts free to use?

A big part of the library is free: open a prompt, copy it, use it. Premium packs and the Complete AI Bundle unlock the full collection with lifetime updates.

How do I adapt these prompts to my use case?

Start with the [variables]: niche, audience, constraints. If the result still misses, add one example of the output you want. A single good example beats three extra instructions.

For a prompt built from scratch, the Start Now card above opens the custom prompt generator.

Related resources

Get smarter on AI every week

One email a week with the best new prompts, tools, and model updates. Unsubscribe anytime.

Join 100,000+ subscribers. One email a week, real prompts, tools, and model updates. Unsubscribe anytime.