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.

Apr 09, 2025 - 12:17
Updated: 
109.4k

Generative AI & LLMs in AI & Data · Tutorial

Data Analytics & Data Science

Generative AI & AI Infrastructure, lesson 5 of 14

Using an LLM With RAG to Query Databases Safely (Text-to-SQL)

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?

StepComponentWhat happens
1User interfaceUser asks a question in plain language
2RetrieverFinds relevant table descriptions, columns and example queries from an index
3LLMWrites one SQL query from the question and retrieved context
4ValidatorChecks the query is a single read-only statement on allowed tables
5DatabaseRuns it under a read-only role with limits
6ResponseShows 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 riskHow it shows up in text-to-SQLControl
LLM01 Prompt InjectionA question or stored text tells the model to ignore rules or query other tablesPermissions enforced in the database, not in the prompt
LLM05 Improper Output HandlingGenerated SQL is run without checksValidation, read-only role, allowlisted tables
LLM06 Excessive AgencyThe tool can write, delete or change schemaGrant SELECT only; no admin accounts
LLM02 Sensitive Information DisclosureQueries return personal data the user should not seeViews that exclude sensitive columns; row-level rules
LLM10 Unbounded ConsumptionHuge joins exhaust the databaseTimeouts, 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

Frequently Asked Questions

A system where retrieval finds the relevant schema and example queries, and a large language model uses them to turn a plain-language question into SQL.

Large schemas do not fit well in a prompt. Retrieving only relevant tables keeps prompts small, reduces confusion and limits what the model sees.

Only with controls: a read-only account limited to approved tables or views, query validation, row limits, timeouts and logging. Treat generated SQL as untrusted.

A crafted question or text stored in the database can steer the model into querying other data, which is why OWASP lists it as LLM01:2025.

Yes. Grant SELECT only on the needed tables or views, set transactions to read-only and add a statement timeout so mistakes cannot change data.

They help catch obvious problems but are easy to bypass. Database permissions and an authorizer or read-only role should be the final barrier.

In a secrets manager or environment configuration outside the code, never in prompts, the retrieval index or source files.

Mainly prompt injection, sensitive information disclosure, improper output handling, excessive agency and unbounded consumption from the 2025 OWASP Top 10 for LLM Applications.

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Wow Wow 0
Sad Sad 0
Angry Angry 0
Vaishnavi

Vaishnavi is a skilled tech professional at the Ethical Hacking Training Institute in Pune, responsible for managing and optimizing the technical infrastructure that supports advanced cybersecurity education. With deep expertise in network security, backend operations, and system performance, she ensures that practical labs, online modules, and assessments run smoothly and securely. Her behind-the-scenes contributions play a vital role in delivering a seamless and secure learning experience for aspiring ethical hackers.