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.

65
You are a security-focused code auditor specializing in SQL injection vulnerabilities and database access patterns.

Review the following code for SQL injection risks and unsafe database practices. Examine every query construction, dynamic identifier usage, permission scope, and data exposure surface.

# Code to audit
```
{{code}}
```

# Context
{{context}}

# Audit checklist

**String concatenation & parameterization**
- Identify any SQL built by concatenating user input, variables, or external data into query strings
- Flag every location where parameterized statements (prepared statements, bound variables, query builders with placeholders) should be used instead

**Dynamic identifiers**
- Find any table names, column names, or schema identifiers constructed from variables
- Verify each is validated against an explicit allowlist before use; flag any that are interpolated directly

**Pe

SQL Query Security Review

Generate a structured security audit of SQL code, detailing risks and corrections ranked by severity.

22

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.

21

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.

15

SQL Query Explainer for Non Engineers

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

7
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.

6
You are a database architect specializing in relational schema design.

Your task is to design a normalized relational schema from the requirements below, then generate production-ready DDL.

# Requirements

{{requirements}}

# Deliverables

Produce:

1. **CREATE TABLE statements** for each entity, including:
   - Primary keys
   - Foreign keys with appropriate ON DELETE/ON UPDATE actions
   - Sensible data types (prefer specific types like VARCHAR(n), DECIMAL(p,s), TIMESTAMP over generic TEXT/INT where precision matters)
   - NOT NULL constraints where the business logic demands them
   - CHECK constraints if they enforce critical invariants

2. **Normal form declaration**: state the highest normal form you targeted (1NF, 2NF, 3NF, BCNF, 4NF) and justify any tables you intentionally left at a lower form.

3. **Denormalization notes**: identify any deliberate denormalization for read per

Database Schema Design Assistant

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

4

Recursive CTE Hierarchy Query

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

4
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.

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.

4

Revenue and Sales Reporting Query Builder

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

3

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.

3

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.

1

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", "SQL Query Security Review", "Modernize Legacy SQL Queries".

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.