SQL Parsing and Validation for LLMs: A Comprehensive Guide
From the publisher’s feed, collected in the ZeroLabs newsroom.
Ensuring data integrity and security in automated SQL generation workflowsPhoto by Author (Gemini)Modern Large Language Models (LLMs) are incredibly powerful at reasoning and automating complex workflows. However, blindly executing the SQL they generate is a major security and reliability risk.The “Hallucination” ProblemLLMs are designed to predict the next most likely token, not to verify facts. If you ask an LLM for the capital of India and if it says “New York,” you’d immediately know it’s wrong because you have the context. But in a complex database environment, a generated SQL query might look correct while containing dangerous errors — like referencing non-existent tables or, worse, including destructive DROP statements.The Risks of Raw SQL Generation:Security Vulnerabilities: Unauthorized DELETE or DROP commands could wipe your data.Schema Mismatches: The LLM might “hallucinate” table or column names that aren’t in your schema.Performance Issues: A poorly written query could trigger massive joins that crash your database.This is why SQL validation is a non-negotiable step in any AI-powered data application.Building a Validator with sqlparseIn our previous guide, we covered how to transform natural language into SQL. Now, let’s look at how to protect your database by parsing that SQL before it ever runs.We will use the sqlparse library, a powerful non-validating SQL parser for Python that allows us to inspect the structure of a query.1. InstallationYou can install sqlparse using uv or any standard package manager:uv add sqlparseOr add it to your pyproject.toml dependencies and run uv sync:dependencies = [ "sqlparse>=0.5.5",]2. Understanding SQL ParsingThe core of sqlparse is the parse() function. It converts a raw SQL string into a structured, tree-like representation called an Abstract Syntax Tree (AST).Example: Analyzing a SELECT Query# sql_parse.pyimport sqlparsequery = "SELECT c.customer_id, c.name FROM customers c;"parsed = sqlparse.parse(query)stmt = parsed[0]# Visualize the tree structurestmt._pprint_tree()Output Breakdown:The parser identifies the first layer of the query:DML (Data Manipulation Language): 'SELECT'IdentifierList: 'c.customer_id, c.name' (The columns being requested)Keyword: 'FROM'Identifier: 'customers c' (The table name and its alias)C:\sainathudata\projects\simple_sql_query_generator>uv run sql_parse.py|- 0 DML 'SELECT'|- 1 Whitespace ' '|- 2 IdentifierList 'c.cust...'| |- 0 Identifier 'c.cust...'| | |- 0 Name 'c'| | |- 1 Punctuation '.'| | `- 2 Name 'custom...'| |- 1 Punctuation ','| |- 2 Whitespace ' '| `- 3 Identifier 'c.name'| |- 0 Name 'c'| |- 1 Punctuation '.'| `- 2 Name 'name'|- 3 Whitespace ' '|- 4 Keyword 'FROM'|- 5 Whitespace ' '|- 6 Identifier 'custom...'| |- 0 Name 'custom...'| |- 1 Whitespace ' '| `- 2 Identifier 'c'| `- 0 Name 'c'`- 7 Punctuation ';'3. Implementing a Robust SQL ValidatorTo bridge the gap between “parsed SQL” and “safe SQL,” we can encapsulate our logic into a SQLValidator class. This implementation specifically targets common security risks like multi-statement injection and destructive commands, with added support for T-SQLKey Features of this Validator:Anti-Injection Logic: It strictly forbids mid-query semicolons, which are a common vector for “Piggybacking” SQL injection attacks.Token Flattening: Unlike a simple string search (which might accidentally block a column named created_at because it contains at), this uses statement.flatten() to inspect actual SQL keywords.Table Allowlisting: You can provide a list of “safe” tables. If the LLM tries to query a system_settings or users table that wasn't in your prompt, the validator will block it.CTE Support: By allowing UNKNOWN statement types, it supports Common Table Expressions (WITH clauses), which are frequently used by modern LLMs for complex data retrieval.T-SQL Compatibility: The _clean_name method ensures that queries using MSSQL brackets (e.g., FROM [dbo].[Sales]) are parsed correctly.Pro Tip: Always use this validator in conjunction with database-level permissions (Least Privilege Principle). The validator is your first line of defense, but the database user should also only have READ access to the necessary tables.# sql_validator.pyimport sqlparsefrom sqlparse.sql import IdentifierList, Identifier, TokenListfrom sqlparse.tokens import Keyword, DML, Namefrom typing import Tuple, List, Setclass SQLValidator: """Validates and sanitizes T-SQL queries for MSSQL.""" # Use whole-word matching to avoid blocking columns like "created_at" DANGEROUS_KEYWORDS = { 'DROP', 'DELETE', 'TRUNCATE', 'ALTER', 'CREATE', 'INSERT', 'UPDATE', 'GRANT', 'REVOKE', 'EXEC', 'EXECUTE', 'INTO' } def __init__(self, allowed_tables: List[str] = None): self.allowed_tables = {t.lower() for t in allowed_tables} if allowed_tables else None def validate(self, query: str) -> Tuple[bool, str]: # 1. Basic Syntax & Semicolon check if query.count(';') > 1 or (';' in query and not query.strip().endswith(';')): return False, "Multiple statements or mid-query semicolons detected" try: parsed = sqlparse.parse(query) if not parsed: return False, "Invalid SQL syntax" statement = parsed[0] except Exception as e: return False, f"Parse error: {str(e)}" # 2. Keyword Check (Token-based to avoid substring issues) for token in statement.flatten(): if token.ttype in Keyword or token.ttype in DML: val = token.value.upper() if val in self.DANGEROUS_KEYWORDS: return False, f"Dangerous operation detected: {val}" # 3. Ensure SELECT or WITH (for CTEs) st_type = statement.get_type() if st_type not in ['SELECT', 'UNKNOWN']: # CTEs often show as UNKNOWN return False, f"Only SELECT queries are allowed (Detected: {st_type})" # 4. Extract and Validate Tables (Handles JOINs) if self.allowed_tables: found_tables = self._extract_tables(statement) for table in found_tables: if table.lower() not in self.allowed_tables: return False, f"Access denied to table: {table}" return True, "Valid" def _extract_tables(self, statement) -> Set[str]: """Extracts tables from FROM and JOIN clauses, cleaning T-SQL brackets.""" tables = set() from_seen = False for token in statement.tokens: # Look for tables after FROM or JOIN if token.ttype is Keyword and token.value.upper() in ('FROM', 'JOIN', 'INNER JOIN', 'LEFT JOIN', 'RIGHT JOIN'): from_seen = True continue if from_seen: if isinstance(token, IdentifierList): for identifier in token.get_identifiers(): tables.add(self._clean_name(identifier.get_real_name())) from_seen = False elif isinstance(token, Identifier): tables.add(self._clean_name(token.get_real_name())) from_seen = False elif token.ttype is Keyword: # End of table list from_seen = False return {t for t in tables if t} def _clean_name(self, name: str) -> str: """Removes MSSQL square brackets [table].""" if not name: return name return name.strip('[]').strip('"') def format_query(self, query: str) -> str: return sqlparse.format(query, reindent=True, keyword_case='upper')Putting it all togetherI have pushed both sql_validator.py and the updated main_validator.py to the project GitHub repository. Note that the script below acts as a driver and requires the schema definitions established in my previous article to execute correctly.# main_validator.pyimport osfrom dotenv import load_dotenvfrom schema_extractor import SchemaExtractorfrom simple_query_generator import SimpleSQLQueryGeneratorfrom sql_validator import SQLValidator# Load environment variablesload_dotenv(override=True)def main(): # 1. Config & Connection # If running locally db_params = { "SERVER": "(localdb)\\MSSQLLocalDB", "DATABASE": "master", "Trusted_Connection": "yes", "Encrypt": "no" } """ # If using environment variables (e.g., for production) db_params = { 'host': os.getenv('DB_HOST'), 'port': os.getenv('DB_PORT'), 'database': os.getenv('DB_NAME'), 'user': os.getenv('DB_USER'), 'password': os.getenv('DB_PASSWORD') } """ # 2. Extract Schema my_tables = ["customers", "orders"] extractor = SchemaExtractor(db_params) schema_md = extractor.format_schema_for_llm(my_tables) # 3. Generate Query generator = SimpleSQLQueryGenerator() #user_question = "Show me the top 5 customers by total order amount." user_question = "Delete all the orders placed today" sql_query = generator.generate_query(user_question, schema_md) validator = SQLValidator(allowed_tables=my_tables) is_valid, error = validator.validate(sql_query) print(f"--- Database Schema ---\n{schema_md}") print(f"User Question: {user_question}\n") print(f"--- Generated SQL ---\n{sql_query}\n") print(f"Validation Result: {'Valid' if is_valid else f'Invalid: {error}'}")if __name__ == "__main__": main()Output:C:\sainathudata\projects\simple_sql_query_generator>uv run main_validator.py--- Database Schema ---# Database Schema (MSSQL)## Table: customersColumns:- customer_id: int NOT NULL (PRIMARY KEY)- name: nvarchar NULL- email: nvarchar NULL- created_at: datetime2 NULL## Table: ordersColumns:- order_id: int NOT NULL (PRIMARY KEY)- customer_id: int NULL- order_date: date NULL- total_amount: decimal NULLForeign Keys:- customer_id → customers.customer_idUser Question: Delete all the order placed today--- Generated SQL ---DELETE oFROM orders oINNER JOIN customers c ON o.customer_id = c.customer_idWHERE DATEPART(day, o.order_date) = DATEPART(day, GETDATE()) AND DATEPART(month, o.order_date) = DATEPART(month, GETDATE()) AND DATEPART(year, o.order_date) = DATEPART(year, GETDATE());Validation Result: Invalid: Dangerous operation detected: DELETEConclusionTreating LLM output as untrusted user input is a fundamental security practice. By integrating a parsing layer with sqlparse, you can automate the verification of generated queries, ensuring your AI-driven chat bots are both smart and safe.Previous Article: Building a Simple SQL Query Generator Using LLMs | by Sainath Udata | Feb, 2026 | Towards AIGitHub: sainathudata/simple_sql_query_generator_llmSQL Parsing and Validation for LLMs: A Comprehensive Guide was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.