From 6 Hours to 20 Minutes: SQL Prompts That Transformed a Bank Analyst's Reporting
Every Monday morning, data analysts across industries brace for the same ritual: extracting data, writing complex SQL queries, debugging errors, and formatting reports. For one bank analyst, this routine used to consume six hours of focused work. After discovering the power of well-crafted prompts for AI assistants, the same reporting now takes just twenty minutes. This isn't magic—it's the smart application of prompting techniques to SQL workflows.
In this guide, I'll share 12 battle-tested prompts that cover the entire SQL reporting lifecycle: from query generation and optimization to debugging and documentation. Each prompt is designed to be copy-paste ready, with explanations and examples so you can adapt them to your own databases and reporting needs.
The Anatomy of an Effective SQL Prompt
Before diving into the prompts, let's understand what makes them work. A good SQL prompt typically includes:
- Context: Database type (PostgreSQL, MySQL, SQL Server, etc.), schema details, and business logic.
- Task: Clearly defined output—whether it's a query, optimization, explanation, or documentation.
- Constraints: Performance limits, coding standards, or specific clauses to include.
- Format: Desired output structure (e.g., table, explanation, code block).
By providing these elements, you guide the AI to produce accurate, relevant results—turning a vague request into a precise tool.
12 SQL Prompts That Save Hours
Here are the prompts that worked wonders for our analyst, categorized by task. Each includes a description, a ready-to-use prompt, and a usage example.
1. Query Generation from Business Requirements
Task: Convert a business question into a SQL query.
Prompt:
You are an expert SQL developer. Write a SQL query for [database type] that answers the following business question: "[insert question]".
Here is the relevant schema:
[schema DDL or table descriptions]
Requirements:
- Use appropriate joins, aggregations, and window functions if needed.
- Add comments explaining each step.
- Optimize for readability and performance.
Return only the SQL code, no explanation.
Example: "What are the top 5 products by revenue in the last quarter?" with a schema including orders and products tables.
2. Query Optimization for Performance
Task: Rewrite a slow query to run faster.
Prompt:
Optimize the following SQL query for [database type]. It currently takes [X] seconds to run on a table with [N] rows.
[your query]
Provide:
1. An optimized version of the query.
2. A brief explanation of changes (e.g., indexing suggestions, rewrite of subqueries).
Focus on reducing execution time while preserving the result set.
Example: A query with multiple subqueries and OR conditions that can be rewritten with UNION ALL or window functions.
3. Debugging and Error Fixing
Task: Find and fix errors in a SQL query.
Prompt:
I'm getting the following error when running this query on [database type]:
[error message]
Query:
[your query]
Explain the cause and provide a corrected version of the query.
Example: ERROR: column "total" does not exist due to a missing alias.
4. Explaining Complex Queries
Task: Understand what a complex query does.
Prompt:
Explain the following SQL query in simple terms for a non-technical stakeholder.
[your query]
Break it down step by step, describing what each part does and the final output. Use analogies if helpful.
Example: A query with CTEs, window functions, and multiple joins.
5. Generating Schema Documentation
Task: Create documentation for database tables.
Prompt:
Generate a markdown table for each table in the following schema, listing column names, data types, constraints, and a brief description of each column.
Schema:
[schema DDL]
Format:
| Table | Column | Type | Constraints | Description |
Example: Documenting a customers table with columns like id, email, created_at.
6. Writing Test Cases for Queries
Task: Create test data and queries to verify correctness.
Prompt:
Write SQL test cases for the following query. Include:
- Sample input data (as INSERT statements).
- Expected output.
- Edge cases (e.g., null values, empty tables).
Query:
[your query]
Example: Testing a query that calculates average order value.
7. Converting Between SQL Dialects
Task: Translate a query from one database dialect to another.
Prompt:
Convert this SQL query from [source dialect] to [target dialect].
[your query]
Note any syntax differences (e.g., string concatenation, date functions, limit syntax).
Example: Converting MySQL's LIMIT to SQL Server's TOP.
8. Generating Reports with Aggregations
Task: Create a query that outputs a summary report.
Prompt:
Write a SQL query for [database type] that generates a report with the following columns:
- [column 1]
- [column 2]
- ...
Include aggregations (e.g., SUM, AVG) and group by appropriate fields. Use date filtering for the last [time period].
Schema:
[schema]
Example: A monthly sales report by product category.
9. Creating Recursive Queries
Task: Write a recursive CTE for hierarchical data (e.g., org charts, category trees).
Prompt:
Write a recursive CTE in [database type] to traverse the following table and return all descendants of a given node.
Table structure: [table name] (id, parent_id, name)
Return the full tree starting from node with id = [value]. Include a depth column.
Example: An employee hierarchy.
10. Data Cleaning and Transformation
Task: Write queries to handle messy data.
Prompt:
Given a table [table name] with columns [list], write SQL queries to:
- Remove duplicates based on [column(s)].
- Normalize date formats.
- Split a column into multiple columns.
- Fill missing values with defaults.
Provide the queries with explanations.
Example: Cleaning a users table with inconsistent date strings.
11. Automating Report Generation with Stored Procedures
Task: Create a stored procedure that generates a report.
Prompt:
Write a stored procedure in [database type] that generates a report named [report name]. The procedure should:
- Accept parameters like [start_date], [end_date].
- Insert results into a table [output_table].
- Use proper error handling.
Include the full procedure code.
Example: A daily sales summary procedure.
12. Learning and Best Practices
Task: Get advice on SQL best practices.
Prompt:
As a SQL expert, list the top 10 best practices for writing efficient and maintainable SQL queries. For each practice, provide a brief explanation and a code example.
Example: Indexing, avoiding SELECT *, using UNION ALL instead of OR, etc.
Real-World Impact: A Case Study
To illustrate the potential, let's look at how our bank analyst used these prompts. They had a weekly report that required:
- Extracting transactions from a core banking system.
- Joining with customer and product tables.
- Calculating metrics like balance, interest, and risk scores.
- Formatting the output for management.
Previously, they wrote queries from scratch, debugged errors, and manually checked data quality—taking six hours. By using the query generation prompt (1), they got a working query in minutes. The optimization prompt (2) reduced runtime from 15 minutes to 2 minutes. Debugging (3) helped fix edge cases. Finally, the report generation prompt (8) produced a clean output. The entire process now takes 20 minutes.
Conclusion
SQL prompts are not just about writing queries faster—they're about working smarter. By leveraging AI to handle routine tasks, you free up time for deeper analysis and decision-making. The prompts above are a starting point; adapt them to your specific schemas and business logic. Start with one prompt, experiment, and soon you'll wonder how you ever survived without them.
Ready to transform your workflow? Copy a prompt, try it on a sample question, and see the difference. Your future self—and your weekends—will thank you.
Comments