Skip to content

SQL Query Constructor

SQL Query Constructor turns a request written in plain language, such as “customers in Valencia who bought last month”, into an SQL query ready to run on your database. It uses an AI model and the information of the connected database (its tables, its columns and examples of its content) to choose the right columns.

The component only writes the query: it does not run it. To get the data, pass the query to a component that runs it, such as SQL Executor, and if you want a plain-language explanation of the result, add Explain SQL results afterwards.

When to use it

  • Let the sales team query the customer database by typing questions, without knowing SQL.
  • Build an assistant that answers questions about orders, stock or invoicing with real data.
  • Generate queries for reports from requests written by email or chat.

Configuration

FieldWhat it does
Input request (required)The request in plain language, for example “How many orders has Talleres Ruiz placed this year?”. It can come from a chat, a form or another component.
Top K (required)The maximum number of results the query asks for when the request does not state an amount. It must be greater than 0.
ConnectionWhat to connect
DatabaseThe database the query is written for: connect the SQLDatabase output of the SQLDatabase component.
LLM (required)An AI model component, for example OpenAI.

What it does with the request

  1. Checks that it only asks to read data. If the request asks to add, change or delete information, the component stops with an error and writes no query.
  2. Adjusts the language. If the request is in a different language from the database content, it translates it first, so text searches find matches.
  3. Links the important words to the columns where that information is likely to be found.
  4. Writes the query, reviews it and returns the final version.

Output

The Text output returns the SQL query as text. Connect it to the query field of a component that runs it, for example Query to run in SQL Executor.

Example

Distribuciones Norte wants its sales team to query the order history from a chat:

  1. An SQLDatabase component with the connection details of the orders database is connected to Database, and an AI model to LLM.
  2. The chat message reaches Input request: “Show me the last ten orders from Talleres Ruiz”. Top K is set to 20.
  3. The query that comes out of Text goes to SQL Executor, and its result to Explain SQL results, which replies in the chat with a clear explanation.

Good practices

  • Connect the database with a user that only has read permission. The check that a request only reads data is made by the AI model, so this second safeguard is worth having.
  • Use clear column names in your database: the component chooses columns from their names and their content.
  • Review the generated queries the first few times, especially with complex requests.