Executes database queries using natural language. This endpoint translates natural language questions into SQL and executes them against WorqDB.
POST https://api.worqhat.com/db/nl-query

What Does This Endpoint Do?

This endpoint allows you to query your database using plain English questions instead of writing SQL. Think of it like having a conversation with your database - you ask questions in natural language, and the API translates them into SQL queries and returns the results.

When to Use Natural Language Queries

  • For non-technical users who need to query data but don’t know SQL
  • For quick data exploration without writing complex SQL queries
  • For building conversational interfaces that need to translate user questions into database queries
  • For prototyping when you want to quickly test ideas without writing formal queries

How It Works

  1. You provide a natural language question and specify which table to query
  2. The API translates your question into a SQL query
  3. The SQL query is executed against your database
  4. The results are returned along with the generated SQL for transparency

Request Body

question
string
required
Natural language question to query the database (e.g., “How many active users do we have?”)
table
string
required
The name of the table to query (e.g., “users”)

Response

success
boolean
Indicates if the query was executed successfully
data
array
The query results as an array of objects
sql
string
The SQL query generated from the natural language question
executionTime
integer
Query execution time in milliseconds
message
string
A message indicating the status of the query execution

Code Examples

Example: Basic Natural Language Query

This example shows how to execute a simple natural language query to retrieve active user count.
import Worqhat from 'worqhat';

// Initialize the client with your API key
const client = new Worqhat({
  apiKey: process.env.WORQHAT_API_KEY, // Always use environment variables for API keys
});

async function countActiveUsers() {
  try {
    // Call the processNlQuery method
    const response = await client.db.processNlQuery({
      question: "How many active users do we have?",
      table: "users"
    });
    
    // Handle the successful response
    console.log(`Result: ${JSON.stringify(response.data)}`);
    console.log('Generated SQL:', response.sql);
    console.log('Query execution time:', response.executionTime, 'ms');
    return response;
  } catch (error) {
    // Handle any errors
    console.error('Error executing query:', error.message);
  }
}

// Call the function
countActiveUsers();

Example: Advanced Natural Language Query

This example shows how to execute a more complex natural language query to analyze sales data.
import Worqhat from 'worqhat';

// Initialize the client with your API key
const client = new Worqhat({
  apiKey: process.env.WORQHAT_API_KEY,
});

async function analyzeSalesData() {
  try {
    // More complex natural language query
    const response = await client.db.processNlQuery({
      question: "What were the top 3 product categories by revenue last quarter?",
      table: "sales"
    });
    
    // Handle the successful response
    console.log('Analysis results:', response.data);
    console.log('Generated SQL:', response.sql);
    return response;
  } catch (error) {
    console.error('Error analyzing sales data:', error.message);
  }
}

analyzeSalesData();

Request Body Explained

question
string
required
The natural language question to ask about your data. Be as specific as possible for better results.Examples: “How many active users do we have?”, “What was the total revenue last month?”, “Which products had the highest sales?”
table
string
required
The name of the table to query. This helps the AI understand the context and structure of your data.Example: “users”, “orders”, “products”

Response Fields Explained

success
boolean
true if the query was executed successfully, false otherwise.
data
array
An array of objects containing the query results. Each object represents a row in the result set.
sql
string
The SQL query that was generated from your natural language question. This is useful for understanding how the AI interpreted your question.
executionTime
integer
The time taken to execute the query in milliseconds.
message
string
A message indicating the status of the query execution.

Example Response

{
  "success": true,
  "data": [
    {
      "count": 157
    }
  ],
  "sql": "SELECT COUNT(*) as count FROM users WHERE status = 'active'",
  "executionTime": 38,
  "message": "Query processed successfully"
}

Common Errors and How to Fix Them

ErrorCauseSolution
”Could not understand question”Question is too vague or uses unknown termsRephrase with more specific language and common terms
”Table not found”Incorrect table name providedVerify the table name exists in your database
”Column not found”Question references fields that don’t existUse field names that match your database schema
”Query timed out”Question generates an overly complex querySimplify your question or break it into smaller parts
”Unauthorized”Invalid or missing API keyCheck that you’re using a valid API key

Tips for Better Results

  • Be specific: Include relevant details like time periods, categories, or conditions
  • Keep it simple: Start with straightforward questions and gradually increase complexity
  • Use common terms: Use terms that match your database schema when possible
  • Specify the table: Always provide the correct table name to query
  • Review the generated SQL: Check the returned SQL to understand how your question was interpreted

Example Questions

Here are some examples of natural language questions you can ask:
  • “How many users signed up last week?”
  • “What’s the average order value for premium customers?”
  • “Show me the top 5 products by sales”
  • “Count active users by country”
  • “What was the total revenue in March 2025?”