Query a SQL database in plain English — natural language in, SQL out, answers back in human-readable form.
Intermediate ~20 minLangChain provides powerful tools to interact with your databases using natural language. This application demonstrates how to create a chat interface that allows users to query databases using conversational language instead of SQL.
| Column | Type | Constraints |
|---|---|---|
| CustomerId | INTEGER | PRIMARY KEY |
| FirstName | NVARCHAR(40) | NOT NULL |
| LastName | NVARCHAR(20) | NOT NULL |
| Country | NVARCHAR(40) | |
| NVARCHAR(60) | NOT NULL |
| Column | Type | Constraints |
|---|---|---|
| InvoiceId | INTEGER | PRIMARY KEY |
| CustomerId | INTEGER | FOREIGN KEY |
| InvoiceDate | DATETIME | NOT NULL |
| BillingCountry | NVARCHAR(40) | |
| Total | NUMERIC(10,2) | NOT NULL |
| Column | Type | Constraints |
|---|---|---|
| ArtistId | INTEGER | PRIMARY KEY |
| Name | NVARCHAR(120) |
| Column | Type | Constraints |
|---|---|---|
| AlbumId | INTEGER | PRIMARY KEY |
| Title | NVARCHAR(160) | NOT NULL |
| ArtistId | INTEGER | FOREIGN KEY |
Key relationships in the Chinook database:
LangChain provides a specialized toolkit for SQL database interactions through its
SQLDatabaseToolkit. This toolkit
contains several tools that enable an AI agent to query and interact with SQL databases.
The language model (like GPT-4) acts as the bridge between natural language and SQL. It:
⚠️ Important Security Warning
Building Q&A systems for SQL databases requires executing model-generated SQL queries. There are inherent risks in doing this:
The user enters a natural language question about the database data.
The system uses ListSQLDatabaseTool and InfoSQLDatabaseTool to understand the database structure.
The LLM converts the natural language question into a SQL query based on the schema.
The QuerySQLCheckerTool validates the SQL query for errors and potential improvements.
The QuerySQLDataBaseTool executes the SQL query against the database.
The LLM translates the raw query results into a natural language response.
Which country's customers spent the most?
Who are the top 3 best selling artists?
What's the most popular music genre by sales?
Which customer has purchased the most tracks?
What was the highest sales month in 2021?
Which employee has the highest sales through their customers?
Built with LangChain, Python, and modern web technologies.
⚠️ Security Note: Always implement proper permissions and validation when connecting LLMs to databases.