0Pricing
AI Agents · Lesson

Generating and Validating SQL Queries

Prompt patterns for safe SQL: SELECT-only mode, parameterized queries.

The SQL Generation Goal

Generating a SQL query is only half the job. Before executing against a real database, you need to validate the query is safe, syntactically correct, and does exactly what the user intended.

This lesson covers SELECT-only enforcement, parsing, safe execution, and explain-plan verification.

SELECT-Only Mode Enforcement

The most dangerous thing a NL-to-SQL agent can do is execute a destructive statement. Always enforce SELECT-only mode regardless of what the LLM returns.

A naive string check is insufficient — use a proper SQL parser.

import sqlparse

def is_select_only(sql):
    parsed = sqlparse.parse(sql)
    if not parsed:
        return False
    for statement in parsed:
        stmt_type = statement.get_type()
        if stmt_type != 'SELECT':
            print(f'Blocked statement type: {stmt_type}')
            return False
    return True

# Test
print(is_select_only('SELECT * FROM users'))  # True
print(is_select_only('DROP TABLE users'))      # False — Blocked

All lessons in this course

  1. How NL-to-SQL Agents Work
  2. Schema Understanding and Injection
  3. Generating and Validating SQL Queries
  4. Handling Ambiguous Database Questions
← Back to AI Agents