Examples · Programming
SQL from plain English
Describe in words the data you want, let Qwen3-Coder write the SQL, run it, and check it against an answer you worked out yourself.
Intermediate · 40 min
What you need
A key and the openai library, as in Your first API call in Python. SQLite comes with Python.
The model
Qwen3-Coder 30B (qwen3-coder-30b). It writes good SQL, but it does not see your data: you give it the tables, and you check the result.
The program
It builds a small school database in memory, asks the model for a query and runs it.
import os
import re
import sqlite3
from openai import OpenAI
client = OpenAI(
base_url="https://api.ai.itsincom.org/v1",
api_key=os.environ["API_KEY"],
)
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE students (id INTEGER PRIMARY KEY, name TEXT, course TEXT);
CREATE TABLE grades (student_id INTEGER REFERENCES students(id), subject TEXT, grade INTEGER);
INSERT INTO students VALUES
(1, 'Giulia', 'Cloud & Cybersecurity'), (2, 'Marco', 'Cloud & Cybersecurity'),
(3, 'Sara', 'Programming'), (4, 'Luca', 'Programming'), (5, 'Elena', 'Programming');
INSERT INTO grades VALUES
(1, 'Networks', 28), (1, 'Linux', 30), (2, 'Networks', 24), (2, 'Linux', 22),
(3, 'Python', 27), (3, 'Databases', 25), (4, 'Python', 18),
(5, 'Python', 30), (5, 'Databases', 29);
""")
tables = "\n".join(row[0] for row in db.execute("SELECT sql FROM sqlite_master WHERE type = 'table'"))
question = "For each course, the average grade rounded to one decimal, highest first."
answer = client.chat.completions.create(
model="qwen3-coder-30b",
temperature=0,
messages=[
{"role": "system", "content": "You write SQLite queries. Answer with one query in a ```sql block, nothing else."},
{"role": "user", "content": f"Tables:\n{tables}\n\nQuestion: {question}"},
],
)
text = answer.choices[0].message.content
block = re.search(r"```(?:sql|sqlite)?\s*(.*?)```", text, re.S | re.I)
query = block.group(1) if block else text
print(query)
for row in db.execute(query):
print(row)
Check it
Work the answer out by hand first, then compare:
- Cloud & Cybersecurity: 28, 30, 24 and 22 → 26.0
- Programming: 27, 25, 18, 30 and 29 → 25.8
Exercise
- The question has a trap. “The average grade” can be the average of all the grades, or the average of the students' averages. For Programming the second one is 24.5, not 25.8. Ask for it explicitly and look at how the query changes. Which one did you mean?
- Ask for the best student of each course with their average (Giulia 29.0, Elena 29.5).
- Ask the model to explain its query line by line.
- On a real database, never run a query you have not read: a model can write a
DELETEtoo. To be safe, open the database read only:sqlite3.connect("file:school.db?mode=ro", uri=True).
