Data Analysis Workflows
Complete workflows for common data analysis tasks. Covers the full process from understanding requirements to delivering validated results.
Workflow 1: Answer Data Questions
Answer a data question, from a quick lookup to a full analysis to a formal report.
1. Understand the Question
Parse the user's question and determine:
- Complexity level:
- Quick answer: Single metric, simple filter, factual lookup (e.g., "How many users signed up last week?")
- Full analysis: Multi-dimensional exploration, trend analysis, comparison (e.g., "What's driving the drop in conversion rate?")
- Formal report: Comprehensive investigation with methodology, caveats, and recommendations (e.g., "Prepare a quarterly business review of our subscription metrics")
- Data requirements: Which tables, metrics, dimensions, and time ranges are needed
- Output format: Number, table, chart, narrative, or combination
2. Gather Data
Options for data access:
- Ask the user to provide data:
- Paste query results directly
- Upload a CSV or Excel file
- Describe the schema so you can write queries for them to run
- If writing queries for manual execution, use the `sql-queries` skill for dialect-specific best practices
- Once data is provided, proceed with analysis
3. Analyze
- Calculate relevant metrics, aggregations, and comparisons
- Identify patterns, trends, outliers, and anomalies
- Compare across dimensions (time periods, segments, categories)
- For complex analyses, break the problem into sub-questions and address each
4. Validate Before Presenting
Before sharing results, run through validation checks:
- Row count sanity: Does the number of records make sense?
- Null check: Are there unexpected nulls that could skew results?
- Magnitude check: Are the numbers in a reasonable range?
- Trend continuity: Do time series have unexpected gaps?
- Aggregation logic: Do subtotals sum to totals correctly?
If any check raises concerns, investigate and note caveats.
5. Present Findings
For quick answers:
- State the answer directly with relevant context
- Include the query used (collapsed or in a code block) for reproducibility
For full analyses:
- Lead with the key finding or insight
- Support with data tables and/or visualizations
- Note methodology and any caveats
- Suggest follow-up questions
For formal reports:
- Executive summary with key findings
- Methodology section explaining approach and data sources
- Detailed findings with supporting evidence
- Caveats and limitations
- Recommendations and next steps
- Appendix with full queries and data tables
Workflow 2: Explore and Profile Datasets
Generate a comprehensive data profile for a table or uploaded file. Understand its shape, quality, and patterns before diving into analysis.
1. Access the Data
If a file is provided (CSV, Excel, Parquet, JSON):
- Read the file and load into a working dataset
- If the file is large, sample it for profiling
If user describes a table:
- Ask for sample data or schema information
- Generate profiling queries for the user to run
2. Profile the Dataset
Generate a report covering:
Basic Statistics
- Row count: Total number of records
- Column count: Number of fields
- Primary key: Identify unique identifier(s)
- Grain: One row per what? (user, order, event, etc.)
- Time range: For temporal data, first and last dates
Column-Level Analysis
For each column, report:
- Type: String, integer, float, date, boolean, etc.
- Null rate: Percentage of missing values
- Cardinality: Number of unique values
- Sample values: Examples of what the column contains
- Distribution: For numeric columns, min/max/mean/median/std dev
Data Quality Flags
Automatically identify potential issues:
- High null rates (>10%)
- Unexpected values (e.g., negative values in a count field)
- Duplicate rows
- Inconsistent formatting (mixed case, trailing spaces)
- Time gaps in temporal data
3. Recommend Next Steps
Based on profiling results, suggest:
- High-value dimensions to explore (columns with moderate cardinality, low nulls)
- Data quality issues to address before analysis
- Potential relationships to investigate (correlated columns, hierarchies)
- Analysis starting points based on the data's structure
Workflow 3: Write Optimized SQL
Write a SQL query from a natural language description, optimized for your specific SQL dialect and following best practices.
1. Understand the Request
Parse the user's description to identify:
- Output columns: What fields should the result include?
- Filters: What conditions limit the data (time ranges, segments, statuses)?
- Aggregations: Are there GROUP BY operations, counts, sums, averages?
- Joins: Does this require combining multiple tables?
- Ordering: How should results be sorted?
- Limits: Is there a top-N or sample requirement?
2. Determine SQL Dialect
Ask the user which database they're using if not specified:
- PostgreSQL / Aurora / Supabase
- Snowflake
- BigQuery
- Databricks / Spark SQL
- Redshift
- MySQL / MariaDB
Each dialect has syntax differences for date functions, string operations, and window functions.
3. Write the Query
Use CTEs (Common Table Expressions) for complex queries:
```sql
WITH base_data AS (
-- First CTE: Get the base dataset
SELECT ...
),
aggregated AS (
-- Second CTE: Perform aggregations
SELECT ...
)
-- Final SELECT from CTEs
SELECT * FROM aggregated;
```
Best practices:
- Use explicit JOIN syntax (not implicit joins in WHERE clause)
- Qualify all column names with table aliases when joining
- Use meaningful CTE and alias names
- Add comments explaining complex logic
- Format for readability (indent, line breaks)
- Consider performance (filter early, avoid SELECT *, use appropriate indexes)
4. Add Context
Include with the query:
- Purpose: One-line description of what the query does
- Tables used: Which tables are referenced
- Performance notes: Expected row counts, potential bottlenecks
- Dialect-specific notes: Any syntax specific to the database being used
Workflow 4: Create Visualizations
Create publication-quality data visualizations using Python. Generates charts from data with best practices for clarity, accuracy, and design.
1. Understand the Request
Determine:
- Data source: Query results, pasted data, CSV/Excel file, or data to be queried
- Chart type: Explicitly requested or needs to be recommended
- Purpose: Exploration, presentation, report, dashboard component
- Audience: Technical team, executives, external stakeholders
2. Get the Data
If data is not yet provided:
- Ask the user to paste data or upload a file
- If querying is needed, use the SQL workflow to generate the query first
3. Choose the Right Chart Type
Select visualization based on what you're showing:
| What You're Showing |
Best Chart |
When to Use |
| Trend over time |
Line chart |
Continuous time series, shows change |
| Comparison across categories |
Bar chart |
Comparing discrete categories |
| Part-to-whole |
Stacked bar / Pie |
Composition, relative sizes |
| Distribution |
Histogram / Box plot |
Understanding spread and outliers |
| Correlation |
Scatter plot |
Relationship between two variables |
| Ranking |
Horizontal bar |
Ordered list, easy to read labels |
4. Generate Python Code
Use `plotly` for interactive charts, `seaborn` or `matplotlib` for static charts.
Chart template pattern:
```python
import matplotlib.pyplot as plt
import pandas as pd
Load data
df = pd.DataFrame({...})
Create figure
fig, ax = plt.subplots(figsize=(10, 6))
Plot
ax.plot(df['x'], df['y']) # or .bar(), .scatter(), etc.
Style
ax.set_title('Clear, Descriptive Title', fontsize=14, fontweight='bold')
ax.set_xlabel('X Axis Label')
ax.set_ylabel('Y Axis Label')
ax.grid(axis='y', alpha=0.3)
Show
plt.tight_layout()
plt.show()
```
5. Apply Design Principles
- Clarity: Remove chart junk, use clear labels
- Accuracy: Don't truncate axes to exaggerate differences
- Accessibility: Use colorblind-friendly palettes
- Context: Add reference lines, annotations for key points
Workflow 5: Build Interactive Dashboards
Build a self-contained interactive HTML dashboard with charts, filters, tables, and professional styling. Opens directly in a browser -- no server or dependencies required.
1. Understand Dashboard Requirements
Determine:
- Purpose: Executive overview, operational monitoring, deep-dive analysis, team reporting
- Audience: Who will use this dashboard?
- Key metrics: What numbers matter most?
- Dimensions: What should users be able to filter or slice by?
- Data source: Live query, pasted data, CSV file, or sample data
2. Gather the Data
If data needs to be queried, use the SQL workflow.
If data is provided, ensure it's in a structured format (CSV or JSON).
3. Design Dashboard Layout
Organize into sections:
- Header: Title, date range, key filters
- KPI cards: 3-5 big numbers that matter most
- Primary charts: 2-3 main visualizations (trends, comparisons)
- Details section: Tables or secondary charts for drill-down
- Footer: Methodology notes, data source, last updated
4. Generate HTML/JS Code
Use this template structure:
```html
// Charts
// Filters
// Interactivity
</script>
5. Add Interactivity
Implement:
- Dropdown filters: Filter by category, time range, segment
- Chart interactions: Hover tooltips, click to drill-down
- Table sorting: Click column headers to sort
- Dynamic updates: Filters update all charts simultaneously
Workflow 6: Validate Analysis Before Sharing
Review an analysis for accuracy, methodology, and potential biases before sharing with stakeholders. Generates a confidence assessment and improvement suggestions.
1. Review Methodology and Assumptions
Examine:
Data selection:
- Which tables/sources were used? Are they the right ones?
- What time range? Is it recent enough?
- Any filters applied? Do they introduce bias?
Aggregation logic:
- Are groupings appropriate for the question?
- Do subtotals match totals?
- Are nulls handled correctly (excluded vs. counted as zero)?
Statistical methods:
- If using averages, is median more appropriate?
- If comparing percentages, are denominators consistent?
- If showing trends, is seasonality accounted for?
2. Check for Common Pitfalls
Survivorship bias:
- Example: Analyzing only current customers excludes churned users
- Check: Does the analysis need to include historical records?
Selection bias:
- Example: Survey responses from only power users
- Check: Is the sample representative of the population?
Simpson's paradox:
- Example: Overall trend contradicts subgroup trends when aggregated
- Check: Break down by segments before concluding
Correlation vs. causation:
- Example: Ice cream sales correlate with drowning deaths (both caused by summer)
- Check: Are confounding variables at play?
3. Sanity Check Results
Compare results to expectations:
- Magnitude: Are numbers in the right ballpark?
- Direction: Do trends match known business context?
- Consistency: Do related metrics tell the same story?
If something looks off:
- Recheck the query
- Look for data quality issues
- Consider if external factors could explain it
4. Assess Confidence Level
Rate confidence as:
- High confidence: Methodology sound, results validated, limitations documented
- Medium confidence: Minor concerns or caveats, but core findings are solid
- Needs more work: Methodological issues or data quality problems need addressing
5. Document Limitations
Every analysis has limits. Document:
- What's excluded from the data
- Assumptions made
- Margin of error or uncertainty
- Known data quality issues
- Alternative interpretations
Example caveat:
"This analysis excludes trial users, which may overstate conversion rate by ~5pp compared to total signups."
When to Use Each Workflow
- Answer Data Questions: User has a specific question to answer
- Explore Datasets: Encountering a new table or dataset
- Write SQL: Need to generate queries for manual execution
- Create Visualizations: Need charts for reports or presentations
- Build Dashboards: Need interactive, shareable dashboards
- Validate Analysis: Before sharing important findings with stakeholders
Use these workflows in combination for complex projects. For example:
- Explore data → 2. Write SQL → 3. Create visualization → 4. Validate → 5. Share
1---2name: data-analysis-workflows3description: Comprehensive data analysis workflows including answering data questions, exploring datasets, writing SQL queries, creating visualizations, building dashboards, and validating analyses. Use when conducting data analysis tasks, from quick lookups to comprehensive reports.4---5
6# Data Analysis Workflows
7
8Complete workflows for common data analysis tasks. Covers the full process from understanding requirements to delivering validated results.
9
10## Workflow 1: Answer Data Questions
11
12Answer a data question, from a quick lookup to a full analysis to a formal report.
13
14### 1. Understand the Question
15
16Parse the user's question and determine:
17
18- **Complexity level**:
19 - **Quick answer**: Single metric, simple filter, factual lookup (e.g., "How many users signed up last week?")
20 - **Full analysis**: Multi-dimensional exploration, trend analysis, comparison (e.g., "What's driving the drop in conversion rate?")
21 - **Formal report**: Comprehensive investigation with methodology, caveats, and recommendations (e.g., "Prepare a quarterly business review of our subscription metrics")
22- **Data requirements**: Which tables, metrics, dimensions, and time ranges are needed
23- **Output format**: Number, table, chart, narrative, or combination
24
25### 2. Gather Data
26
27**Options for data access:**
28
291. Ask the user to provide data:
30 - Paste query results directly
31 - Upload a CSV or Excel file
32 - Describe the schema so you can write queries for them to run
332. If writing queries for manual execution, use the \`sql-queries\` skill for dialect-specific best practices
343. Once data is provided, proceed with analysis
35
36### 3. Analyze
37
38- Calculate relevant metrics, aggregations, and comparisons
39- Identify patterns, trends, outliers, and anomalies
40- Compare across dimensions (time periods, segments, categories)
41- For complex analyses, break the problem into sub-questions and address each
42
43### 4. Validate Before Presenting
44
45Before sharing results, run through validation checks:
46
47- **Row count sanity**: Does the number of records make sense?
48- **Null check**: Are there unexpected nulls that could skew results?
49- **Magnitude check**: Are the numbers in a reasonable range?
50- **Trend continuity**: Do time series have unexpected gaps?
51- **Aggregation logic**: Do subtotals sum to totals correctly?
52
53If any check raises concerns, investigate and note caveats.
54
55### 5. Present Findings
56
57**For quick answers:**
58- State the answer directly with relevant context
59- Include the query used (collapsed or in a code block) for reproducibility
60
61**For full analyses:**
62- Lead with the key finding or insight
63- Support with data tables and/or visualizations
64- Note methodology and any caveats
65- Suggest follow-up questions
66
67**For formal reports:**
68- Executive summary with key findings
69- Methodology section explaining approach and data sources
70- Detailed findings with supporting evidence
71- Caveats and limitations
72- Recommendations and next steps
73- Appendix with full queries and data tables
74
75---
76
77## Workflow 2: Explore and Profile Datasets
78
79Generate a comprehensive data profile for a table or uploaded file. Understand its shape, quality, and patterns before diving into analysis.
80
81### 1. Access the Data
82
83**If a file is provided (CSV, Excel, Parquet, JSON):**
841. Read the file and load into a working dataset
852. If the file is large, sample it for profiling
86
87**If user describes a table:**
881. Ask for sample data or schema information
892. Generate profiling queries for the user to run
90
91### 2. Profile the Dataset
92
93Generate a report covering:
94
95#### Basic Statistics
96- **Row count**: Total number of records
97- **Column count**: Number of fields
98- **Primary key**: Identify unique identifier(s)
99- **Grain**: One row per what? (user, order, event, etc.)
100- **Time range**: For temporal data, first and last dates
101
102#### Column-Level Analysis
103
104For each column, report:
105- **Type**: String, integer, float, date, boolean, etc.
106- **Null rate**: Percentage of missing values
107- **Cardinality**: Number of unique values
108- **Sample values**: Examples of what the column contains
109- **Distribution**: For numeric columns, min/max/mean/median/std dev
110
111#### Data Quality Flags
112
113Automatically identify potential issues:
114- High null rates (>10%)
115- Unexpected values (e.g., negative values in a count field)
116- Duplicate rows
117- Inconsistent formatting (mixed case, trailing spaces)
118- Time gaps in temporal data
119
120### 3. Recommend Next Steps
121
122Based on profiling results, suggest:
123- **High-value dimensions** to explore (columns with moderate cardinality, low nulls)
124- **Data quality issues** to address before analysis
125- **Potential relationships** to investigate (correlated columns, hierarchies)
126- **Analysis starting points** based on the data's structure
127
128---
129
130## Workflow 3: Write Optimized SQL
131
132Write a SQL query from a natural language description, optimized for your specific SQL dialect and following best practices.
133
134### 1. Understand the Request
135
136Parse the user's description to identify:
137
138- **Output columns**: What fields should the result include?
139- **Filters**: What conditions limit the data (time ranges, segments, statuses)?
140- **Aggregations**: Are there GROUP BY operations, counts, sums, averages?
141- **Joins**: Does this require combining multiple tables?
142- **Ordering**: How should results be sorted?
143- **Limits**: Is there a top-N or sample requirement?
144
145### 2. Determine SQL Dialect
146
147Ask the user which database they're using if not specified:
148- PostgreSQL / Aurora / Supabase
149- Snowflake
150- BigQuery
151- Databricks / Spark SQL
152- Redshift
153- MySQL / MariaDB
154
155Each dialect has syntax differences for date functions, string operations, and window functions.
156
157### 3. Write the Query
158
159Use CTEs (Common Table Expressions) for complex queries:
160
161\`\`\`sql
162WITH base_data AS (
163 -- First CTE: Get the base dataset
164 SELECT ...
165),
166aggregated AS (
167 -- Second CTE: Perform aggregations
168 SELECT ...
169)
170-- Final SELECT from CTEs
171SELECT * FROM aggregated;
172\`\`\`
173
174**Best practices:**
175- Use explicit JOIN syntax (not implicit joins in WHERE clause)
176- Qualify all column names with table aliases when joining
177- Use meaningful CTE and alias names
178- Add comments explaining complex logic
179- Format for readability (indent, line breaks)
180- Consider performance (filter early, avoid SELECT *, use appropriate indexes)
181
182### 4. Add Context
183
184Include with the query:
185- **Purpose**: One-line description of what the query does
186- **Tables used**: Which tables are referenced
187- **Performance notes**: Expected row counts, potential bottlenecks
188- **Dialect-specific notes**: Any syntax specific to the database being used
189
190---
191
192## Workflow 4: Create Visualizations
193
194Create publication-quality data visualizations using Python. Generates charts from data with best practices for clarity, accuracy, and design.
195
196### 1. Understand the Request
197
198Determine:
199
200- **Data source**: Query results, pasted data, CSV/Excel file, or data to be queried
201- **Chart type**: Explicitly requested or needs to be recommended
202- **Purpose**: Exploration, presentation, report, dashboard component
203- **Audience**: Technical team, executives, external stakeholders
204
205### 2. Get the Data
206
207If data is not yet provided:
208- Ask the user to paste data or upload a file
209- If querying is needed, use the SQL workflow to generate the query first
210
211### 3. Choose the Right Chart Type
212
213Select visualization based on what you're showing:
214
215| What You're Showing | Best Chart | When to Use |
216|---------------------|------------|-------------|
217| **Trend over time** | Line chart | Continuous time series, shows change |
218| **Comparison across categories** | Bar chart | Comparing discrete categories |
219| **Part-to-whole** | Stacked bar / Pie | Composition, relative sizes |
220| **Distribution** | Histogram / Box plot | Understanding spread and outliers |
221| **Correlation** | Scatter plot | Relationship between two variables |
222| **Ranking** | Horizontal bar | Ordered list, easy to read labels |
223
224### 4. Generate Python Code
225
226Use \`plotly\` for interactive charts, \`seaborn\` or \`matplotlib\` for static charts.
227
228**Chart template pattern:**
229
230\`\`\`python
231import matplotlib.pyplot as plt
232import pandas as pd
233
234# Load data
235df = pd.DataFrame({...})
236
237# Create figure
238fig, ax = plt.subplots(figsize=(10, 6))
239
240# Plot
241ax.plot(df['x'], df['y']) # or .bar(), .scatter(), etc.
242
243# Style
244ax.set_title('Clear, Descriptive Title', fontsize=14, fontweight='bold')
245ax.set_xlabel('X Axis Label')
246ax.set_ylabel('Y Axis Label')
247ax.grid(axis='y', alpha=0.3)
248
249# Show
250plt.tight_layout()
251plt.show()
252\`\`\`
253
254### 5. Apply Design Principles
255
256- **Clarity**: Remove chart junk, use clear labels
257- **Accuracy**: Don't truncate axes to exaggerate differences
258- **Accessibility**: Use colorblind-friendly palettes
259- **Context**: Add reference lines, annotations for key points
260
261---
262
263## Workflow 5: Build Interactive Dashboards
264
265Build a self-contained interactive HTML dashboard with charts, filters, tables, and professional styling. Opens directly in a browser -- no server or dependencies required.
266
267### 1. Understand Dashboard Requirements
268
269Determine:
270
271- **Purpose**: Executive overview, operational monitoring, deep-dive analysis, team reporting
272- **Audience**: Who will use this dashboard?
273- **Key metrics**: What numbers matter most?
274- **Dimensions**: What should users be able to filter or slice by?
275- **Data source**: Live query, pasted data, CSV file, or sample data
276
277### 2. Gather the Data
278
279If data needs to be queried, use the SQL workflow.
280If data is provided, ensure it's in a structured format (CSV or JSON).
281
282### 3. Design Dashboard Layout
283
284Organize into sections:
285
2861. **Header**: Title, date range, key filters
2872. **KPI cards**: 3-5 big numbers that matter most
2883. **Primary charts**: 2-3 main visualizations (trends, comparisons)
2894. **Details section**: Tables or secondary charts for drill-down
2905. **Footer**: Methodology notes, data source, last updated
291
292### 4. Generate HTML/JS Code
293
294Use this template structure:
295
296\`\`\`html
297<!DOCTYPE html>
298<html lang="en">
299<head>
300 <meta charset="UTF-8">
301 <meta name="viewport" content="width=device-width, initial-scale=1.0">
302 <title>Dashboard Title</title>
303 <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
304 <style>
305 /* CSS styling */
306 </style>
307</head>
308<body>
309 <div class="container">
310 <!-- Dashboard content -->
311 </div>
312 <script>
313 // Data
314 const data = { /* embed data here */ };
315
316 // Charts
317 // Filters
318 // Interactivity
319 </script>
320</body>
321</html>
322\`\`\`
323
324### 5. Add Interactivity
325
326Implement:
327- **Dropdown filters**: Filter by category, time range, segment
328- **Chart interactions**: Hover tooltips, click to drill-down
329- **Table sorting**: Click column headers to sort
330- **Dynamic updates**: Filters update all charts simultaneously
331
332---
333
334## Workflow 6: Validate Analysis Before Sharing
335
336Review an analysis for accuracy, methodology, and potential biases before sharing with stakeholders. Generates a confidence assessment and improvement suggestions.
337
338### 1. Review Methodology and Assumptions
339
340Examine:
341
342**Data selection:**
343- Which tables/sources were used? Are they the right ones?
344- What time range? Is it recent enough?
345- Any filters applied? Do they introduce bias?
346
347**Aggregation logic:**
348- Are groupings appropriate for the question?
349- Do subtotals match totals?
350- Are nulls handled correctly (excluded vs. counted as zero)?
351
352**Statistical methods:**
353- If using averages, is median more appropriate?
354- If comparing percentages, are denominators consistent?
355- If showing trends, is seasonality accounted for?
356
357### 2. Check for Common Pitfalls
358
359**Survivorship bias:**
360- Example: Analyzing only current customers excludes churned users
361- Check: Does the analysis need to include historical records?
362
363**Selection bias:**
364- Example: Survey responses from only power users
365- Check: Is the sample representative of the population?
366
367**Simpson's paradox:**
368- Example: Overall trend contradicts subgroup trends when aggregated
369- Check: Break down by segments before concluding
370
371**Correlation vs. causation:**
372- Example: Ice cream sales correlate with drowning deaths (both caused by summer)
373- Check: Are confounding variables at play?
374
375### 3. Sanity Check Results
376
377Compare results to expectations:
378
379- **Magnitude**: Are numbers in the right ballpark?
380- **Direction**: Do trends match known business context?
381- **Consistency**: Do related metrics tell the same story?
382
383If something looks off:
384- Recheck the query
385- Look for data quality issues
386- Consider if external factors could explain it
387
388### 4. Assess Confidence Level
389
390Rate confidence as:
391
392- **High confidence**: Methodology sound, results validated, limitations documented
393- **Medium confidence**: Minor concerns or caveats, but core findings are solid
394- **Needs more work**: Methodological issues or data quality problems need addressing
395
396### 5. Document Limitations
397
398Every analysis has limits. Document:
399- What's excluded from the data
400- Assumptions made
401- Margin of error or uncertainty
402- Known data quality issues
403- Alternative interpretations
404
405**Example caveat:**
406> "This analysis excludes trial users, which may overstate conversion rate by ~5pp compared to total signups."
407
408---
409
410## When to Use Each Workflow
411
412- **Answer Data Questions**: User has a specific question to answer
413- **Explore Datasets**: Encountering a new table or dataset
414- **Write SQL**: Need to generate queries for manual execution
415- **Create Visualizations**: Need charts for reports or presentations
416- **Build Dashboards**: Need interactive, shareable dashboards
417- **Validate Analysis**: Before sharing important findings with stakeholders
418
419Use these workflows in combination for complex projects. For example:
4201. Explore data → 2. Write SQL → 3. Create visualization → 4. Validate → 5. Share