Build This Project · AI Portfolio

Natural-Language-to-SQL Analytics Assistant for Your AI Portfolio

Build an NL-to-SQL analytics assistant that demonstrates your ability to work with LLMs, databases, and AI-powered data querying.

Tracks
NL to SQL · Live Interactive
Project Focus
What you'll build
Skills Demonstrated
Key competencies
Employer Interest
Value to employer
Design DB LLM Query Gen App Portfolio
Click to see the project overview — an NL-to-SQL assistant that will make your AI portfolio stand out.

Home / Tutorials / Project Guides / Natural-Language-to-SQL Analytics Assistant

Build This Project · AI Portfolio

Natural-Language-to-SQL Analytics Assistant — Complete Project Guide

LLM DB APP PORTFOLIO LLM NL to SQL Query generation GPT-4/Claude Database PostgreSQL/SQLite Schema design Sample data App Streamlit UI Query results End-to-end Portfolio Showcase work Get hired Offer
An NL-to-SQL assistant bridges the gap between natural language and data — a highly sought-after AI skill.

Quick summary — build a natural-language-to-SQL analytics assistant

Natural-language-to-SQL is a game-changing AI capability. This project demonstrates your ability to build a system that translates English questions into SQL queries and returns data — exactly what companies need to democratize data access.

In this guide you will learn:

  1. Project overview — what you'll build and why.
  2. Database design — schema and sample data.
  3. NL to SQL generation — using LLMs.
  4. Query execution — running SQL and showing results.
  5. Building the app — Streamlit interface.
  6. Portfolio presentation — how to show it to employers.

SECTION 01Project overview

Here's what you'll build in this project:

  • Business problem: Non-technical users need to query data but don't know SQL. Writing SQL queries is a barrier to data access.
  • Your solution: An assistant that converts natural language questions into SQL queries and displays results.
  • Tools: Python, OpenAI/Claude API, SQLite/PostgreSQL, Streamlit.
  • Outcome: A portfolio-ready AI application that demonstrates LLM integration, SQL generation, and data access.
Key insight: NL-to-SQL is a rapidly growing field — companies are investing heavily in making data accessible to everyone.

SECTION 02Database design

Here's how to design your database schema:

-- Sales database schema
CREATE TABLE customers (
    customer_id INTEGER PRIMARY KEY,
    name TEXT,
    email TEXT,
    city TEXT,
    signup_date DATE
);

CREATE TABLE products (
    product_id INTEGER PRIMARY KEY,
    name TEXT,
    category TEXT,
    price DECIMAL(10,2)
);

CREATE TABLE orders (
    order_id INTEGER PRIMARY KEY,
    customer_id INTEGER,
    product_id INTEGER,
    quantity INTEGER,
    order_date DATE,
    total_amount DECIMAL(10,2),
    FOREIGN KEY (customer_id) REFERENCES customers(customer_id),
    FOREIGN KEY (product_id) REFERENCES products(product_id)
);

CREATE TABLE employees (
    employee_id INTEGER PRIMARY KEY,
    name TEXT,
    department TEXT,
    hire_date DATE,
    salary DECIMAL(10,2)
);
schema.sql

SECTION 03NL to SQL generation

Here's how to generate SQL from natural language:

import openai

def generate_sql(question, schema):
    prompt = f"""You are a SQL expert. Convert the following natural language question into a SQL query.

    Database Schema:
    {schema}

    Question: {question}

    SQL Query:
    """

    response = openai.ChatCompletion.create(
        model="gpt-4",
        messages=[{"role": "user", "content": prompt}]
    )

    sql = response.choices[0].message.content.strip()

    # Clean up SQL (remove markdown formatting)
    if sql.startswith('```sql'):
        sql = sql.split('```sql')[1].split('```')[0].strip()
    elif sql.startswith('```'):
        sql = sql.split('```')[1].split('```')[0].strip()

    return sql

# Example
schema = """
customers: customer_id, name, email, city, signup_date
products: product_id, name, category, price
orders: order_id, customer_id, product_id, quantity, order_date, total_amount
employees: employee_id, name, department, hire_date, salary
"""

question = "What are the total sales by product category?"
sql = generate_sql(question, schema)
print(sql)
nl-to-sql.py

SECTION 04Query execution

Here's how to execute SQL and return results:

import sqlite3
import pandas as pd

def execute_query(sql):
    conn = sqlite3.connect('sales.db')
    try:
        df = pd.read_sql_query(sql, conn)
        return df
    except Exception as e:
        return f"Error: {str(e)}"
    finally:
        conn.close()

def get_data(question):
    schema = get_schema_description()
    sql = generate_sql(question, schema)
    results = execute_query(sql)

    # Return both SQL and results
    return {
        'sql': sql,
        'results': results
    }
execute.py

SECTION 05Building the app

Here's how to build the Streamlit app:

import streamlit as st

st.title("Natural Language to SQL Analytics Assistant")

st.markdown("""
Ask questions about your data in plain English.
The assistant will convert your question to SQL and show results.
""")

# Example questions
examples = [
    "What are the total sales by product category?",
    "Show me customers from Mumbai",
    "What is the average order value?",
    "List employees with salary above 60000"
]

st.subheader("Try these examples:")
for ex in examples:
    if st.button(ex):
        st.session_state.question = ex

# User input
question = st.text_input("Your question:", value=st.session_state.get('question', ''))

if question and st.button("Get Data"):
    with st.spinner("Generating SQL query..."):
        result = get_data(question)

    # Show SQL query
    with st.expander("Generated SQL Query"):
        st.code(result['sql'], language='sql')

    # Show results
    if isinstance(result['results'], str):
        st.error(result['results'])
    elif result['results'].empty:
        st.info("No results found for your query.")
    else:
        st.subheader("Query Results")
        st.dataframe(result['results'])
        st.caption(f"Rows: {len(result['results'])}")
app.py

SECTION 06Portfolio presentation

Here's how to present this project to employers:

  • GitHub: Upload your code, database schema, and app code.
  • README: Write a clear README with project overview, examples, and deployment instructions.
  • Live demo: Deploy your app on Streamlit Cloud.
  • Screenshots: Add screenshots of your app in action.
  • LinkedIn post: Share your project with a brief explanation of the problem you solved.
Key point: NL-to-SQL is a highly visible AI application — it shows you can bridge the gap between natural language and data.

SECTION 07Interview Q&A — NL to SQL assistant

Q1Why did you choose an NL-to-SQL project?

Data access is a major barrier for non-technical users. I wanted to show I can build a system that makes data accessible through natural language.

Q2How does the assistant handle complex queries?

The assistant uses GPT-4 to understand the question and generate SQL. I also provide the database schema as context to improve accuracy.

Q3What database did you use?

I used SQLite for local development. The app can be adapted to work with PostgreSQL or other databases.

Q4What was the biggest challenge?

Handling complex questions and ensuring the generated SQL was syntactically correct was the biggest challenge.

Q5What would you do differently next time?

I'd add query validation, error handling for invalid SQL, and support for more complex queries with joins and subqueries.

SECTION 08Test yourself — NL to SQL quiz

Five questions. No sign-up.

0 / 5

Pick an answer to see why it is right or wrong.

SECTION 09Frequently asked questions

What is natural-language-to-SQL?

Natural-language-to-SQL is the ability to convert English questions into SQL queries, making data accessible to non-technical users.

What LLM is best for NL-to-SQL?

GPT-4 and Claude are excellent for NL-to-SQL. They understand complex questions and generate accurate SQL.

What database should I use?

SQLite is great for development and prototyping. PostgreSQL is excellent for production.

How long does this project take?

3-4 weeks — 1 week for database design, 1 week for NL-to-SQL, 1 week for execution, 1 week for app and deployment.

Can the assistant handle complex joins?

Yes — with proper schema context, the LLM can generate queries with joins, aggregations, and subqueries.

Classroom & online · Noida

Build AI projects — get hired

Our Artificial Intelligence Training Course includes NL-to-SQL and other AI projects with step-by-step guidance.

₹18,500 · full programme ₹28,000
  • 8 AI projects
  • LLM integration
  • Mock interviews
  • Weekday & weekend batches
Build This Project

More AI project guides

Career resources

Build your career

Latest articles

Fresh this week