Day 04 Advanced Topics

Using AI to Write and Optimize SQL

How modern data teams actually work — describe what you want in English, get SQL back in seconds, then understand and refine it. AI as a SQL copilot, not a replacement.

~1 hour Hands-on Precision AI Academy

Today’s Objective

How modern data teams actually work — describe what you want in English, get SQL back in seconds, then understand and refine it. AI as a SQL copilot, not a replacement.

A personal AI SQL workflow — prompts that reliably generate correct queries, a debugging process, and an optimization approach. You'll also write a CTE-based query entirely by prompting Claude.

AI doesn't replace SQL knowledge. It multiplies it.

Here's what you'll find: AI writes good SQL fast. But it also writes confidently wrong SQL sometimes. Without the three days you just completed, you can't tell the difference. That's why you learned SQL first.

The workflow is: describe what you want → get a query → read it, run it, verify the output makes sense → refine. You stay in control. AI handles the typing.

Never trust AI SQL blindly. Always run it against a small dataset first. Check that the row counts and values look right before using any query in a production report or decision.

The Prompt Template That Works

The key to getting good SQL from AI is giving it your schema upfront. AI that doesn't know your table names and column names will hallucinate them.

Prompt Template — Copy and Adapt

I have a SQLite database with these tables:

customers (id, name, city, segment)
orders (id, customer_id, order_date, amount, status)

Write a SQL query that: [describe what you want in plain English]

Return only the SQL, no explanation needed.

The plain-English description is everything. Be specific about:

Example Prompts That Produce Good Queries

prompt examples
PROMPT EXAMPLES
// Prompt 1 — specific and complete
"Give me the total revenue per customer segment for
completed orders only, sorted high to low."

// Prompt 2 — asks for a specific technique
"Using a CTE, find customers whose total spend is more
than 1.5x the average customer spend."

// Prompt 3 — window function request
"Rank customers by total revenue using RANK().
Show name, total, and rank. Top customer is rank 1."

AI as a SQL Debugger

When you get an error — paste it in. AI is extremely good at explaining SQL errors and suggesting fixes.

Debug Prompt

I ran this SQL query in SQLite:

[paste your query]

I got this error:
[paste the error message]

My table schema is: customers (id, name, city, segment), orders (id, customer_id, order_date, amount, status)

What's wrong and how do I fix it?

Common SQL errors AI handles perfectly: "column does not exist" (typo or wrong alias), "ambiguous column name" (need table prefix), "aggregate function in WHERE" (should be HAVING), GROUP BY violations.

Using AI to Speed Up Slow Queries

Once you're working with large tables (100K+ rows), query speed matters. AI can suggest indexes, rewrite inefficient subqueries as JOINs, and spot patterns that slow databases down.

sql — slow version
SQL — SLOW VERSION
-- Slow: correlated subquery runs once per row
SELECT *
FROM orders o
WHERE amount > ( SELECT AVG(amount) FROM orders WHERE customer_id = o.customer_id
);
sql — faster version (CTE pre-computes the average)
SQL — FASTER VERSION (CTE PRE-COMPUTES THE AVERAGE)
WITH avg_per_customer AS ( SELECT customer_id, AVG(amount) AS avg_amt FROM orders GROUP BY customer_id
)
SELECT o.*
FROM orders o
JOIN avg_per_customer a ON o.customer_id = a.customer_id
WHERE o.amount > a.avg_amt;

Prompt: "Here's a slow SQL query. Rewrite it to be more efficient. Explain what change you made and why." — paste your query. AI will almost always find the issue.

80%

Final day: build a full data pipeline

Day 5 ties SQL, Python, and AI together into a complete end-to-end data pipeline you can show employers.

Day 5: SQL + Python + AI Pipeline

Supporting Resources

Go deeper with these references.

Day 4 Checkpoint

Before moving on, make sure you can answer these without looking:

Continue To Day 5
Build a Data Pipeline — SQL + Python + AI