Using an LLM With RAG to Query Databases Safely (Text-to-SQL)
To let users chat with a database, a text-to-SQL system uses retrieval-augmented generation (RAG) to find the parts of the schema relevant to a question, such as table and column descriptions and example queries. It passes those to a large language model (LLM), which writes a SQL query. Your application then validates the query, runs it with a read-only database account, and returns the results.
Topic: Generative AI & LLMs in AI & Data · Tutorial
Also covers: Data Analytics & Data Science
Learning path: Generative AI & AI Infrastructure, lesson 5 of 14
Quick answer: To let users chat with a database, a text-to-SQL system uses retrieval-augmented generation (RAG) to find the parts of the schema relevant to a question, such as table and column descriptions and example queries. It passes those to a large language model (LLM), which writes a SQL query. Your application then validates the query, runs it with a read-only database account, and returns the results. Treat the generated SQL as untrusted input: the OWASP Top 10 for LLM Applications 2025 lists prompt injection and improper output handling as leading risks, so permissions and validation must hold even when the model is fooled.
Key takeaways
- RAG retrieves only the relevant schema, so prompts stay small and accurate.
- Generated SQL is untrusted output; validate it before running it.
- Run queries with a read-only account that can see only approved tables.
- Add row limits, timeouts and logging to every query.
- Prompt injection can come from user questions or from data in the database itself.
Table of Contents
- How Does an LLM With RAG Query a Database?
- What Should the Retrieval Step Return?
- What Are the Main Security Risks?
- How Do You Set Up a Read-Only Database User?
- How Do You Validate Generated SQL?
- What Does a Safe Python Runner Look Like?
- How Do You Run It Responsibly in Production?
- References
How Does an LLM With RAG Query a Database?
| Step | Component | What happens |
|---|---|---|
| 1 | User interface | User asks a question in plain language |
| 2 | Retriever | Finds relevant table descriptions, columns and example queries from an index |
| 3 | LLM | Writes one SQL query from the question and retrieved context |
| 4 | Validator | Checks the query is a single read-only statement on allowed tables |
| 5 | Database | Runs it under a read-only role with limits |
| 6 | Response | Shows results, and ideally the SQL, to the user |
What Should the Retrieval Step Return?
Large databases have too many tables to fit in a prompt. The retriever stores short documents describing each table: its purpose, column names and types, join keys, and two or three verified example queries. At question time it returns the closest matches. Keep this index limited to tables the user is allowed to query, and never include real customer records, credentials or connection strings in it. OWASP lists sensitive information disclosure as LLM02:2025.
What Are the Main Security Risks?
| OWASP 2025 risk | How it shows up in text-to-SQL | Control |
|---|---|---|
| LLM01 Prompt Injection | A question or stored text tells the model to ignore rules or query other tables | Permissions enforced in the database, not in the prompt |
| LLM05 Improper Output Handling | Generated SQL is run without checks | Validation, read-only role, allowlisted tables |
| LLM06 Excessive Agency | The tool can write, delete or change schema | Grant SELECT only; no admin accounts |
| LLM02 Sensitive Information Disclosure | Queries return personal data the user should not see | Views that exclude sensitive columns; row-level rules |
| LLM10 Unbounded Consumption | Huge joins exhaust the database | Timeouts, row limits, rate limits |
Indirect prompt injection matters too: stored text, such as a customer comment, can be read back into a later prompt. The OWASP SQL Injection Prevention Cheat Sheet also recommends least privilege for every database account, which applies fully to LLM tools.
How Do You Set Up a Read-Only Database User?
In PostgreSQL, create a dedicated role, give it SELECT only on approved tables or views, and set default_transaction_read_only and statement_timeout for it:
CREATE ROLE llm_reader LOGIN;
GRANT CONNECT ON DATABASE sales TO llm_reader;
GRANT USAGE ON SCHEMA reporting TO llm_reader;
GRANT SELECT ON reporting.orders_summary TO llm_reader;
ALTER ROLE llm_reader SET default_transaction_read_only = on;
ALTER ROLE llm_reader SET statement_timeout = '5s';
Set the password separately through your secrets manager, never in code or prompts.
How Do You Validate Generated SQL?
- Allow exactly one statement, and only SELECT.
- Check every referenced table against an allowlist.
- Enforce a maximum number of returned rows.
- Reject queries that touch system catalogues or attach other databases.
- Log the question, retrieved context, SQL and outcome for review.
Text checks with regular expressions are easy to bypass, so rely on the database engine's own permissions as the final barrier.
What Does a Safe Python Runner Look Like?
This tested example uses Python's sqlite3 module. It opens the file read-only and installs an authorizer that permits only reads, and blocks one sensitive table. The LLM call is left out; pass its SQL to this function.
import sqlite3
ALLOWED = {sqlite3.SQLITE_SELECT, sqlite3.SQLITE_READ, sqlite3.SQLITE_FUNCTION}
BLOCKED_TABLES = {'customers_pii'}
def authorizer(action, arg1, arg2, db_name, trigger):
if action not in ALLOWED:
return sqlite3.SQLITE_DENY
if action == sqlite3.SQLITE_READ and arg1 in BLOCKED_TABLES:
return sqlite3.SQLITE_DENY
return sqlite3.SQLITE_OK
def run_generated_sql(db_path, sql, max_rows=200):
conn = sqlite3.connect('file:' + db_path + '?mode=ro', uri=True)
try:
conn.set_authorizer(authorizer)
cur = conn.execute(sql) # raises if sql holds more than one statement
return cur.fetchmany(max_rows)
finally:
conn.close()
In testing, a GROUP BY query returned results, while DELETE, ATTACH, PRAGMA, a second chained statement and any read of the blocked table raised errors.
How Do You Run It Responsibly in Production?
Start with a small set of approved views, review logs weekly, and test with adversarial questions before launch. NIST's Generative AI Profile (AI 600-1) covers risk management practices for such systems. If personal data is in scope, India's DPDP Act, 2023 applies to how it is processed. For background, read our guides to prompt injection in generative AI and whether ChatGPT writes better SQL than an analyst. For hands-on learning, ask about AI security training.
References
- OWASP Top 10 for LLM Applications 2025
- OWASP LLM01:2025 Prompt Injection
- OWASP LLM05:2025 Improper Output Handling
- OWASP LLM06:2025 Excessive Agency
- OWASP LLM02:2025 Sensitive Information Disclosure
- OWASP SQL Injection Prevention Cheat Sheet
- PostgreSQL GRANT
- PostgreSQL client connection defaults
- Python sqlite3 documentation
- NIST AI 600-1
Frequently Asked Questions
What's Your Reaction?
Like
0
Dislike
0
Love
0
Funny
0
Wow
0
Sad
0
Angry
0