πŸ“ Text-to-SQL with Vanna.AI and Python

Convert natural language into SQL queries and unlock your data with ease.

Summary: In this tutorial, we’ll explore how to use Vanna.AI with Python to transform plain English questions into working SQL queries that you can run on your database. Think of it as ChatGPT for your data warehouse!

πŸ” What is Vanna.AI?

Vanna.AI is an open-source AI-powered SQL agent. It allows you to:

This makes it a great choice for self-service analytics, BI integration, and RAG-style data chatbots.

βš™οΈ Setting Up Vanna.AI with Python

1. Install the library

pip install vanna

2. Import and initialize

from vanna.openai import VannaOpenAI
from vanna.vannadb import VannaDB

# Initialize Vanna with API key
vn = VannaOpenAI(api_key="YOUR_VANNA_API_KEY")

# Connect to your database (PostgreSQL example)
db = VannaDB(db_url="postgresql://user:password@localhost:5432/mydb")

πŸ“ Natural Language β†’ SQL

question = "Show me the top 5 customers by total sales in 2024"

# Generate SQL from natural language
sql_query = vn.generate_sql(question)

print("Generated SQL:", sql_query)
Example output:
SELECT customer_name, SUM(sales) as total_sales
FROM orders
WHERE EXTRACT(YEAR FROM order_date) = 2024
GROUP BY customer_name
ORDER BY total_sales DESC
LIMIT 5;

▢️ Running SQL Queries

# Execute generated SQL on DB
results = db.run(sql_query)

# Print results
for row in results:
    print(row)

πŸ’‘ End-to-End Example

question = "List the average transaction amount per customer in 2023"

sql_query = vn.generate_sql(question)
print("SQL:", sql_query)

results = db.run(sql_query)
print("Results:", results)

πŸ“Š Real-World Use Cases

πŸš€ Final Thoughts

Vanna.AI bridges the gap between natural language and SQL. By combining LLM-powered query generation with direct database execution, it empowers teams to unlock insights faster.

Question for you: Would you integrate text-to-SQL in your next analytics project?

← Back to Blog Index