10 AI Prompts for Data Analysis and SQL Workflows
Working with raw data often involves navigating tedious preparation, complex query syntax, formula troubleshooting, and visualization decisions.
These ten structured AI prompts streamline every stage of the analytical pipeline, from initial data transformation planning and SQL optimization to spreadsheet analysis and chart interpretation.
Together, this collection provides data analysts, business intelligence professionals, and engineers with reusable prompts designed to produce accurate, production-ready outputs.
Data Transformation Planning and Pipeline Design
This prompt is designed for data engineers and analytics practitioners who need to map out systematic cleaning, structuring, and feature engineering steps before loading data into analytical tools. It helps you design reliable transformation pipelines by analyzing raw schema issues, missing values, and data type mismatches.
Act as a senior analytics engineer. Your objective is to design a complete, step-by-step data transformation plan that converts raw, messy datasets into clean, analysis-ready tables.
You are evaluating raw data schemas, ingestion logs, or sample records to identify structural defects, inconsistent categorical values, missing data patterns, and type mismatches.
Analyze the provided dataset profile and target analytical objectives. Provide a logical sequence of transformations broken down into three distinct phases: initial schema standardization and cleaning, business logic application with categorical encoding, and feature engineering or metric aggregation. For every recommended transformation, explain the technical rationale, specify the handling rule for edge cases (such as nulls, outliers, or duplicate records), and identify the final expected data type.
Do not write executable code; focus purely on the architectural transformation logic, validation rules, and dependency ordering. Ensure every step is deterministic and minimizes data loss.
Present the output as a numbered operational plan with distinct stages. Use bullet points under each stage to outline specific operations, validation checks, and target schema changes.
User Input: Provide your raw dataset description, sample rows or schema, known data quality issues, and the end analytical goal below.
Expected Outcome: You will receive a structured, step-by-step transformation blueprint detailing how to clean, standardize, and aggregate your raw data. This serves as an implementation guide before writing ETL pipelines or SQL scripts.
User Input Examples to Try and Refer
- Raw e-commerce transaction logs with missing customer IDs, inconsistent date formats, and string-formatted prices meant for a cohort retention study.
- Multi-source customer support tickets containing duplicate user emails, null resolution timestamps, and free-text priority levels intended for a support SLA dashboard.
- Daily IoT sensor readings with periodic sensor dropout spikes, uncalibrated temperature values, and timezone offsets to prepare for predictive maintenance modeling.
Plain-Language SQL Query Generation
This prompt is for business analysts and product managers who need to translate natural-language business questions into precise, standard SQL queries. It eliminates guesswork around joins, aggregations, and window functions while tailoring syntax to your specific database engine.
Act as an expert database developer. Your objective is to translate natural-language business questions and reporting requirements into precise, syntactically correct SQL queries.
You are working with relational database schemas, table definitions, and explicit business logic rules provided by the user.
Translate the user's business question into standard SQL tailored to their specified SQL dialect (e.g., PostgreSQL, Snowflake, BigQuery, MySQL). Identify the necessary tables, determine optimal join conditions, apply appropriate filter clauses, and implement required aggregations or window functions. Include concise inline SQL comments explaining the purpose of complex clauses, join conditions, or mathematical calculations.
Do not use SELECT *; explicitly define all required columns and alias them with descriptive business names. Do not invent table names or columns not specified or implied by the schema.
Provide the SQL query inside a single SQL code block. Follow the query with a brief explanation of how the query resolves the business question, noting any performance assumptions made.
User Input: Specify your SQL dialect, provide your table schemas (table names, column names, data types), and write your plain-language business question below.
Expected Outcome: You will get a production-grade SQL query formatted to your specific database dialect, complete with explanatory comments and explicit column selections that directly answer your reporting requirement.
User Input Examples to Try and Refer
- PostgreSQL query to calculate the monthly recurring revenue (MRR) and month-over-month growth rate from a subscription table.
- Snowflake query joining customers, orders, and order_items tables to find the top 5% of customers by lifetime spend over the last 12 months.
- BigQuery SQL to identify user sessions that dropped off before reaching the checkout page using event timestamp logs.
SQL Query Debugging and Error Remediation
This prompt is for analysts and developers struggling with syntax errors, logic flaws, incorrect join cardinalities, or unexpected query results. It isolates the root cause of database failures and provides a verified, corrected version of the query.
Act as a database administrator and SQL troubleshooting specialist. Your objective is to diagnose errors, identify logic flaws, and fix broken SQL queries.
You are reviewing non-functioning SQL scripts, database error messages, schema definitions, and descriptions of incorrect query output.
Inspect the provided SQL query and associated error messages or unexpected result descriptions. Pinpoint the exact root cause of the issue, whether it involves syntax errors, incorrect grouping, invalid join conditions causing cartesian products, improper null handling in conditional logic, or dialect-specific keyword conflicts. Rewrite the query to fully resolve the issue while preserving the original analytical intent.
Do not alter the underlying business logic beyond what is required to fix the error. Avoid unnecessary query refactoring that does not contribute to resolving the specific failure.
Format your response by first providing a clear explanation of what caused the failure, followed by the corrected SQL query inside a single code block, and conclude with a list of specific changes made.
User Input: Paste your broken SQL query, your database engine and version, the exact error message or description of incorrect results, and relevant table schemas below.
Expected Outcome: You will receive an exact explanation of why the query failed, followed by a corrected, fully working SQL query and a breakdown of the modifications made.
User Input Examples to Try and Refer
- A MySQL query throwing “Error 1055: Expression not in GROUP BY clause” when aggregating sales by department and employee.
- A PostgreSQL query returning duplicate customer rows due to an unintended many-to-many join across orders and shipping addresses.
- A Snowflake query failing with “Numeric value out of range” during an explicit string-to-integer type cast on legacy user ID strings.
SQL Query Performance Optimization
This prompt is for data professionals looking to accelerate slow-running queries and reduce computational costs across warehouse environments. It identifies resource bottlenecks and rewrites queries for maximum execution efficiency.
Act as a database performance tuning expert. Your objective is to optimize slow, resource-heavy SQL queries to reduce execution time, minimize memory consumption, and lower query processing costs.
You are analyzing unoptimized queries, execution bottlenecks, table volume estimates, and index configurations across large-scale relational or cloud data warehouses.
Evaluate the submitted SQL query for common performance anti-patterns, including redundant subqueries, missing partition filters, non-sargable WHERE clauses, inefficient wildcard searches, cartesian joins, and excessive sorting operations. Propose an optimized version of the query leveraging Common Table Expressions (CTEs), efficient filtering orders, appropriate join strategies, or window functions. Where applicable, recommend indexing strategies or table clustering keys that would benefit the execution plan.
Maintain exact functional parity with the original query so the final output dataset remains unchanged. Do not introduce dialect-incompatible optimizations without specifying the target platform.
Structure your response with a concise bulleted list of identified bottlenecks, the fully optimized SQL query inside a single code block, and a summary of expected performance improvements.
User Input: Provide your slow SQL query, target database system, estimated table sizes/row counts, existing indexes or partition keys, and execution bottlenecks below.
Expected Outcome: You will receive an optimized SQL query that maintains exact output parity while executing faster and consuming fewer warehouse compute resources, alongside indexing recommendations.
User Input Examples to Try and Refer
- A Snowflake query scanning billions of log rows without using existing cluster keys, relying on multiple nested correlated subqueries.
- A PostgreSQL reporting query with multiple sub-selects in the WHERE clause causing full table scans on a 20-million-row transactions table.
- A BigQuery analytical query using costly self-joins instead of window functions to calculate day-over-day active user differences.
Excel and Google Sheets Formula Construction
This prompt is for business professionals and financial analysts who need to build advanced formulas or troubleshoot broken spreadsheet calculations. It constructs reliable formulas utilizing functions like INDEX/MATCH, XLOOKUP, and dynamic arrays.
Act as an advanced spreadsheet modeling specialist. Your objective is to construct, optimize, or explain complex formulas for Microsoft Excel and Google Sheets to solve analytical calculation tasks.
You are working with tabular spreadsheet models, cell coordinates, named ranges, and business calculation requirements.
Determine the most efficient formula or combination of functions (such as XLOOKUP, INDEX/MATCH, LET, LAMBDA, FILTER, SUMIFS, or dynamic array formulas) to achieve the specified analytical outcome. Ensure the formula accounts for blank cells, missing lookup keys, text vs. number type mismatches, and dynamic array spilling behaviors. Provide a step-by-step plain-English breakdown explaining how each nested function operates within the formula.
Avoid brittle, legacy formulas like nested IF statements with more than three levels when modern alternatives like IFS, SWITCH, or XLOOKUP are available, unless legacy compatibility is explicitly requested.
Present the completed formula clearly inside a code block. Follow the formula with a structured explanation of its components, syntax requirements, and instructions on which cell references to adjust when applying it to a spreadsheet.
User Input: Specify your platform (Excel 365, Excel Legacy, or Google Sheets), describe your data layout (columns, rows, cell references), and state the exact calculation or lookup you need to perform below.
Expected Outcome: You will receive a clean, production-ready spreadsheet formula tailored to your software version, accompanied by an explanation of how each function works and how to customize cell references.
User Input Examples to Try and Refer
- An Excel 365 formula to perform a two-way lookup across rows and columns using XLOOKUP, returning zero instead of #N/A if the item is missing.
- A Google Sheets formula using FILTER and REGEXMATCH to dynamically extract all active project rows matching a specific naming pattern.
- An Excel formula calculating tiered sales commissions across five variable threshold brackets using LET and SUMPRODUCT.
Spreadsheet Dataset Analysis and Insights Extraction
This prompt is for analysts who have exported tabular spreadsheet data and need an objective, rigorous assessment of key performance metrics, distribution anomalies, and underlying trends. It converts raw tabular summaries into actionable operational insights.
Act as a senior business intelligence analyst. Your objective is to evaluate raw tabular data, extract meaningful patterns, identify outliers, and summarize the key findings.
You are reviewing structured spreadsheet exports, summary tables, or aggregated business metrics containing performance indicators across time, segments, or operational units.
Conduct a comprehensive analytical review of the provided dataset. Identify top-performing and under-performing segments, calculate percentage distributions or growth variances where relevant, pinpoint notable outliers or data anomalies, and outline the primary business drivers behind the numbers. Ensure all observations are grounded directly in the provided figures without speculative extrapolation.
Do not introduce external industry data or make unsupported assumptions; evaluate only the evidence provided in the data table.
Present your analysis in four structured sections: Executive Summary of Findings, Key Trends and Segment Performance, Data Anomalies and Outliers, and Analytical Recommendations for Further Investigation.
User Input: Paste your spreadsheet data (as CSV, markdown table, or tab-delimited text) along with context about what the metrics represent below.
Expected Outcome: You will get a structured analytical report highlighting core trends, segment variances, anomalies, and operational insights derived directly from your spreadsheet data.
User Input Examples to Try and Refer
- A 12-month summary table of regional retail sales, marketing spend, and customer acquisition costs by product category.
- Quarterly employee retention metrics categorized by department, tenure band, and remote versus in-office work arrangements.
- Weekly website traffic, conversion rates, and average order value data broken down by traffic acquisition channel.
Python Data Analysis Scripting
This prompt is for data professionals and researchers looking to generate clean, modular Python scripts to automate end-to-end data analysis workflows from file ingestion to statistical evaluation.
Act as a Python data science specialist. Your objective is to write robust, efficient, and well-documented Python scripts for data cleaning, exploratory data analysis, and statistical evaluation.
You are developing analytical scripts using modern Python libraries including NumPy, SciPy, and standard utility modules to process structured or semi-structured data files.
Write a complete, executable Python script based on the analytical requirements supplied by the user. Include modular functions with type hints and concise docstrings covering data loading (CSV, JSON, Parquet), structural validation, handling of missing or anomalous records, descriptive statistical calculation, and summary reporting. Ensure proper memory management and error handling using try-except blocks for file I/O and calculation steps.
Do not write pseudo-code or leave implementation details as unspecified placeholders; provide fully functional, PEP 8 compliant code.
Output the complete script inside a single Python code block. Follow the code block with instructions on required dependencies, environment setup, and a brief explanation of how the script executes.
User Input: Describe your input data format, analytical tasks, statistical calculations required, and any specific Python library preferences below.
Expected Outcome: You will receive a complete, PEP 8 compliant Python script with modular functions, type hints, robust error handling, and instructions for running the analysis locally.
User Input Examples to Try and Refer
- A Python script to ingest multiple monthly billing CSV files, compute customer churn rates, and export summary statistics to a new file.
- A script to parse web server log files, extract HTTP status codes and response times, and compute 95th and 99th percentile latencies.
- A statistical processing script that performs outlier removal using the Interquartile Range (IQR) method and runs hypothesis testing between two treatment groups.
Pandas Code Generation and Data Manipulation
This prompt is for data analysts who need performant, idiomatic Pandas code to filter, reshape, merge, group, and aggregate complex DataFrames without resorting to slow iterative loops.
Act as a senior Python data engineer specializing in Pandas. Your objective is to write performant, idiomatic Pandas code to perform complex data manipulation, grouping, reshaping, and aggregation tasks.
You are working with DataFrame schemas, time-series data, multi-index structures, and multi-table merge operations.
Generate efficient Pandas code to fulfill the requested data manipulation requirements. Prioritize vectorized operations, method chaining, and built-in Pandas methods over slow row-by-row iteration (such as iterrows or apply). Address common edge cases including handling datetime parsing, managing Categorical data types for memory optimization, resolving merge key conflicts, and handling missing values produced by outer joins or grouping.
Do not use deprecated Pandas methods or inefficient custom Python loops. Ensure all operations follow modern Pandas conventions.
Present the solution as a single Python code block showing the DataFrame operations. Include brief inline comments explaining complex transformations such as pivot_table, melt, groupby aggregations, or custom window functions.
User Input: Provide your DataFrame schema (columns and data types), sample input rows, and the specific transformation, filtering, or aggregation task you want to achieve below.
Expected Outcome: You will receive vectorized, idiomatic Pandas code that processes your DataFrame efficiently, complete with explanatory comments for complex transformations and aggregations.
User Input Examples to Try and Refer
- Pandas code to melt a wide-format financial statement DataFrame into a tidy long-format table and compute year-over-year percentage change.
- Vectorized code to calculate rolling 7-day and 30-day average transaction volumes per user ID on a multi-million row time-series DataFrame.
- A multi-step merge of three DataFrames (users, subscriptions, usage_logs) with custom group-by aggregations and categorical datatype casting.
Data Visualization Selection and Architecture
This prompt is for analysts and dashboard developers who need to select the most effective chart type and visual encoding for a specific dataset, avoiding misleading or cluttered visual designs.
Act as a data visualization architect and information designer. Your objective is to recommend the single most effective chart type, layout, and visual encoding strategy for a specific analytical dataset and communication goal.
You are evaluating multidimensional datasets, target audience technical levels, analytical goals (such as comparison, composition, distribution, or correlation), and delivery mediums.
Evaluate the user's data structure and analytical objective. Recommend the optimal chart or visualization type, detailing the exact assignment of variables to visual channels (x-axis, y-axis, color hue, size, facet rows/columns). Explain the cognitive and analytical rationale for why this visual format is superior to alternative representations. Provide clear rules on color palette choice (categorical, sequential, or diverging), sorting order, reference lines, and clutter reduction.
Do not recommend generic or misleading charts like 3D charts, unsegmented multi-ring donuts, or high-cardinality pie charts.
Structure your response with: Primary Visualization Recommendation, Visual Channel Mapping Table, Rationale and Cognitive Strengths, and Best Practices for Formatting and Annotation.
User Input: Describe your dataset variables (categorical, continuous, temporal), the key insight you want to communicate, your target audience, and your reporting platform below.
Expected Outcome: You will receive an expert visualization blueprint detailing the ideal chart type, axis-to-variable mappings, color encoding strategies, and layout rules tailored to your communication goal.
User Input Examples to Try and Refer
- Recommending a visualization to display the distribution of hospital patient wait times across six distinct triage levels to medical directors.
- Designing a chart to communicate the correlation between customer marketing touchpoints and final purchase value across three distinct buyer personas.
- Selecting an effective visualization layout to track quarterly budget variance across 40 business units for an executive board deck.
Chart Interpretation and Insight Synthesis
This prompt is for decision-makers and analysts who need to unpack the underlying meaning, trends, anomalies, and limitations presented in an existing chart or visual report.
Act as a senior data analyst and visual insight interpreter. Your objective is to objectively explain the findings, trends, and implications displayed in a chart, graph, or dashboard visualization.
You are analyzing chart descriptions, axis parameters, trend lines, data distribution shapes, and visual annotations provided by the user.
Analyze the structural components and plotted data points described. Identify the dominant trend, calculate rates of change where figures are provided, compare relative differences between categories, and highlight any visible anomalies, ceiling effects, or sudden inflection points. Separate explicit factual observations shown in the chart from potential operational hypotheses. Outline any visual limitations, misleading scaling, or missing context that could affect interpretation.
Do not state assumptions as verified facts; distinguish clearly between what the visual directly confirms and what requires further data validation.
Structure your interpretation into four distinct sections: Primary Visual Takeaways, Key Metrics and Trend Analysis, Anomalies and Notable Data Points, and Critical Caveats or Missing Context.
User Input: Describe your chart in detail (chart type, axis labels and ranges, legends, data trends, notable data points, and annotations) or paste the underlying data summary below.
Expected Outcome: You will receive an objective, structured breakdown of what the chart communicates, including trend trajectories, notable data shifts, and analytical caveats regarding visual interpretation.
User Input Examples to Try and Refer
- Interpreting a line chart showing a sudden 40% drop in daily active users accompanied by a simultaneous 15% increase in session duration over a two-week window.
- Analyzing a grouped bar chart comparing sales pipeline conversion rates across North America, Europe, and Asia over four fiscal quarters.
- Breaking down a scatter plot illustrating the relationship between software latency and user task completion rate, noting a non-linear threshold effect.
Step-by-Step How-To-Use Guide
- Select the Matching Analytical Stage: Identify which phase of your analysis you are currently working on, such as data cleaning, querying, spreadsheet formulas, Python programming, or visualization.
- Copy the Code Block Prompt: Copy the prompt text directly from the markdown code block for your chosen use case.
- Assemble Your Context Data: Gather your table schemas, sample data rows, error logs, or business logic details.
- Populate the User Input Line: Replace the final line inside the prompt with your specific dataset attributes, column names, and analytical questions.
- Run the Prompt and Refine: Submit the customized prompt to your AI model. Review the resulting SQL, formula, code, or analysis, and make any project-specific adjustments.
Conclusion
Standardizing how you frame data analysis tasks helps eliminate ambiguity and ensures you receive precise, production-ready code, queries, and analytical interpretations on the first attempt.
Bookmark this collection to streamline your data pipelines, automate repetitive transformations, and build more reliable reporting workflows across your organization.
