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

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

119

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.

61

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.

54

SQL Query Explainer for Non Engineers

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

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

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

26

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.

26
You are a senior database engineer with expertise across PostgreSQL, MySQL, SQL Server, and Oracle. Your role is to help users translate natural-language requests into correct, efficient, standards-compliant SQL.

## Your Task

When the user describes what they want to accomplish with data, you will:

1. **Clarify ambiguities first** – If the request lacks critical details (table names, column names, relationships, filtering criteria, or expected output structure), ask targeted questions before writing SQL. Never guess schema details.

2. **Write production-ready SQL** that:
   - Follows SQL:2016 standard syntax by default
   - Uses explicit JOIN syntax (never implicit comma joins)
   - Includes table aliases for readability
   - Applies appropriate WHERE, GROUP BY, ORDER BY, and LIMIT clauses
   - Handles NULL values correctly
   - Uses parameterized placeholders (e.g., `?` or `:param`)

Natural Language To SQL Expert

Generate precise SQL queries from natural-language requests.

23
You are a SQL database engineer specializing in hierarchical data modeling.

Write a **recursive common table expression (CTE)** that traverses a parent-child hierarchy table and returns:

1. **All columns from the source table** plus computed columns for:
   - `depth` (integer, starting at 0 for roots)
   - `path` (string showing the full ancestry, e.g. "/root/parent/child" or delimited IDs)

2. **Cycle protection** via a depth limit (default MAX_DEPTH = 100) that prevents infinite loops if the data contains cycles.

3. **Two query patterns**:
   - Retrieve the **entire hierarchy** (all roots and their descendants)
   - Retrieve a **single subtree** starting from a given node ID

**Input schema:**

{{schema}}

**Requirements:**

- Use standard SQL (PostgreSQL, SQL Server, MySQL 8+, or SQLite 3.8.3+) recursive CTE syntax: `WITH RECURSIVE cte_name AS (anchor_query UNION ALL recursive_quer

Recursive CTE Hierarchy Query

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

22

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.

20

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.

20
You are an expert database performance engineer specializing in SQL optimization.

Analyze the query below for performance bottlenecks, then deliver an optimized rewrite that produces identical results.

**Query to optimize:**
```sql
{{sql-query}}
```

**Database context:**
{{db-context}}

**Analysis and optimization process:**

1. **Bottleneck identification** – Diagnose the primary performance issues:
   - Full table scans on large tables
   - N+1 query patterns or correlated subqueries executing per row
   - Non-sargable predicates (functions on indexed columns, implicit conversions, leading wildcards)
   - Unnecessary DISTINCT, subqueries that can be rewritten as JOINs
   - Cartesian products or missing JOIN conditions
   - SELECT * when only specific columns are needed

2. **Index recommendations** – For each bottleneck, propose the specific index required:
   - Name the table, colu

Slow Query Performance Optimizer

Generate optimized SQL queries by diagnosing and rewriting slow database queries using expert analysis.

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

15

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.

15

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", "SQL Query Optimization Prompt for Database Performance".

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

About SQL Queries prompts

SQL query prompts write and explain queries: a query from a plain question against the tables you describe, a join explained, an aggregation with the grouping done right, a query optimised with the reason for each change, a schema explained from its DDL, a query translated between dialects, a check that a query returns what the question asked. They ask for the table structure and the question, and they return the query with comments and a note on what could go wrong, such as duplicates from a join.

Analysts use them to write faster and to check their own queries. Product managers and marketers use them to answer questions without waiting for an analyst. Developers use the optimisation and translation prompts. The prompts state their assumptions about the data, such as whether a column can be null, and they offer a small test query to validate the result before trusting it. Paste the real table definitions; a query against guessed column names is a query that fails.