If you've ever stared at a 200-line SQL query at 2 AM, wondering which developer wrote it and why it runs slower than a snail on tranquilizers, you're not alone. Database work is often messy, undocumented, and painfully time-consuming. But what if you could delegate the grunt work to an AI assistant? Not just for writing simple SELECTs, but for untangling complex joins, optimizing indexes, and even generating documentation? This isn't a futuristic dream—it's a practical reality with the right prompts. In this article, I'll share 12 battle-tested prompts that I use in my daily workflow to turn SQL chaos into order. Each one comes with a real-world example, so you can copy, adapt, and start saving hours today.
1. The Query Translator: From Plain English to SQL
The Prompt:
Convert the following business question into a PostgreSQL SQL query. Use appropriate JOINs, GROUP BY, and window functions if needed. Return only the SQL code, no explanations.
Business question: [your question here]
Why it works: It forces the AI to think in terms of schema and relations, not just syntax. I've used this when business stakeholders ask for ad-hoc reports. For example, "Show me the monthly revenue per customer segment in 2025" becomes a clean query with proper date_trunc and case statements.
Example: For a typical e-commerce schema, this prompt might generate:
SELECT date_trunc('month', o.created_at) AS month,
c.segment,
SUM(o.total_amount) AS revenue
FROM orders o
JOIN customers c ON o.customer_id = c.id
WHERE o.created_at >= '2025-01-01' AND o.created_at < '2026-01-01'
GROUP BY 1, 2
ORDER BY 1, 2;
This alone saves me 15–20 minutes per request.
2. The Debugger: Finding the Missing Rows
The Prompt:
I have the following SQL query that returns fewer rows than expected. Analyze it for potential causes such as missing JOIN conditions, incorrect WHERE clauses, or NULL handling. Suggest fixes.
Query: [paste query]
Schema: [describe tables and columns]
Why it works: It gives the AI context to spot logical errors. Once, a query was missing rows because of an INNER JOIN where a LEFT JOIN was needed. The AI caught it and explained the impact.
Example: After running the prompt, it might respond:
"The issue is likely the INNER JOIN on orders—customers without orders are excluded. Use LEFT JOIN if you want all customers."
3. The Performance Tune-Up: Why Is My Query So Slow?
The Prompt:
I have a slow-running query in PostgreSQL. Explain its execution plan (I'll provide EXPLAIN ANALYZE output) and suggest concrete improvements: indexes, query rewrites, or configuration changes. Be specific.
EXPLAIN ANALYZE output: [paste output]
Why it works: This turns the AI into an indexing consultant. In one case, it identified a sequential scan on a large table and recommended a composite index, cutting query time from 2 seconds to 50 ms. Always verify with your own EXPLAIN, but it's a great starting point.
Example: The AI might suggest:
"Add a composite index on (customer_id, created_at) to support the WHERE and ORDER BY clauses."
4. The Schema Documenter: Generating Table Comments
The Prompt:
Generate PostgreSQL COMMENT ON statements for the following schema to document each table and column. Use plain English, and mention any constraints or relationships.
Schema: [paste CREATE TABLE statements]
Why it works: Documentation is often neglected. This prompt produces ready-to-run comments that make your database self-documenting. It's a game-changer for onboarding.
Example: For a users table, it might output:
COMMENT ON TABLE users IS 'Stores user profiles with authentication info';
COMMENT ON COLUMN users.email IS 'Unique email used for login';
5. The Rewriter: Optimizing for Readability
The Prompt:
Rewrite the following SQL query to make it more readable while preserving its logic. Use CTEs, proper indentation, and meaningful aliases. Return only the rewritten query.
Query: [paste query]
Why it works: Readable code is maintainable code. This prompt is perfect for refactoring legacy queries. I've converted monstrous subqueries into clean CTEs, making future edits a breeze.
Example: A query with multiple nested subqueries becomes a series of WITH clauses, each adding a step.
6. The Data Profiler: Understanding What's in Your Table
The Prompt:
Write a PostgreSQL script to profile the table [table_name]. For each column, output data type, count of non-null values, number of distinct values, and min/max for numeric and date columns. Also, identify columns that could serve as primary keys.
Why it works: Before joining or analyzing, you need to know your data. This script gives you a quick overview, helping you spot data quality issues early.
Example: It might output a summary like:
| column | non_null | distinct | min | max |
|---|---|---|---|---|
| id | 1000000 | 1000000 | 1 | 1000000 |
| created_at | 999000 | 900000 | 2020-01-01 | 2026-09-01 |
7. The Query Explainer: Simplifying Complex SQL
The Prompt:
Explain the following SQL query in plain English, step by step. Highlight any non-obvious logic or potential pitfalls.
Query: [paste query]
Why it works: When you inherit a query, this prompt helps you understand it quickly. It's like having a senior dev walk you through the code.
Example: For a query with window functions, it'll break down each PARTITION BY and ORDER BY.
8. The Test Data Generator: Creating Sample Rows
The Prompt:
Generate 10 INSERT statements for each table in the following schema, using realistic sample data. Ensure foreign key constraints are satisfied.
Schema: [paste schema]
Why it works: Testing often requires dummy data. This prompt produces consistent, constraint-aware inserts, saving you from manual data creation.
Example: For an e-commerce DB, it'll create customers, orders, and products with matching IDs.
9. The Migration Helper: Converting Between SQL Dialects
The Prompt:
Convert the following SQL query from MySQL to PostgreSQL syntax. Pay attention to limit/offset, string functions, and date functions. Return the converted query.
Query: [paste query]
Why it works: When moving between databases, this prompt handles syntax differences. I've used it to migrate scripts from MySQL to PostgreSQL without hours of manual fixes.
Example: MySQL's LIMIT 10 OFFSET 20 stays the same, but functions like DATE_FORMAT become TO_CHAR.
10. The Anomaly Detector: Finding Outliers in Data
The Prompt:
Write a SQL query to detect outliers in the [column] column of [table] using the interquartile range (IQR) method. Return rows where the value is below Q1 - 1.5*IQR or above Q3 + 1.5*IQR.
Why it works: Anomaly detection is critical for data quality. This prompt gives you a reusable script.
Example:
WITH stats AS (
SELECT percentile_cont(0.25) WITHIN GROUP (ORDER BY amount) AS q1,
percentile_cont(0.75) WITHIN GROUP (ORDER BY amount) AS q3
FROM transactions
)
SELECT * FROM transactions, stats
WHERE amount < q1 - 1.5*(q3-q1) OR amount > q3 + 1.5*(q3-q1);
11. The View Architect: Creating Reusable Views
The Prompt:
Create a SQL view that consolidates the following tables into a single 'sales_daily' view. Include date, product category, region, and total sales. Use joins and aggregations.
Tables: sales, products, regions
Why it works: Views simplify recurring queries. This prompt designs a view that analysts can query directly.
Example: The generated view becomes a go-to for daily sales reporting.
12. The Query Reviewer: Catching Anti-Patterns
The Prompt:
Review the following SQL query for common anti-patterns: SELECT *, missing indexes, implicit conversions, non-sargable WHERE clauses, and cartesian joins. Suggest improvements.
Query: [paste query]
Why it works: It acts as a second pair of eyes, catching issues you might miss. I've used it before merging code into production.
Example: It might flag WHERE YEAR(date) = 2025 and recommend WHERE date >= '2025-01-01' to use an index.
These 12 prompts are part of my daily toolkit. They've turned me from a spreadsheet wrangler into a database whisperer. Start with one, adapt it to your schema, and watch your efficiency soar. The hours you save can be spent on more important things—like actually enjoying your data.
Ready to tame your database? Try these prompts in your next session, and let me know which one saves you the most time.
Comments