Ravindra BagaleCourses & study guides Track your progress
AI CODING ASSISTANTS · CHAPTER 3 · LANGUAGES

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

WHY

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

WHAT
  • 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

1 · Give schema + DB name no real data 2 · Ask one clear question with date range 3 · AI writes the query read the JOINs 4 · Run on a tiny sample answer known by hand 5 · Then run on real data read-only user

Set up a safe practice database

HOW
  1. Python already includes SQLite. No install needed.
  2. Or install PostgreSQL / MySQL locally, or use a Docker container.
  3. Create the sample tables below and load the 5 rows.
schema.sql
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

COPY THIS 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 2025
We ran it on SQLite with these 5 rows and got exactly those two rows. In PostgreSQL the totals show as 5700.00 and 2000.00 because of the NUMERIC type.

Step 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.py
import 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 passed

The 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

  1. Count by hand on 5–10 rows first.
  2. Check every JOIN: INNER JOIN drops rows with no match; LEFT JOIN keeps them.
  3. Check date ranges: use >= start AND < next_start; avoid BETWEEN with timestamps.
  4. Check GROUP BY includes every non-aggregated column.
  5. Look at the plan: EXPLAIN (PostgreSQL/MySQL) before running on big tables.
  6. Run as a read-only user when exploring real data.

Watch out (common AI mistakes in SQL)

  • Wrong database dialect — LIMIT vs TOP, 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.
Rule: never paste real customer data into a cloud AI. Share only the schema and fake sample rows.

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.

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.

Practice label: every name, number and time in this exercise is fictional teaching data. It is not about a real person, account or company. Passing these tests proves only the cases listed in the tests, not every possible input.
Environment (tested): this exercise was run on 6 November 2026 and re-run on 16 November 2026 with 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

HOW
  1. Create a project folder and open a terminal inside it.
  2. Create a virtual environment: on macOS or Linux run python3 -m venv .venv. On Windows run py -3 -m venv .venv.
  3. 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.
  4. Install pytest inside the virtual environment: python -m pip install pytest.

Starter parts_report.py (seed works; query body is empty on purpose):

parts_report.py
"""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):

test_parts_report.py
"""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.txt
In 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

HOW
  1. Save parts_report.py and test_parts_report.py in the same folder.
  2. Run python -m pytest -q test_parts_report.py. Expect 4 failed, 2 passed while the query still returns an empty list.
  3. Ask your AI assistant for the parameterized GROUP BY query using the prompt above.
  4. Paste only a safe version that keeps the ? placeholder. Keep the seed data unchanged.
  5. Run the same pytest command again. Expect 6 passed.
  6. Hand-check March 2026: North should total 13, East 4, South 2.

Real output before the query:

pytest-before.txt
4 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.

parts_report.py
"""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

HOW
  1. Problem: March totals are wrong after you paste AI SQL. Fix: confirm the filter uses a prefix match on ordered_on for 2026-03, and that February and January rows stay out of the March group.
  2. Error: ValueError: year_month must look like YYYY-MM on a good month. Fix: pass a string such as "2026-03", not an integer and not 2026/03.
  3. Problem: the placeholder test fails. Fix: your source must contain the text ordered_on LIKE ?. Do not remove the question mark.
  4. Error: ModuleNotFoundError: No module named pytest. Fix: activate the virtual environment and run python -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.

PRACTICE CARDAI Coding

Parameters beat string glue

Keep month filters in a ? placeholder when AI writes SQL for your code.
Prove the GROUP BY totals on the tiny seed table before you trust a bigger database.
Ravindra Bagale · ravindrabagale.com/ai-coding
PRACTICE CARDAI Coding

Hand-count before you celebrate

For March 2026 the North bay must total 13 across two fictional rows.
If the AI query misses a bay, fix the filter or the GROUP BY before you ship it.
Ravindra Bagale · ravindrabagale.com/ai-coding
सराव कार्डमराठी

Parameters हे string glue पेक्षा सुरक्षित

AI जेव्हा तुमच्या code साठी SQL लिहिते, तेव्हा month filter ? placeholder मध्ये ठेवा.
मोठ्या database वर विश्वास ठेवण्याआधी छोट्या seed table वर GROUP BY totals सिद्ध करा.
Ravindra Bagale · ravindrabagale.com/ai-coding
सराव कार्डमराठी

Celebrate करण्याआधी हाताने मोजून पहा

March 2026 साठी North bay दोन काल्पनिक rows मिळून 13 असला पाहिजे.
जर AI query एखादा bay चुकवते, तर ship करण्याआधी filter किंवा GROUP BY दुरुस्त करा.
Ravindra Bagale · ravindrabagale.com/ai-coding

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

SMART AI USE

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.

Save these cards

INTERVIEW CARDAI Coding

How do you trust an AI-written SQL query?

Give schema + DB name; test on a tiny sample with a known answer.
Check JOINs, dates, GROUP BY; EXPLAIN first.
Ravindra Bagale · ravindrabagale.com/ai-coding
COMPARISON CARDAI Coding

INNER JOIN vs LEFT JOIN

INNER: only rows with a match on both sides.
LEFT: all left rows, NULLs where no match.
Ravindra Bagale · ravindrabagale.com/ai-coding
REVISION CARDAI Coding

SQL with AI in 3

Schema, not data.
Count by hand on 5 rows.
Parameters in code, read-only user.
Ravindra Bagale · ravindrabagale.com/ai-coding