SQL Query
This notebook walks through how to load and run a chain that constructs SQL queries that can be run against your database to answer a question. Note that this ONLY constructs the query and does not run it.
from langchain.chains import create_sql_query_chain
from langchain.chat_models import ChatOpenAI
from langchain.utilities import SQLDatabase
API Reference:
- create_sql_query_chain from
langchain.chains
- ChatOpenAI from
langchain.chat_models
- SQLDatabase from
langchain.utilities
db = SQLDatabase.from_uri("sqlite:///../../../../notebooks/Chinook.db")
chain = create_sql_query_chain(ChatOpenAI(temperature=0), db)
response = chain.invoke({"question":"How many employees are there"})
print(response)
SELECT COUNT(*) FROM Employee
db.run(response)
'[(8,)]'