Skip to content
Fondazione ITS INCOM

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:

Exercise

All examples