
Building a Natural-Language-to-SQL AI Assistant with Generative AI
Learn how to build an AI assistant that converts natural-language questions into SQL queries, helping non-technical users interact with structured databases without writing SQL manually
Building a Natural-Language-to-SQL AI Assistant with Generative AI
Introduction
Databases contain valuable information, but accessing that information often requires knowledge of SQL. For non-technical users, even a simple question such as βWhich products had the highest sales last month?β may require assistance from a developer or data engineer.
Generative AI and Large Language Models (LLMs) provide an opportunity to simplify this process.
In this article, we will explore how to build a Natural-Language-to-SQL AI Assistant that accepts questions in everyday language, understands the user's intent, generates an SQL query, and returns the result in an understandable format.
The Problem
Traditional database systems expect users to understand SQL syntax.
For example, a user may need to write:
1
2
3
4
5
SELECT product_name, SUM(quantity * price) AS total_sales
FROM orders
WHERE order_date >= '2026-09-01'
GROUP BY product_name
ORDER BY total_sales DESC;A business user may not know how to write this query.
Instead, they could simply ask:
Which products generated the highest sales in September 2026?
The AI system can translate this natural-language request into SQL automatically.
ποΈ Proposed Architecture
The system can be designed using the following workflow:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
User
β
Natural Language Question
β
AI / LLM
β
Schema Understanding
β
SQL Generation
β
SQL Validation
β
Database
β
Query Result
β
AI-generated Explanation
β
UserThe important part of this architecture is that the LLM should not generate SQL blindly. It should first understand the database schema and then generate a query based on the available tables and columns.
π Step 1: Understand the Database Schema
The AI system needs information about the database before generating a query.
For example, suppose we have an e-commerce database containing:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
customers
customer_id
name
email
products
product_id
product_name
category
price
orders
order_id
customer_id
product_id
quantity
order_dateThe schema information can be provided to the LLM as context.
This helps the model understand which tables and columns are available.
π‘ Simple understanding: The database schema acts like a map that tells the AI what information exists.
π€ Step 2: Convert Natural Language into SQL
The user can ask:
1
Show me the top 5 products by sales.The LLM analyzes the intent and generates SQL similar to:
1
2
3
4
5
6
7
8
SELECT p.product_name,
SUM(o.quantity * p.price) AS total_sales
FROM orders o
JOIN products p
ON o.product_id = p.product_id
GROUP BY p.product_name
ORDER BY total_sales DESC
LIMIT 5;The generated SQL can then be passed to the database.
π‘οΈ Step 3: Validate the Generated Query
Generated SQL should not immediately be executed against a production database.
A validation layer can check:
- Whether the referenced tables exist
- Whether the referenced columns exist
- Whether the SQL syntax is valid
- Whether dangerous operations are present
- Whether the user has permission to access the requested data
For example, an application intended only for data analysis should prevent queries such as:
1
DROP TABLE customers;This validation layer provides an additional security boundary between the LLM and the database.
βοΈ Using AWS
AWS services can be used to build different parts of this architecture.
One possible architecture is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
βββββββββββββββββββ
β User β
ββββββββββ¬βββββββββ
β
βββββββββββββββββββ
β Web Interface β
ββββββββββ¬βββββββββ
β
βββββββββββββββββββ
β API / Backend β
ββββββββββ¬βββββββββ
β
βββββββββββββββββββ
β Generative AI β
β Layer β
ββββββββββ¬βββββββββ
β
βββββββββββββββββββ
β SQL Validation β
ββββββββββ¬βββββββββ
β
βββββββββββββββββββ
β Database β
βββββββββββββββββββAWS services such as Amazon Bedrock, AWS Lambda, Amazon API Gateway, and database services can be combined depending on the application requirements.
For example:
- Amazon Bedrock can provide access to foundation models.
- AWS Lambda can handle backend processing without managing servers.
- Amazon API Gateway can expose backend APIs.
- Amazon RDS can host relational databases.
- Amazon CloudWatch can be used for monitoring and logging.
The exact services can be selected based on the scale, security requirements, latency, and database architecture.
π§© Prompt Engineering
The quality of SQL generation depends heavily on how the model is instructed.
A system prompt could contain rules such as:
1
2
3
4
5
6
7
8
You are a SQL generation assistant.
Rules:
1. Use only the tables and columns provided in the schema.
2. Generate read-only SQL queries.
3. Never generate INSERT, UPDATE, DELETE, DROP, or ALTER statements.
4. Return valid SQL.
5. Ask for clarification if the user's request is ambiguous.Providing clear constraints helps reduce incorrect or unsafe queries.
π Example
Consider this user question:
1
Which customers spent more than βΉ10,000?The AI could generate:
1
2
3
4
5
6
7
8
9
10
SELECT c.name,
SUM(o.quantity * p.price) AS total_spent
FROM customers c
JOIN orders o
ON c.customer_id = o.customer_id
JOIN products p
ON o.product_id = p.product_id
GROUP BY c.customer_id, c.name
HAVING SUM(o.quantity * p.price) > 10000
ORDER BY total_spent DESC;The application can execute the query and transform the result into a simple response:
1
2
3
4
5 customers spent more than βΉ10,000.
Top customer:
Customer A β βΉ18,450This makes database analytics much more accessible to non-technical users.
π Important Security Considerations
Natural-Language-to-SQL systems need strong security controls because the LLM interacts with potentially sensitive data.
Some important practices include:
- Use read-only database credentials whenever possible.
- Validate generated SQL before execution.
- Apply database permissions so users can access only authorized information.
- Limit query execution time and result size to prevent expensive queries.
- Avoid exposing sensitive schema information unnecessarily.
- Log queries and system activity for monitoring and debugging.
The LLM should be treated as an untrusted component rather than as a security boundary.
π Future Improvements
The system can be extended with several advanced capabilities.
Multi-database Support
The assistant could support PostgreSQL, MySQL, Amazon Aurora, and other relational databases.
Conversational Queries
Users could ask follow-up questions such as:
1
Show sales by category.followed by:
1
Only for September.The system would maintain the previous context and generate a new query.
Automatic Visualization
After executing a query, the AI could determine whether the result is better represented as a table, bar chart, line chart, or another visualization.
Query Explanation
The system could explain the generated SQL in simple language so that users can understand what the AI executed.
π― Conclusion
Natural-Language-to-SQL systems can make structured data significantly more accessible by allowing users to interact with databases using everyday language.
Combining Generative AI with AWS services provides a flexible foundation for building these applications. However, successful implementation requires more than simply connecting an LLM to a database. Schema awareness, SQL validation, access control, monitoring, and careful prompt design are essential for building a reliable system.
Generative AI can therefore act as an interface between humans and structured data, reducing the technical barrier to database analytics while maintaining appropriate security and control.
#AWS #GenerativeAI #AmazonBedrock #SQL #ArtificialIntelligence
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article