How to Build High‑Quality SQL Prompts with GPT: From Open‑Source Tool to Product

This article explains how to construct effective SQL prompts by combining personal SQL expertise with large language model capabilities, introduces the open‑source sql‑translator tool for bidirectional SQL‑natural language conversion, and discusses practical productization scenarios.

Programmer DD
Programmer DD
Programmer DD
How to Build High‑Quality SQL Prompts with GPT: From Open‑Source Tool to Product

Overview

With the rapid development of GPT models, many applications integrate them to enhance functionality. This article outlines a systematic method for building SQL prompts and explores how to productize an open‑source SQL project.

1. Personal SQL Ability

Creating high‑quality SQL prompts requires strong SQL knowledge, understanding of execution processes, and the ability to translate natural language into effective prompts. Two key skills are needed:

Continuous learning: Prompt engineering is suited for engineers rather than beginners, but tools like ChatGPT can lower the learning curve.

Familiarity with SQL syntax: Mastery of DDL, DML, DQL and their specific syntax forms the foundation for prompt generation.

2. Large Language Model Performance

Effective SQL prompts also depend on the LLM’s capabilities in natural language understanding, database metadata comprehension, and SQL generation/optimization. Evaluation criteria include:

Natural language understanding – correctly interpreting user queries.

Database metadata understanding – recognizing schema, data types, relationships.

SQL generation – producing accurate DDL/DML statements, optimization suggestions, and risk warnings.

sql‑translator Product Overview

sql‑translator is an open‑source Node.js tool that calls the ChatGPT API to convert between SQL statements and natural language. It provides a simple UI where users input a prompt and receive the corresponding SQL or natural language output.

Figure 1 shows the natural‑language‑to‑SQL interface; Figure 2 shows the SQL‑to‑natural‑language interface.

Running sql‑translator

The core of the tool consists of two scripts:

translateToSQL.js

Defines translateToSQL(query, apiKey, tableSchema=""), builds a prompt, and sends a POST request to https://api.openai.com/v1/completions using the text-davinci-003 model.

// import fetch from "isomorphic-unfetch"
const translateToSQL = async (query, apiKey, tableSchema = "") => {
  const prompt = `Translate this natural language query into SQL without changing the case of the entries given by me:

"${query}"
${tableSchema ? `Use this table schema:

${tableSchema}

` : ""}SQL Query:`;
  const response = await fetch("https://api.openai.com/v1/completions", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${apiKey}`
    },
    body: JSON.stringify({
      prompt,
      temperature: 0.5,
      max_tokens: 2048,
      n: 1,
      stop: "\
",
      model: "text-davinci-003",
      frequency_penalty: 0.5,
      presence_penalty: 0.5,
      logprobs: 10
    })
  });
  const data = await response.json();
  if (!response.ok) {
    console.log(response);
    throw new Error(data.error || "Error translating to SQL.");
  }
  return data.choices[0].text.trim();
};

translateToHuman.js

Defines translateToHuman(query, apiKey) to convert SQL back to natural language, using a similar API call.

// import fetch from "isomorphic-unfetch"
const translateToHuman = async (query, apiKey) => {
  const prompt = `Translate this SQL query into natural language:

"${query}"

Natural language query:`;
  const response = await fetch("https://api.openai.com/v1/completions", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${apiKey}`
    },
    body: JSON.stringify({
      prompt,
      temperature: 0.5,
      max_tokens: 2048,
      n: 1,
      stop: "\
",
      model: "text-davinci-003",
      frequency_penalty: 0.5,
      presence_penalty: 0.5,
      logprobs: 10
    })
  });
  const data = await response.json();
  if (!response.ok) {
    console.log(response);
    throw new Error(data.error || "Error translating to natural language.");
  }
  return data.choices[0].text.trim();
};

Productization Ideas

Based on sql‑translator, three potential products are suggested:

A SQL teaching platform where users input natural‑language queries and receive the generated SQL, facilitating hands‑on learning.

An intelligent data‑report generator that translates natural‑language requests into SQL, fetches data, and produces readable analysis reports.

A data‑analysis chatbot that converts user questions into SQL queries, retrieves results, and returns answers in human language.

Artificial IntelligenceSQLdatabaseprompt engineeringNode.jsGPTOpenAI API
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.