Database

Initialize the client with your API key

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 about your data
  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

questionstringbodyrequired

Natural language question to query the database (e.g., "How many active users do we have?")

tablestringbodyrequired

The name of the table to query (e.g., "users")

Response

successbooleanrequired

Indicates if the query was executed successfully

dataarrayrequired

The query results as an array of objects

sqlstringrequired

The SQL query generated from the natural language question

executionTimeintegerrequired

Query execution time in milliseconds

messagestringrequired

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.

JavaScript

natural-language-query.js

import Worqhat from 'worqhat';// Initialize the client with your API keyconst 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?",    environment: process.env.WORQHAT_ENVIRONMENT || 'production' // Defaults to production  });    // 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 functioncountActiveUsers();

Example: Advanced Natural Language Query

This example shows how to execute a more complex natural language query to analyze sales data.

JavaScript

advanced-nl-query.js

import Worqhat from 'worqhat';// Initialize the client with your API keyconst client = new Worqhat({apiKey: process.env.WORQHAT_API_KEY,environment: process.env.WORQHAT_ENVIRONMENT || 'production', // Defaults to production});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?",    environment: process.env.WORQHAT_ENVIRONMENT || 'production' // Defaults to production  });    // 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

questionstringbodyrequired

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?"

Response Fields Explained

successbooleanrequired

true if the query was executed successfully, false otherwise.

dataarrayrequired

An array of objects containing the query results. Each object represents a row in the result set.

sqlstringrequired

The SQL query that was generated from your natural language question. This is useful for understanding how the AI interpreted your question.

executionTimeintegerrequired

The time taken to execute the query in milliseconds.

messagestringrequired

A message indicating the status of the query execution.

Example Response

response.json

{"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
"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
  • 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?"