Text-to-SQL translates a natural-language request into a SQL query. A generated query can be submitted to a database, but plausible output is not proof of accuracy. Establish a baseline and test it before relying on the service. section 6.0 section 6.3
Counting employees
A user might ask for SQL to count employees in the marketing department. The service combines that request with available table definitions and can include recent queries as additional context. section 6.0 section 6.2
Listing 6.11 The SqlGeneratorServiceImpl#buildPrompt() method
String buildPrompt(SqlGeneratorQueryRequest request) {
StringBuilder prompt = new StringBuilder();
prompt.append("You are a SQL expert. Generate a SQL query based on the following information:\n\n"); #A
prompt.append("User Request: ").append(request.getUserPrompt()).append("\n\n"); #B
prompt.append("Available Tables:\n"); #C
for (Table table : request.getTables()) {
prompt.append("- ").append(table.getCreateTableSql()).append("\n"); #C
}
#D
if (request.getNLastQueries() != null && !request.getNLastQueries().isEmpty()) {
prompt.append("\nRecent Queries for those tables:\n");
for (int i = 0; i < request.getNLastQueries().size(); i++) {
prompt.append(i + 1).append(". ").append(request.getNLastQueries().get(i)).append("\n");
}
prompt.append("\n");
}
prompt.append("Please generate a valid SQL query that addresses the user's request. ");
prompt.append("Only return the SQL query without any additional explanation or formatting."); #E
return prompt.toString();
}The prompt builder adds the user request, CREATE TABLE statements, and optional recent queries. The extra context may help accuracy, but it also increases prompt size and cost. section 6.2 section 6.0
Build and evaluate the service with explicit guardrails:
- Hide the model provider behind a service API to reduce direct provider coupling. Managed AI gateways are an alternative, but can introduce cloud-ecosystem lock-in and delay access to new models. section 6.0
- Limit request length and count prompt tokens against a budget. Schema, column descriptions, and recent queries are useful context candidates, but their value should be tested against their cost. section 6.2 section 6.3
- Configure temperature for the specific model. Low temperature is a conventional choice for repeatable SQL generation, but some newer reasoning models recommend their default setting instead. section 6.2
- Use a dataset such as BIRD to assess accuracy and compare context or prompting changes. Treat step-by-step prompting as a hypothesis to test, not a guarantee of correctness. section 6.3
- Handle empty responses and remove formatting such as Markdown fences, but do not confuse response cleanup with verification that the SQL is correct. section 6.2 section 6.3


