Natural Language to SQL and Code
From the course AI for Data Science: From Cleaning to Storytelling
Converting questions to SQL queries is one of AI's strongest capabilities. Modern LLMs can generate complex queries from natural language — but knowing how to prompt effectively makes all the difference.
How AI Generates SQL
You provide:
- Your database schema (table names, column names, types)
- A natural language question
- Any constraints or business rules
AI returns: A SQL query that answers your question.
Example:
Schema provided:
orders(id, customer_id, total, status, created_at)
customers(id, name, email, segment, country)
products(id, name, category, price)
order_items(order_id, product_id, quantity)
Question: "What are the top 10 customers by total spend in the last 90 days, broken down by product category?"
AI generates:
SELECT c.name, p.category,
SUM(oi.quantity * p.price) AS category_spend,
SUM(SUM(oi.quantity * p.price)) OVER (PARTITION BY c.id) AS total_spend
FROM customers c
JOIN orders o ON c.id = o.customer_id
JOIN order_items oi ON o.id = oi.order_id
JOIN products p ON oi.product_id = p.id
WHERE o.created_at >= CURRENT_DATE - INTERVAL '90 days'
AND o.status = 'completed'
GROUP BY c.id, c.name, p.category
ORDER BY total_spend DESC, c.name, category_spend DESC
LIMIT 50;
Best Practices for AI-Generated SQL
1. Always provide the full schema
Prompt: "Given this schema: [paste CREATE TABLE statements or column lists]
Write a query to find..."
2. Specify the SQL dialect PostgreSQL, MySQL, BigQuery, and Snowflake have different syntax.
3. Add business context "Active customers means those with at least one order in the last 180 days" "Revenue should exclude refunded orders (status = 'refunded')"
4. Request optimization "Optimize this query for a table with 50M rows" "Add appropriate indexes for this query pattern"
5. Validate before running
- Check the logic: does the query answer what you actually asked?
- Review JOINs: are they correct (INNER vs LEFT)?
- Check filters: are date ranges and conditions right?
- Estimate performance: any full table scans on large tables?
AI Tools for SQL Generation
- ChatGPT / Claude — Best for complex analytical queries
- GitHub Copilot — Inline SQL suggestions in your IDE
- Cursor — AI-powered code editor with SQL support
- AI2sql — Dedicated text-to-SQL tool
- DBeaver AI — AI assistant built into the database client
Beyond SQL: AI for Code Generation
AI excels at generating data science code:
- Python (pandas, numpy, scikit-learn) — Data manipulation and ML
- R (tidyverse, ggplot2) — Statistical analysis and visualization
- PySpark — Big data processing
- dbt models — Data transformation layers
Prompt pattern for code generation:
"Using pandas, write a function that:
1. Reads a CSV file
2. Handles missing values in the 'age' column using median imputation
3. Creates a 'age_group' column (18-25, 26-35, 36-50, 51+)
4. Returns the cleaned DataFrame
Include type hints and docstrings."
Key Takeaways
- •AI converts natural language questions to SQL with high accuracy when given proper schema
- •Always provide full schema, SQL dialect, and business context in your prompts
- •Validate AI-generated SQL: check logic, JOINs, filters, and performance
- •AI generates Python, R, and PySpark code for data manipulation and analysis
- •Use structured prompt patterns with numbered steps for best code generation results
Progress is kept in this browser only.