Skip to main content

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:
  1. Converts natural language to SQL queries
  2. Executes queries against PostgreSQL
  3. Generates charts to visualize results
  4. Explains SQL queries in plain English
View live demo

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:
Configure environment variables:
Download and seed the database:
  1. Get the CB Insights Unicorn Companies dataset
  2. Save as unicorns.csv in project root
  3. 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:
The explanation schema:

Generate Chart Configuration

Create chart configs based on query results:
The config schema:

Frontend Integration

Use the server actions in your Next.js page:

Key Concepts

Structured Output

Using Output.object() ensures the model returns properly formatted data:

Schema Descriptions

Add .describe() to schema fields to guide the model:

Chain of Thought

Asking for description and takeaway first helps the model generate better configs:

Running the Application

Try these queries:
  • “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

  1. Schema Context: Provide complete table schema in system prompt
  2. Edge Cases: Document data quirks (comma-separated fields, null handling)
  3. Constraints: Explicitly state allowed operations (e.g., no DELETE/UPDATE)
  4. Examples: Include example queries for complex patterns
  5. 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

Resources