Coding
AI SQL Query and Database Prompts
Get 10 copy-ready prompts for writing, explaining, debugging, optimizing and safely changing SQL across common database systems.
The prompts
Copy a prompt, then replace the parts in [BRACKETS] with your own details.
You are a careful SQL assistant. Write a query for [SQL DIALECT AND VERSION]. Business request: [PLAIN-ENGLISH QUESTION] Schema: [PASTE TABLES, COLUMNS, DATA TYPES, PRIMARY KEYS, FOREIGN KEYS AND RELATIONSHIPS] Requirements: [DESIRED COLUMNS] [EXPECTED ROW GRAIN, SUCH AS ONE ROW PER CUSTOMER] [FILTERS] [DATE RANGE AND TIME ZONE] [DEFINITIONS FOR AMBIGUOUS TERMS] Use only the supplied tables and columns. Do not invent fields or business rules. If information is missing, ask up to five specific questions before writing SQL. Return: 1. Assumptions and ambiguities. 2. One SELECT-only query in a code block. 3. A short explanation of joins, filters and aggregation. 4. Expected result shape. 5. Two validation checks. 6. Index or performance notes. Do not claim the query is correct without testing it.
Tip: Add three to five synthetic rows when duplicates, NULLs or date boundaries could change the result.
Explain the SQL below for [BEGINNER, ANALYST OR DEVELOPER]. The database is [SQL DIALECT AND VERSION]. SQL: [PASTE SQL QUERY] Schema and relationships: [PASTE RELEVANT SCHEMA] Explain each clause in execution order. Cover joins, filters, NULL behavior, grouping, window functions, sorting and result grain. Identify any assumptions, possible duplicate rows, dialect-specific syntax or logic risks. Then provide: 1. A plain-language summary. 2. A line-by-line explanation. 3. A small example of the expected result shape. 4. Three checks I should run to confirm the query behaves as intended. 5. A clearer rewrite only if it preserves the same result. Do not invent the business meaning of a column. Mark unclear points as questions.
Tip: Give the expected output grain so the explanation can focus on the logic that matters.
Debug this SQL query for [SQL DIALECT AND VERSION]. Do not guess missing schema details. Query: [PASTE QUERY] Error message: [PASTE EXACT ERROR] Schema: [PASTE RELEVANT TABLES, COLUMNS, TYPES AND KEYS] Expected result: [DESCRIBE OR SHOW A SMALL EXPECTED RESULT] First, identify the likely cause and any separate logic problems. Then return: 1. The corrected query in a code block. 2. A concise explanation of each change. 3. Any dialect-specific issue. 4. A test query or test case for the original error. 5. Two checks for wrong joins, duplicate rows, NULLs or incorrect date handling. Use only supplied names. If more than one fix is possible, show the safest option first and explain the difference. Do not add INSERT, UPDATE, DELETE, DROP or ALTER statements.
Tip: Paste the exact error and the smallest query that still fails.
Review the following [SQL DIALECT AND VERSION] query for correctness, not just syntax. Query: [PASTE QUERY] Schema: [PASTE TABLES, COLUMNS, TYPES, KEYS AND RELATIONSHIPS] Business goal: [PLAIN-ENGLISH GOAL] Expected row grain: [ONE ROW PER CUSTOMER, ORDER, DAY OR OTHER GRAIN] Review it for: 1. Incorrect or incomplete joins. 2. Duplicate rows and accidental fan-out. 3. NULL and empty-value handling. 4. Inclusive and exclusive date boundaries. 5. Incorrect aggregation or window logic. 6. Unclear business definitions. 7. Unnecessary SELECT * or unsafe assumptions. Return a severity-labelled review, a corrected SELECT-only query if needed, validation queries, and questions that must be answered before use. Do not claim semantic correctness without test data.
Tip: State the expected row count or a trusted total when you have one.
Help optimize this slow [SQL DIALECT AND VERSION] query without changing its intended result. Query: [PASTE QUERY] Schema and table sizes: [PASTE TABLES, COLUMNS, TYPES AND APPROXIMATE ROW COUNTS] Indexes and constraints: [PASTE INDEXES, PRIMARY KEYS AND FOREIGN KEYS] Execution plan: [PASTE EXPLAIN OR EXPLAIN ANALYZE OUTPUT] Observed issue: [QUERY TIME, RESOURCE ISSUE OR SLOW STEP] Business goal and expected row grain: [DESCRIBE GOAL] Return: 1. Findings ranked by likely impact. 2. A revised query, if safe. 3. Index or statistics suggestions with trade-offs. 4. Steps that may reduce scans, sorting or row multiplication. 5. A validation plan proving the result stayed the same. 6. Dialect-specific cautions. Do not recommend changes based only on guesswork. Do not modify data or schema.
Tip: Include the execution plan and table sizes, because query text alone rarely shows the slowest operation.
Convert this query from [SOURCE DIALECT AND VERSION] to [TARGET DIALECT AND VERSION]. Query: [PASTE SQL] Relevant schema: [PASTE TABLES, COLUMNS, TYPES AND KEYS] Required behavior: [DESCRIBE EXPECTED RESULT, DATE RULES, NULL RULES AND ROW GRAIN] Preserve the query's meaning, filters, joins, grouping, ordering and duplicate behavior. Identify every changed function or syntax pattern, including date handling, string functions, Boolean values, identifier quoting, pagination and type casts. Return: 1. The converted query in a code block. 2. A compatibility warning for features that may differ. 3. A change table with source syntax, target syntax and reason. 4. Test cases for normal rows, NULLs, empty results and date boundaries. 5. Any part that cannot be converted safely without more information. Do not invent tables or columns. Do not execute or modify data.
Tip: Name both database versions, since supported functions can vary between releases.
Create a SELECT-only analytics query for [SQL DIALECT AND VERSION]. Question: [BUSINESS QUESTION] Schema: [PASTE TABLES, COLUMNS, TYPES, KEYS AND RELATIONSHIPS] Definitions: [DEFINE METRICS SUCH AS ACTIVE USER, REVENUE OR COMPLETED ORDER] Analysis rules: [DATE RANGE] [TIME ZONE] [ROW GRAIN] [NULL AND DUPLICATE RULES] [EXCLUSIONS] Use only supplied schema details. Ask questions instead of guessing. Return: 1. Assumptions and unresolved definitions. 2. A SELECT-only query. 3. A plain-language explanation. 4. Expected columns and row grain. 5. Validation queries for counts, totals and duplicate rows. 6. Performance notes. Check for join fan-out, date boundary errors, NULL values and accidental filtering in a LEFT JOIN. Do not use SELECT * unless I request it.
Tip: Include a trusted total or sample result so the model can suggest a useful validation check.
Write a [COHORT, RETENTION, FUNNEL OR ROLLING-AVERAGE] query for [SQL DIALECT AND VERSION]. Business definition: [DEFINE THE EVENT, COHORT AND SUCCESS CONDITION] Schema: [PASTE TABLES, COLUMNS, TYPES, KEYS AND RELATIONSHIPS] Rules: [COHORT DATE RULE] [ACTIVITY OR CONVERSION RULE] [PERIOD LENGTH, SUCH AS WEEK OR MONTH] [DATE RANGE] [TIME ZONE] [EXCLUSIONS] Expected output: [DESCRIBE COLUMNS AND ROW GRAIN] Before writing SQL, list ambiguities about dates, repeat events, NULLs, time zones and duplicate events. Then provide a SELECT-only query, a short explanation, a small sample output shape and validation queries. Use only the supplied schema. Do not invent a metric definition or claim the result is correct without testing.
Tip: Define the cohort event and return period precisely, such as first purchase month and purchases in later calendar months.
Review this relational database design for [APPLICATION OR BUSINESS USE]. The target database is [SQL DIALECT AND VERSION]. Schema: [PASTE CREATE TABLE STATEMENTS OR TABLE AND COLUMN LIST] Expected users and workflows: [DESCRIBE MAIN OPERATIONS AND REPORTS] Review: 1. Primary and foreign keys. 2. Relationship cardinality. 3. NULL and default choices. 4. Data types and precision. 5. Naming consistency. 6. Constraints that protect data quality. 7. Indexes for stated queries. 8. Privacy risks in stored fields. 9. Likely update and delete behavior. Return a table of findings with severity, reason and suggested change. Separate required fixes from optional improvements. Provide revised DDL only for safe, clearly justified changes. Do not remove data or suggest destructive commands. Ask questions where the business rule is unclear.
Tip: Include the reports and write operations the schema must support, not only the table definitions.
Plan a safe, reversible migration for [SQL DIALECT AND VERSION]. Do not write executable destructive SQL until the plan is reviewed. Current schema: [PASTE CURRENT DDL] Target schema: [DESCRIBE THE REQUIRED CHANGE] Data volume and constraints: [APPROXIMATE ROW COUNTS, TRAFFIC, DOWNTIME LIMITS, KEYS AND INDEXES] Application impact: [APPLICATIONS, REPORTS OR SERVICES USING THESE TABLES] Create a staged plan covering: 1. Pre-checks and backups. 2. A dry-run or preview query. 3. Additive changes first. 4. Data backfill and batch strategy. 5. Validation checks before and after the change. 6. Application rollout order. 7. Monitoring signals. 8. Rollback conditions and steps. 9. Cleanup after confirmation. Flag any step that could lock a table, lose data or break old application code. Provide SQL only for non-destructive inspection and additive steps. State assumptions and ask questions before proposing ALTER, UPDATE or DELETE statements.
Tip: Give table sizes, traffic limits and rollback requirements so the plan fits your operating conditions.
Use this pack to write, explain, debug, optimize and review SQL. Each prompt works in ChatGPT, Claude or Gemini without API access or a live database connection.
Start with the schema
Start by replacing every bracketed placeholder. Include the SQL dialect and version, such as PostgreSQL 16, MySQL 8.0 or SQL Server 2022. Paste table definitions, keys, relationships and relevant indexes. Add a few synthetic rows when NULL values, duplicates or date rules matter.
Describe the business request in plain language. State the expected output grain, such as one row per customer or one row per month. Define terms such as active user, revenue, completed order or churned customer. Also give the date range and time zone.
Ask for assumptions first
Ask the model to list assumptions before writing SQL. This helps expose unclear terms and missing relationships. Tell it not to invent tables, columns or business rules. For changes to data, request a dry run, a transaction plan and rollback steps.
For performance work, provide approximate table sizes, indexes and an execution plan. A syntactically valid query can still return wrong results or run slowly. Review joins for duplicate rows, check NULL handling and confirm inclusive or exclusive date boundaries.
Use safe testing practices
Use SELECT-only settings while learning or exploring. Never paste passwords, API keys, private customer records or other secrets. Use a development database or a read-only account for testing. Review generated SQL before running it in any environment.
For dialect conversion, name both the source and target systems. Ask for a compatibility warning and a short list of changed functions. Common differences include date functions, string aggregation, identifier quoting, Boolean values and pagination syntax.
Improve analytics requests
For analytics, ask for validation queries and a small expected result. Cohort, retention and funnel queries need clear definitions and stable time periods. If the answer depends on an unclear definition, ask the model to stop and ask questions instead of guessing.
Google's Gemini prompting guidance recommends specific instructions, context and explicit output formats. Anthropic's prompt guidance supports separated inputs and clear sequential instructions. AWS text-to-SQL guidance also recommends schemas and question-to-SQL examples. These principles shape every prompt below.
Avoid common mistakes
Do not omit the SQL dialect, paste a vague business request or leave out the schema. Prevent invented columns, incorrect joins, unnecessary SELECT *, mixed dialect functions and unsafe data changes. Treat syntactically valid SQL as untested until you compare results against trusted data.
Frequently asked questions
How do I ask ChatGPT to write a SQL query?
Give it the SQL dialect, schema, relationships and plain-English goal. State the expected output columns, row grain, filters, date range and time zone. Ask it to list assumptions, avoid invented fields and provide validation checks before you run the query.
Can AI generate SQL from plain English?
Yes, but the result depends on your schema and definitions. Include table and column names, keys, joins and sample rows. Define terms such as revenue or active user. Ask for SQL that matches your database dialect and a check against expected results.
Why did the AI invent a table or column?
The request probably lacked enough schema detail, or the model guessed from common naming patterns. Tell it to use only supplied tables and columns. Ask it to list missing information instead of guessing, then provide the exact definitions it needs.
Is it safe to paste a database schema into an AI chat?
A schema can reveal business information even without customer rows. Remove credentials, secrets, personal data and sensitive names first. Check your employer's rules and the provider's current data controls. Use synthetic examples and a read-only workflow when possible.
How do I check an AI-generated SQL query?
Run it against a safe copy or read-only connection. Compare row counts and totals with a trusted report. Test NULLs, duplicates, empty results and date boundaries. Review every join and filter, and inspect the execution plan for slow queries.
More in Coding
Help keep every tool free
FreeToolr stays free because people help it grow. Share a tool you like, tell us what to build next, or support us on Ko-fi.