How to Write SQL Using AI
Use an AI assistant to write SQL queries you can trust. Give it your table structure, ask a clear question, then check the answer on a small sample you can count by hand.
In short: paste the CREATE TABLE lines (not real data), name your database (PostgreSQL, MySQL, SQLite, SQL Server), state the question, and test on a tiny sample with a known answer.
Why SQL with AI
Almost every company stores data in SQL databases: banks, e-commerce, hospitals. Analysts and developers write queries daily. AI writes them fast, but a wrong JOIN or date filter gives wrong numbers that look right.
What you need
- The schema: the CREATE TABLE statements: table names, columns, types, keys.
- Your database name and version: SQL differs a little between PostgreSQL, MySQL, SQLite and SQL Server.
- A small sample: a few rows where you know the right answer.
- A safe place to run it: a local copy or test database, never production first.
How it flows
Set up a safe practice database
- Python already includes SQLite. No install needed.
- Or install PostgreSQL / MySQL locally, or use a Docker container.
- Create the sample tables below and load the 5 rows.
CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT NOT NULL, city TEXT NOT NULL); CREATE TABLE orders ( id INTEGER PRIMARY KEY, customer_id INTEGER NOT NULL REFERENCES customers(id), amount NUMERIC(10,2) NOT NULL, created_at DATE NOT NULL ); INSERT INTO customers VALUES (1,'Asha','Pune'),(2,'Ravi','Mumbai'),(3,'Meena','Nagpur'); INSERT INTO orders VALUES (1,1,1200.00,'2026-01-15'),(2,1,800.00,'2026-03-02'),(3,2,5000.00,'2026-02-20'), (4,3,300.00,'2025-12-30'),(5,2,700.00,'2026-07-01');
Step 1 — the prompt
PostgreSQL. Tables: customers(id, name, city) and orders(id, customer_id, amount, created_at DATE). Write a query that shows each customer's name, city, number of orders and total amount for orders in 2026 only, highest total first. Use a date range that can use an index (no functions on the column). Only return the SQL.
Step 2 — the query (tested here)
top_customers.sql-- Total spend per customer in 2026, highest first. Built with an AI assistant, then tested.
SELECT c.name,
c.city,
COUNT(o.id) AS orders,
SUM(o.amount) AS total
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
WHERE o.created_at >= '2026-01-01'
AND o.created_at < '2027-01-01'
GROUP BY c.id, c.name, c.city
ORDER BY total DESC;# expected on the sample (count by hand first):
# Ravi Mumbai 2 5700 (5000 + 700)
# Asha Pune 2 2000 (1200 + 800)
# Meena is not listed: her only order is in 2025Step 3 — run queries from code safely
Ask: “Show me how to run this from Python with a parameter for the city, no string joining.”
safe_query.py"""Run a query safely with a parameter (no string joining). Tested with SQLite."""
import sqlite3
def orders_for_city(conn, city):
sql = """SELECT o.id, o.amount FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE c.city = ? ORDER BY o.id"""
return conn.execute(sql, (city,)).fetchall()test_sql.pyimport sqlite3
from safe_query import orders_for_city
def db():
conn = sqlite3.connect(":memory:")
conn.executescript(open("schema.sql").read())
return conn
def test_top_customers_2026():
rows = db().execute(open("top_customers.sql").read()).fetchall()
assert rows == [("Ravi", "Mumbai", 2, 5700), ("Asha", "Pune", 2, 2000)] # Meena's order is 2025
def test_parameter_blocks_injection():
conn = db()
assert orders_for_city(conn, "Pune") == [(1, 1200), (2, 800)]
assert orders_for_city(conn, "Pune' OR '1'='1") == []pytest -q
# -> 2 passedThe second test passes an attack string as the city. Because of the ? parameter, it is treated as plain text and returns nothing.
How to check any AI query
- Count by hand on 5–10 rows first.
- Check every JOIN: INNER JOIN drops rows with no match; LEFT JOIN keeps them.
- Check date ranges: use
>= start AND < next_start; avoidBETWEENwith timestamps. - Check GROUP BY includes every non-aggregated column.
- Look at the plan:
EXPLAIN(PostgreSQL/MySQL) before running on big tables. - Run as a read-only user when exploring real data.
Watch out (common AI mistakes in SQL)
- Wrong database dialect —
LIMITvsTOP, date functions differ; always name your DB. - Functions on indexed columns (
YEAR(created_at) = 2026) — slow on big tables. - String-joined SQL in code — SQL injection risk; use parameters.
- UPDATE or DELETE without WHERE — always run a SELECT with the same WHERE first, inside a transaction.
Try this yourself: ask AI for a grouped SQL report, then prove it with pytest
Hello friends. This practice uses a tiny fictional warehouse called Lumen Bay Workshop, with clerk Oren Pike and invented part SKUs. You ask an AI assistant for a filtered and grouped SQLite query that totals quantities by bay for one month. Then you prove the answer with pytest against sqlite3. The live chapter already showed a customers and orders join. Here you practise a different table and a GROUP BY total. Always keep the month value in a ? parameter. Do not build SQL by joining user text into the string. This page shows only the safe parameterized form and describes the unsafe habit in words.
नमस्कार मित्रांनो. हा सराव Lumen Bay Workshop नावाच्या छोट्या काल्पनिक गोदामावर आहे, ज्यात clerk Oren Pike आणि काल्पनिक part SKUs आहेत. तुम्ही AI कडून एका महिन्यासाठी bay नुसार quantities एकत्र करणारी filtered आणि grouped SQLite query मागता. नंतर sqlite3 वर pytest ने उत्तर सिद्ध करता. Live chapter मध्ये customers आणि orders join दाखवला होता. इथे वेगळी table आणि GROUP BY total चा सराव आहे. Month value नेहमी ? parameter मध्ये ठेवा. User text SQL मध्ये जोडून query बनवू नका. या पानावर फक्त सुरक्षित parameterized रूप दाखवले आहे, आणि असुरक्षित सवय शब्दांत सांगितली आहे.
नमस्ते दोस्तों. यह अभ्यास Lumen Bay Workshop नाम की छोटी काल्पनिक गोदाम पर है, जिसमें clerk Oren Pike और काल्पनिक part SKUs हैं. आप AI से एक महीने के लिए bay के हिसाब से quantities जोड़ने वाली filtered और grouped SQLite query मांगते हो. फिर sqlite3 पर pytest से जवाब साबित करते हो. Live chapter में customers और orders join दिखाया था. यहां अलग table और GROUP BY total का अभ्यास है. Month value हमेशा ? parameter में रखो. User text को SQL में जोड़कर query मत बनाओ. इस पेज पर सिर्फ सुरक्षित parameterized रूप दिखाया है, और असुरक्षित आदत शब्दों में बताई है.
Ravindra Bagale's Tip
When an AI gives you SQL for application code, look for a ? or %s placeholder before you run it. If the month or city is pasted into the SQL text with plus signs or an f-string, rewrite it as a bound parameter. You do not need an attack example to understand that risk.
Ravindra Bagale's Tip – मराठी
AI जेव्हा application code साठी SQL देते, ते चालवण्याआधी ? किंवा %s placeholder शोधा. जर month किंवा city plus चिन्हांनी किंवा f-string ने SQL मजकूरात चिकटवली असेल, तर ती bound parameter म्हणून पुन्हा लिहा. हा धोका समजण्यासाठी attack उदाहरणाची गरज नाही.
Ravindra Bagale's Tip – हिंदी
जब AI application code के लिए SQL दे, उसे चलाने से पहले ? या %s placeholder ढूंढो. अगर month या city plus चिह्नों या f-string से SQL पाठ में चिपकी हो, तो उसे bound parameter के रूप में फिर लिखो. यह जोखिम समझने के लिए attack उदाहरण की ज़रूरत नहीं।
Python 3.13.5, sqlite3 3.46.1 (Python stdlib), and pytest 9.1.1. Use Python 3.10 or newer.Your task: save the starter parts_report.py and the tests. The starter seeds six fictional Lumen Bay rows but bay_totals_for_month still returns an empty list. Ask an AI for a parameterized GROUP BY bay query filtered by a YYYY-MM prefix, paste the safe version, and re-run pytest until all six tests pass.
Setup
- Create a project folder and open a terminal inside it.
- Create a virtual environment: on macOS or Linux run
python3 -m venv .venv. On Windows runpy -3 -m venv .venv. - Activate it: on macOS or Linux run
source .venv/bin/activate. In Windows Command Prompt run.venv\Scripts\activate.bat, and in Windows PowerShell run.venv\Scripts\Activate.ps1. - Install pytest inside the virtual environment:
python -m pip install pytest.
Starter parts_report.py (seed works; query body is empty on purpose):
"""Lumen Bay Workshop parts orders report (fictional teaching data only).
Ask an AI for a filtered + grouped SQLite query, then prove it with pytest.
Clerk name Oren Pike and every SKU/bay/date here are invented practice data.
"""
from __future__ import annotations
import sqlite3
SCHEMA = """
CREATE TABLE parts_orders (
id INTEGER PRIMARY KEY,
part_sku TEXT NOT NULL,
bay TEXT NOT NULL,
qty INTEGER NOT NULL,
ordered_on TEXT NOT NULL
);
"""
# Fictional seed rows for Lumen Bay Workshop (not a real warehouse).
SEED: list[tuple[str, str, int, str]] = [
("LB-GEAR-04", "North", 3, "2026-03-04"),
("LB-BOLT-12", "North", 10, "2026-03-11"),
("LB-GEAR-04", "South", 2, "2026-03-18"),
("LB-PIN-07", "South", 5, "2026-02-20"),
("LB-BOLT-12", "East", 4, "2026-03-22"),
("LB-WASHER-3", "East", 8, "2026-01-09"),
]
def connect_memory() -> sqlite3.Connection:
"""Return an in-memory SQLite connection with schema and seed rows loaded."""
conn = sqlite3.connect(":memory:")
conn.execute(SCHEMA)
conn.executemany(
"INSERT INTO parts_orders (part_sku, bay, qty, ordered_on) VALUES (?, ?, ?, ?)",
SEED,
)
conn.commit()
return conn
def bay_totals_for_month(conn: sqlite3.Connection, year_month: str) -> list[tuple[str, int]]:
"""Return (bay, total_qty) for orders whose ordered_on starts with year_month.
year_month must look like '2026-03'. Use a parameterized query (? placeholder).
Sort bays ascending. Do not build SQL by joining user text into the string.
Starter note: this returns an empty list on purpose. Ask an AI for the query,
paste a safe parameterized version, then re-run the tests.
"""
if not isinstance(year_month, str) or len(year_month) != 7 or year_month[4] != "-":
raise ValueError("year_month must look like YYYY-MM")
# TODO: replace this empty return with a parameterized GROUP BY query.
# Keep the ? placeholder. Never paste year_month into the SQL with + or f-strings.
_ = conn # starter keeps the connection unused until you add the query
return []
Tests test_parts_report.py (do not weaken these checks):
"""pytest checks for the fictional Lumen Bay Workshop parts report."""
import pytest
from parts_report import bay_totals_for_month, connect_memory
@pytest.fixture()
def conn():
c = connect_memory()
yield c
c.close()
def test_march_2026_totals_by_bay(conn):
assert bay_totals_for_month(conn, "2026-03") == [
("East", 4),
("North", 13),
("South", 2),
]
def test_february_2026_only_south(conn):
assert bay_totals_for_month(conn, "2026-02") == [("South", 5)]
def test_january_2026_only_east(conn):
assert bay_totals_for_month(conn, "2026-01") == [("East", 8)]
def test_month_with_no_orders(conn):
assert bay_totals_for_month(conn, "2026-12") == []
def test_rejects_bad_year_month_shape(conn):
with pytest.raises(ValueError, match="YYYY-MM"):
bay_totals_for_month(conn, "2026/03")
with pytest.raises(ValueError, match="YYYY-MM"):
bay_totals_for_month(conn, "26-03")
with pytest.raises(ValueError, match="YYYY-MM"):
bay_totals_for_month(conn, 202603) # type: ignore[arg-type]
def test_query_uses_parameter_placeholder():
"""Guardrail: source must keep a ? placeholder (parameterized), not only string glue."""
from pathlib import Path
import parts_report as mod
src = Path(mod.__file__).read_text(encoding="utf-8")
assert "?" in src
assert "ordered_on LIKE ?" in src.replace("\n", " ") or 'ordered_on LIKE ?' in src
Suggested AI ask (copy and adapt):
sql-prompt.txtIn parts_report.py, implement bay_totals_for_month for SQLite. Input year_month like 2026-03. Return list of (bay, total_qty) for rows whose ordered_on starts with that month, GROUP BY bay, ORDER BY bay ASC. Validate year_month shape and raise ValueError with message containing YYYY-MM when invalid. Use a parameterized query with a ? placeholder for the LIKE pattern. Do not concatenate year_month into the SQL string with + or an f-string. Fictional Lumen Bay Workshop teaching data only.
HOW to finish
- Save
parts_report.pyandtest_parts_report.pyin the same folder. - Run
python -m pytest -q test_parts_report.py. Expect 4 failed, 2 passed while the query still returns an empty list. - Ask your AI assistant for the parameterized GROUP BY query using the prompt above.
- Paste only a safe version that keeps the
?placeholder. Keep the seed data unchanged. - Run the same pytest command again. Expect 6 passed.
- Hand-check March 2026: North should total 13, East 4, South 2.
Real output before the query:
pytest-before.txt4 failed, 2 passed in 0.02s
Real output after a good parameterized query (seconds can differ slightly):
pytest-after.txt...... [100%]
6 passed in 0.01s
Optional completed parts_report.py (try it yourself first)
Your AI assistant may format the SQL differently. Any version is fine if all 6 tests pass and the SQL still uses a ? placeholder for the month filter.
"""Lumen Bay Workshop parts orders report (fictional teaching data only).
Ask an AI for a filtered + grouped SQLite query, then prove it with pytest.
Clerk name Oren Pike and every SKU/bay/date here are invented practice data.
"""
from __future__ import annotations
import sqlite3
SCHEMA = """
CREATE TABLE parts_orders (
id INTEGER PRIMARY KEY,
part_sku TEXT NOT NULL,
bay TEXT NOT NULL,
qty INTEGER NOT NULL,
ordered_on TEXT NOT NULL
);
"""
# Fictional seed rows for Lumen Bay Workshop (not a real warehouse).
SEED: list[tuple[str, str, int, str]] = [
("LB-GEAR-04", "North", 3, "2026-03-04"),
("LB-BOLT-12", "North", 10, "2026-03-11"),
("LB-GEAR-04", "South", 2, "2026-03-18"),
("LB-PIN-07", "South", 5, "2026-02-20"),
("LB-BOLT-12", "East", 4, "2026-03-22"),
("LB-WASHER-3", "East", 8, "2026-01-09"),
]
def connect_memory() -> sqlite3.Connection:
"""Return an in-memory SQLite connection with schema and seed rows loaded."""
conn = sqlite3.connect(":memory:")
conn.execute(SCHEMA)
conn.executemany(
"INSERT INTO parts_orders (part_sku, bay, qty, ordered_on) VALUES (?, ?, ?, ?)",
SEED,
)
conn.commit()
return conn
def bay_totals_for_month(conn: sqlite3.Connection, year_month: str) -> list[tuple[str, int]]:
"""Return (bay, total_qty) for orders whose ordered_on starts with year_month.
year_month must look like '2026-03'. Use a parameterized query (? placeholder).
Sort bays ascending. Do not build SQL by joining user text into the string.
"""
if not isinstance(year_month, str) or len(year_month) != 7 or year_month[4] != "-":
raise ValueError("year_month must look like YYYY-MM")
# Safe pattern: bind the month prefix with ?. Never concatenate year_month into SQL
# with + or an f-string. That string-building habit is how injection bugs start;
# this practice shows only the safe parameterized form.
rows = conn.execute(
"""
SELECT bay, SUM(qty) AS total_qty
FROM parts_orders
WHERE ordered_on LIKE ?
GROUP BY bay
ORDER BY bay ASC
""",
(year_month + "%",),
).fetchall()
return [(bay, int(total)) for bay, total in rows]
Troubleshooting
- Problem: March totals are wrong after you paste AI SQL. Fix: confirm the filter uses a prefix match on
ordered_onfor2026-03, and that February and January rows stay out of the March group. - Error:
ValueError: year_month must look like YYYY-MMon a good month. Fix: pass a string such as"2026-03", not an integer and not2026/03. - Problem: the placeholder test fails. Fix: your source must contain the text
ordered_on LIKE ?. Do not remove the question mark. - Error:
ModuleNotFoundError: No module named pytest. Fix: activate the virtual environment and runpython -m pip install pytest.
Practice cards: English and spoken Marathi
Each card below explains one idea on its own, so you can save or revise a single card without reading the whole chapter.
Parameters beat string glue
Hand-count before you celebrate
Parameters हे string glue पेक्षा सुरक्षित
Celebrate करण्याआधी हाताने मोजून पहा
Quick quiz
1. What should you give the AI instead of real data?
The CREATE TABLE schema and a few fake sample rows.
2. Why was Meena missing from the result?
Her only order was in 2025, outside the 2026 range.
3. What stops SQL injection in code?
Query parameters (like ? or %s), never string joining.
4. Safer date filter than YEAR(created_at) = 2026?
created_at >= '2026-01-01' AND created_at < '2027-01-01'.
Save tokens and money
Paste only the tables the query needs, not the whole database schema. Ask for the query only, without long explanations. Reuse a working prompt as a template for similar reports.