Natural Language to Postgres
Learn how to build an application that lets users query a PostgreSQL database using natural language, with automatic chart generation and query explanations.What You’ll Build
An application that:- Converts natural language to SQL queries
- Executes queries against PostgreSQL
- Generates charts to visualize results
- Explains SQL queries in plain English
Prerequisites
- Node.js 18+
- PostgreSQL database (Vercel Postgres recommended)
- Vercel AI Gateway API key
- Basic knowledge of SQL and Next.js
Setup
Clone the starter repository:- Get the CB Insights Unicorn Companies dataset
- Save as
unicorns.csvin project root - Run:
pnpm run seed
Implementation
Generate SQL from Natural Language
Create a server action that converts questions to SQL:Execute Generated Queries
Run the SQL query against your database:Explain SQL Queries
Generate plain English explanations of SQL queries:Generate Chart Configuration
Create chart configs based on query results:Frontend Integration
Use the server actions in your Next.js page:Key Concepts
Structured Output
UsingOutput.object() ensures the model returns properly formatted data:
Schema Descriptions
Add.describe() to schema fields to guide the model:
Chain of Thought
Asking fordescription and takeaway first helps the model generate better configs:
Running the Application
- “How many unicorns are from San Francisco?”
- “What are the top 5 industries by total valuation?”
- “Show me the growth of unicorns over time”
Best Practices
- Schema Context: Provide complete table schema in system prompt
- Edge Cases: Document data quirks (comma-separated fields, null handling)
- Constraints: Explicitly state allowed operations (e.g., no DELETE/UPDATE)
- Examples: Include example queries for complex patterns
- Validation: Always validate and sanitize generated SQL
Next Steps
- Add support for JOINs across multiple tables
- Implement query result caching
- Add query history and favorites
- Support more chart types
- Add export to CSV/PDF