Skip to main content
March 23, 2026Dan Rodney/6 min read

AI and SQL - Hands On Challenge - Solution

Master AI-Assisted SQL Query Development and Optimization

Prerequisites for This Challenge

This hands-on solution assumes you have ChatGPT access, a database schema screenshot, and basic SQL knowledge for verification purposes.

AI-Assisted SQL Development Process

1

Upload Schema Documentation

Provide ChatGPT with your database structure screenshot or documentation to establish context

2

Write Specific Prompts

Be explicit about SQL dialect (PostgreSQL, SQL Server, Oracle) and exact requirements

3

Iterate and Refine

Engage in back-and-forth conversation to clarify requirements and fix issues

4

Validate Results

Always test the generated query and verify results make logical sense

Generic vs Specific AI Prompts

FeatureGeneric PromptSpecific Prompt
Request StyleCalculate sales by state for 2021Write a PostgreSQL query that calculates sales by state for 2021
AI ResponseAttempts data analysis directlyGenerates SQL query code
OutcomeMay not match your needsProvides exactly what you want
Recommended: Always specify the exact SQL dialect and that you want a query, not analysis
Common AI Misinterpretation

ChatGPT may choose the easiest data relationship rather than the business-correct one. Always verify the logic matches your requirements.

Ship-To vs User Location Analysis

Pros
User location shows actual customer demographics
Better for marketing and business strategy decisions
More accurate representation of customer base geography
Cons
Ship-to location is easier to implement with fewer joins
May not reflect gift purchases or business shipping addresses
Requires more complex query structure with additional table joins

Database Query Results

States with Sales Data
39
Total US States
50

Query Validation Checklist

0/5
Advanced Query Enhancement

When you need more complex analysis like year-over-year growth, you can iteratively build on existing queries by asking ChatGPT to add specific columns or calculations.

Common Query Patterns for Business Analysis

Revenue by Geography

Analyze sales performance across different states or regions. Requires joining user location data with sales transactions.

Year-over-Year Growth

Compare current period performance to previous periods. Often uses CTEs and window functions for complex calculations.

Customer Segmentation

Group customers by behavior or demographics. Involves aggregating transaction data with user characteristics.

Don't just assume it's going to get everything right. Be as specific as you can, and you'll get it closer to being in just kind of a one-shot query.
Key principle for effective AI-assisted SQL development
Avoiding Division by Zero Errors

Complex calculations like percentage growth require NULLIF functions to prevent division by zero errors. Always understand why specific SQL functions are being used.

Learning SQL Through AI Assistance

1

Ask for Explanations

When you see unfamiliar functions or approaches, ask ChatGPT to explain them in detail

2

Understand the Logic

Don't just copy-paste queries; try to follow the reasoning behind each part of the code

3

Request Examples

Ask for specific examples of how functions like NULLIF work in different contexts

4

Build Incrementally

Start with simple queries and gradually add complexity as you understand each component

Using ChatGPT for SQL Development

Pros
Helps with complex queries you might struggle to write alone
Provides instant feedback and iteration capabilities
Can explain unfamiliar SQL functions and concepts
Great for getting unstuck on difficult problems
Serves as a digital assistant for query optimization
Cons
Not always perfect, especially for very complex requirements
Requires SQL knowledge to validate and verify results
May choose suboptimal approaches without business context
Cannot replace understanding of fundamental SQL concepts
Accuracy depends on how well you can verify the output
The Bottom Line

ChatGPT can be a powerful ally for SQL development, but the responsibility for accuracy and validation always remains with you as the developer.

Let's dive into the first challenge with a practical example: analyzing our 2021 revenue by state. This scenario demonstrates both the power and pitfalls of using AI for database queries. I'll walk you through the process, including the critical mistakes to avoid and the verification steps that separate amateur from professional data analysis.

The initial approach many professionals take is too generic. When I first uploaded my database schema screenshot and asked ChatGPT to "calculate the sales by state for 2021," it defaulted to its advanced data analysis mode. This feature allows ChatGPT to process CSV or Excel files directly, performing calculations within its interface. While convenient, this wasn't what I needed—I required a SQL query that could be executed against my production database, not a one-off analysis.

This highlights the first critical lesson: specificity drives accuracy. When working with AI assistants for database work, vague requests yield suboptimal results. Instead of asking for generic calculations, I needed to explicitly request a SQL query.

Here's where precision becomes crucial: I specified "PostgreSQL query" rather than simply "SQL query." This distinction matters significantly in enterprise environments. PostgreSQL, Oracle, SQL Server, and other database systems each have distinct syntax variations and optimization patterns. By specifying the exact database system, I ensured the generated code would be compatible with my infrastructure and follow PostgreSQL-specific best practices.

The AI's initial query attempt revealed another common pitfall. It joined the orders table to line items and calculated results based on shipping addresses—the path of least resistance in the schema. However, my business requirement was different: I needed results based on where customers actually lived, not where their orders were shipped. This distinction could significantly impact strategic decisions about market penetration and customer geographic distribution.

This required immediate correction. I specified: "Please use where users live, not where orders were shipped to." The AI quickly adapted, restructuring the query to join orders to users, then to line items, properly focusing on user residential locations rather than shipping destinations. This back-and-forth interaction exemplifies why human oversight remains essential in AI-assisted data analysis.

The verification process is where professional data analysts distinguish themselves. I didn't simply accept the generated query—I executed it against my database to validate both the logic and results. The output showed sales data across 39 states, properly ordered by total sales volume with high-performing states at the top. This gave me confidence that our customer base had meaningful geographic distribution across most of the United States.


Examining the underlying calculations, I confirmed the AI correctly computed price times quantity for each line item, summed by user state, and filtered by the appropriate year from the order placement date. The mathematical logic was sound, the joins were appropriate, and the grouping made business sense. This comprehensive verification process—what I call the "sniff test"—is non-negotiable when using AI-generated code in production environments.

Building on this success, I wanted to explore year-over-year growth patterns. Understanding revenue trends is crucial for strategic planning, investor communications, and resource allocation decisions. I requested an additional column showing year-over-year growth from the previous year, comparing 2021 performance against 2020 baseline figures.

The AI generated a more sophisticated query using Common Table Expressions (CTEs) to calculate sales for both years, then performed the growth calculations. The resulting dataset revealed fascinating insights: some states showed dramatic growth (one jumped from $50 to over $1,000 in sales), while others declined year-over-year. This granular view enables targeted marketing investments and regional strategy adjustments.

However, I noticed the AI used techniques I wasn't immediately familiar with, including a sales pivot structure and the NULLIF function. Rather than blindly trusting the code, I asked for detailed explanations. The AI clarified that NULLIF prevents division-by-zero errors when calculating percentage growth—essential for data integrity when some states had zero sales in the baseline year. This educational aspect transforms AI from a mere coding assistant into a learning tool for advancing SQL expertise.

Recognizing that state-by-state analysis might be too granular for executive reporting, I started a fresh conversation focused on overall company performance. This decision to create a new chat session rather than continuing the previous thread demonstrates strategic thinking—different business questions require different analytical approaches, and context switching helps maintain clarity.

For the company-wide analysis, I requested year-over-year growth spanning 2020 to 2022, providing broader trend visibility. The AI's first attempt focused on order count rather than revenue—a common misinterpretation that highlights why domain expertise remains crucial. Orders and revenue tell different stories: we might process more orders while generating less revenue due to changing customer behavior, promotional strategies, or product mix shifts.


After clarifying that I needed sales amounts rather than order counts, the revised query provided the strategic insight I sought. The final output showed clear revenue progression over the three-year period, with calculated percentage growth rates that could be directly incorporated into board presentations and strategic planning documents.

This experience illustrates the optimal relationship between AI assistance and professional expertise. ChatGPT excels at handling complex query structures, remembering schema relationships, and implementing SQL best practices. However, it requires human guidance for business context, requirement clarification, and result validation. The AI can't determine whether shipping addresses or customer addresses better serve your analytical needs—that requires business acumen and strategic thinking.

As we advance into 2026, this collaborative approach becomes increasingly valuable. Modern databases are more complex, business requirements are more nuanced, and the cost of analytical errors continues to rise. AI assistants can dramatically accelerate query development and help professionals tackle sophisticated analytical challenges, but they cannot replace the critical thinking and domain expertise that ensure accurate, actionable results.

The key to success lies in maintaining healthy skepticism while leveraging AI capabilities. Always verify generated queries against your database. Always validate that results align with business logic and known patterns. Always ensure you understand the code well enough to explain it to stakeholders and troubleshoot issues when they arise.

Ultimately, ChatGPT serves as a powerful digital assistant that can help overcome complex query challenges, accelerate learning, and handle routine analytical tasks. But the responsibility for accuracy, business relevance, and strategic insight remains squarely with the professional analyst. In this partnership, AI handles the syntax while humans provide the strategy—a combination that delivers both efficiency and excellence in modern data analysis.

Key Takeaways

1Always be specific when prompting ChatGPT - specify the exact SQL dialect (PostgreSQL, Oracle, SQL Server) and clarify that you want a query, not data analysis
2Upload your database schema to ChatGPT to provide proper context for accurate table joins and column references
3Engage in iterative conversation with ChatGPT to refine queries - don't expect perfection on the first try
4Always validate AI-generated queries by testing them in your database and performing logical checks on the results
5Pay attention to business logic requirements - AI might choose the easiest technical solution rather than the correct business solution
6Use ChatGPT as a learning tool by asking for explanations of unfamiliar SQL functions and query patterns
7Understand that ChatGPT can help with complex queries and getting unstuck, but cannot replace fundamental SQL knowledge
8Remember that you are ultimately responsible for query accuracy - fast AI responses are worthless if they produce incorrect results

RELATED ARTICLES