A SQL Assistant for Your DB
Give the model a schema, let it write SQL, run it against a sandboxed DB, and explain the results.
A SQL Assistant for Your DB is a free AI Agents lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Agents learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Project Goal
Build an agent that turns natural-language questions into SQL, executes against a sandboxed DB, and explains the results.
The bread-and-butter "talk to my database" agent.
Architecture
- User: "How many active users this month?"
- Agent calls list_tables and describe_table to learn schema
- Agent calls run_sql with the generated query
- Agent explains the result in natural language
Step 1: Schema Tools
import psycopg
conn = psycopg.connect(DATABASE_URL)
def list_tables():
with conn.cursor() as cur:
cur.execute("SELECT table_name FROM information_schema.tables WHERE table_schema='public'")
return [r[0] for r in cur.fetchall()]
def describe_table(name):
with conn.cursor() as cur:
cur.execute('''
SELECT column_name, data_type FROM information_schema.columns
WHERE table_name = %s
''', (name,))
return cur.fetchall()Step 2: A SAFE run_sql Tool
You must restrict what the agent can do — read-only, query timeout, row limit:
import re
def run_sql(query: str, limit: int = 100):
q = query.strip().rstrip(';').lower()
if not q.startswith('select'):
return {'error': 'Only SELECT statements are allowed.'}
if any(bad in q for bad in [' drop ', ' delete ', ' update ', ' insert ', ' alter ', ' truncate ']):
return {'error': 'Statement contains a disallowed keyword.'}
with conn.cursor() as cur:
cur.execute(f'SET statement_timeout = 5000') # 5 seconds
cur.execute(f'SELECT * FROM ({query}) sub LIMIT {limit}')
cols = [c.name for c in cur.description]
rows = cur.fetchall()
return {'columns': cols, 'rows': rows}Tool Definitions
tools = [
{'type': 'function', 'function': {'name': 'list_tables', 'description': 'List tables in the database', 'parameters': {'type': 'object', 'properties': {}}}},
{'type': 'function', 'function': {'name': 'describe_table', 'description': 'Get columns of a table', 'parameters': {'type': 'object', 'properties': {'name': {'type': 'string'}}, 'required': ['name']}}},
{'type': 'function', 'function': {'name': 'run_sql', 'description': 'Execute a SELECT query (read-only, max 100 rows, 5s timeout)', 'parameters': {'type': 'object', 'properties': {'query': {'type': 'string'}}, 'required': ['query']}}}
]
import json
print(json.dumps(tools, indent=2))
System Prompt
system = '''
You are a SQL analyst assistant for a Postgres database.
First use list_tables and describe_table to learn the schema.
Then write a single SELECT query to answer the user.
Never modify data.
After receiving results, explain them in plain language.
'''
print(system.strip())
Pass Schema in System Prompt
For better latency, fetch the schema once at startup and put it in the system prompt — saves tool round-trips:
schema = ''
for t in list_tables():
cols = describe_table(t)
schema += f'{t}: {cols}\n'
system = system + f'\nSchema:\n{schema}'Read-Only Database User
Even with code checks, also create a read-only DB user with permissions only on the analytic schema. Defense in depth.
PII Masking
Some columns (email, phone) should never leak. Mask them in the results before returning:
PII_COLS = {'email', 'phone'}
for row in rows:
for i, col in enumerate(cols):
if col in PII_COLS:
row[i] = '[REDACTED]'Query Cost Estimation
Use EXPLAIN to estimate query cost; reject queries with cost > threshold (prevents accidental full-table scans on huge tables).
Sample Conversation
User: "Top 5 customers by spend last month"
Agent:
- list_tables -> [users, orders, ...]
- describe_table(orders) -> [id, user_id, total, created_at]
- run_sql("SELECT user_id, SUM(total) ...")
- Returns: "Alice ($1240), Bob ($910), ..."
Output Charts
For richer UX, add a render_chart tool that takes columns + rows and returns a chart image URL. The agent can call it after a query.
Fail Gracefully
SQL errors are common. Return the Postgres error message verbatim — the model is excellent at fixing its own broken SQL when shown the error.
Audit Every Query
Log the user, the natural-language question, the generated SQL, and the result count. Audits are non-negotiable for DB access agents.
Why Restrict to SELECT?
Why hard-code the agent to only run SELECT statements?
Recap
SQL agents are immediately valuable. Build them carefully — read-only user, statement timeout, row limit, query type whitelist, audit log.
Frequently asked questions
Is the “A SQL Assistant for Your DB” lesson free?
Yes — the full text of “A SQL Assistant for Your DB” is free to read here on the web, and the AI Agents course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Agents course, upgrade to CoddyKit PRO.
What will I learn in “A SQL Assistant for Your DB”?
Give the model a schema, let it write SQL, run it against a sandboxed DB, and explain the results. You practise AI Agents with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start AI Agents?
No prior experience is required. AI Agents on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “A SQL Assistant for Your DB” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this AI Agents lesson?
Yes. Every AI Agents lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- A Q&A Bot Over Your Documents
- A Code-Explainer Agent
- A Web-Browsing Research Agent
- A SQL Assistant for Your DB