Course Overview All Courses Blog Reserve Bootcamp Seat
SQL for AI · Day 4 of 5 ~60 minutes

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.

Day 1
Day 2
Day 3
4
Day 4
5
Day 5
What You'll Build Today

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.

1
The Right Mindset

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.

2
Generating SQL

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:

  • What rows you want (filter conditions)
  • What columns to show
  • How to sort or limit results
  • Any grouping or aggregation needed

Example Prompts That Produce Good Queries

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."
3
Debugging

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.

4
Optimization

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
-- 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)
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.

Day 4 Complete — What You Learned

  • The mindset: AI multiplies SQL skill, it doesn't replace it
  • The prompt template: schema + plain-English description = reliable SQL
  • How to use AI to debug SQL errors with context
  • How to ask AI to optimize slow queries
Course progress
80%
Day 4 Done

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
Finished this lesson?