×
Community Blog Generating SQL Queries with Alibaba Cloud's Qwen

Generating SQL Queries with Alibaba Cloud's Qwen

In this tutorial, we'll show you how to use Alibaba Cloud's Qwen model to generate SQL queries from natural language.

Gartner's Generative AI Landscape: Quick Wins & Likely Wins

Gartner's "Quick Wins" Framework

1
_Source: Gartner (2023)_

According to Gartner, "Quick Wins" are use cases that:

  • Deliver moderate to high business value
  • Require low deployment cost, complexity, and risk
  • Can be implemented rapidly with existing tools and resources

These projects are ideal for organizations seeking early ROI (Return On Investment) from generative AI without major infrastructure overhauls.

Text-to-SQL as a "Quick Win"

Our solution exemplifies a Quick Win because:

  1. Low Implementation Cost: Utilizing existing databases (e.g., PostgreSQL) and APIs (Qwen-Max).
  2. Fast Time-to-Value: Deployment in hours, not months.
  3. Scalable Impact: Automating repetitive SQL tasks to reduce labor costs and errors.
  4. Minimal Risk: Seamless integration with current workflows; no disruptive changes required.

Gartner's 2024 GenAI Use-Case Comparison

2
Source: Gartner, Inc. (2024)

In Gartner's analysis, code generation (including text-to-SQL) falls in the "Likely Wins" quadrant—high feasibility, high value, low risk. Key takeaways:

  • High Feasibility: Tools like Qwen-Max reliably generate SQL from natural language.
  • High Business Value: Automates repetitive tasks, reduces errors, and accelerates data insights.
  • Low Risk: Minimal disruption compared to complex AI applications.

Why Text-to-SQL Fits "Likely Wins"

1. Cost Efficiency:

  • Reduce Manual Effort: Developers and analysts focus on strategic work.
  • Lower Error Rates: AI-generated SQL minimizes syntax/logic errors.

2. Scalability:

  • Automate Reporting: Generate thousands of queries for dashboards or audits.
  • Integrate with Existing Systems: Works with databases like PostgreSQL.

3. Fast Time-to-Value:

  • Quick Setup: Deploy in hours using APIs like Qwen-Max.
  • Minimal Training: Users need only basic natural language skills.

Conclusion: Text-to-SQL Is A Strategic Low-Risk Investment

By adopting text-to-SQL solutions, organizations align with Gartner's recommendations to prioritize low-risk, high-impact AI initiatives. It's not just automation—it's about unlocking productivity and accelerating data-driven decisions with minimal upfront investment.

For deeper insights, explore Gartner's reports:

This structure emphasizes business alignment, risk mitigation, and pragmatic ROI- perfect for executives and decision-makers.

Technical Deep Dive: Building Your Text-to-SQL Chatbot

SQL Queries: The Problem Every Developer Faces

3

Writing SQL queries is time-consuming, error-prone, and costly. Whether you're analyzing customer data or generating reports, translating natural language questions into SQL requires a deep understanding of databases. What if you could automate this process using AI, and save costs?

In this article, we'll build a text-to-SQL chatbot powered by Alibaba Cloud's Qwen3 (we'll use Qwen-Max in this example), a state-of-the-art large language model (LLM). This chatbot connects to a PostgreSQL database, converts human queries into SQL, and returns results—all without writing a single line of SQL manually.

You'll reduce both development time and cloud expenses with Alibaba Cloud's cost-effective API pricing and Qwen-Max's high accuracy.

Step 1: Get Started with Alibaba Cloud Model Studio

1.1 Access Model Studio

Visit Alibaba Cloud and sign up. Once logged in, navigate to the Model Studio console (link).

1.2 Generate Your API Key

Go to the API Key Management page (link) and create a new API key. Store it securely—it's your access token to Qwen-Max.

1.3 Set Up Your Python Environment

Create a virtual environment and install dependencies:

# Create virtual environment
python3 -m venv venv
source venv/bin/activate

# Install required packages
pip install openai python-dotenv psycopg2-binary tabulate

Save the following in requirements.txt:

openai
python-dotenv
psycopg2-binary
tabulate

1.4 Test the Qwen-Max API

Run a quick test using the provided example code to verify your API key works.

import os
from openai import OpenAI

try:
    client = OpenAI(
        # If the environment variable is not configured, replace the following line with your API key: api_key="sk-xxx",
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
    )

    completion = client.chat.completions.create(
        model="qwen-plus",  # Model list: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
        messages=[
            {'role': 'system', 'content': 'You are a helpful assistant.'},
            {'role': 'user', 'content': 'Who are you?'}
            ]
    )
    print(completion.choices[0].message.content)
except Exception as e:
    print(f"Error message: {e}")
    print("For more information, see: https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code")

Step 2: Set Up PostgreSQL for Automation

2.1 Create an ApsaraDB RDS Instance with PostgreSQL

Use ApsaraDB for PostgreSQL to set up a managed PostgreSQL instance. Refer to this documentation for details.

Another option is to follow this step-by-step guide to provision a PostgreSQL 17 database on Alibaba Cloud and connect it to your local machine using psql.

Step 1: Access the ApsaraDB RDS Console

4

  1. Log in to the Alibaba Cloud Console.
  2. Navigate to ApsaraDB RDS > Quick Start (as shown in the image).

Step 2: Configure Database Settings

Use the interface shown in the image above to set up your PostgreSQL 17 instance:

Setting Action
Region Select a region (e.g., Singapore).
Database Engine Choose PostgreSQL and select version 17 from the dropdown.
SLR Authorization Ensure 'Authorized' is checked for enhanced security.
Edition Select High-Availability Edition for redundancy.
Product Type Choose Standard for most use cases.
Storage Type Opt for Premium ESSD for high-performance I/O.
Network Type Select VPC for secure isolation.
Add to Whitelist Enable Yes to allow connections from your local IP or VPC.

Step 3: Finalize and Launch

  1. Review your configuration and click Create.
  2. Wait for the instance to enter the Running state (typically 5–10 minutes).

Step 4: Retrieve Connection Details

Once the instance is active:

  1. Go to the Overview tab in the ApsaraDB RDS console.
  2. Note the Endpoint, Port, Username, and Password.

Step 5: Connect Locally with psql

Install psql on your local machine (if not already installed), then connect using:

psql -h <ENDPOINT> -U <USERNAME> -d <DATABASE_NAME> -p <PORT>

Replace placeholders with your values (e.g., -d postgres for the default database).

Success!

For deeper configuration details, refer to Alibaba Cloud's official documentation:

2.2 Install PostgreSQL Tools

On macOS/Linux, run:

brew install postgresql  # macOS
sudo apt install postgresql-client  # Ubuntu

2.3 Restore the DVD Rental Sample Database

Download the DVD Rental sample database and restore it:

# Restore the database
pg_restore -U your_user -h your_host -p your_port -d dvdrental dump_file.tar

2.4 Test with psql or pgAdmin

Run a sample query to confirm everything works:

SELECT * FROM film LIMIT 5;

Step 3: Build the Text-to-SQL Chatbot

3.1 Code Overview

The following script uses Qwen-Max to convert natural language queries into SQL and executes them on PostgreSQL.

import os
import psycopg2
from openai import OpenAI
from dotenv import load_dotenv
from tabulate import tabulate

load_dotenv()

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
)

def generate_sql_query(natural_language_query):
    system_prompt = """
You are a helpful assistant trained to convert natural language queries into SQL statements.
The database schema includes the following tables:
- film_category (category_id, name)
- film (film_id, title, category_id)
- inventory (inventory_id, film_id, store_id)
- rental (rental_id, inventory_id, customer_id, return_date, rental_date)
- payment (payment_id, customer_id, staff_id, rental_id, amount, payment_date)

Generate a valid SQL query that answers the user's question.
"""

    response = client.chat.completions.create(
        model="qwen-max",
        messages=[
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": natural_language_query}
        ],
        temperature=0.2
    )

    sql_query = response.choices[0].message.content.strip()
    
    # Extract SQL between "```sql" and "```"
    start_marker = "```sql"
    end_marker = "```"
    start_idx = sql_query.find(start_marker)
    end_idx = sql_query.find(end_marker, start_idx + len(start_marker))

    if start_idx != -1 and end_idx != -1:
        sql_query = sql_query[start_idx + len(start_marker):end_idx]
    elif start_idx != -1:
        sql_query = sql_query[start_idx + len(start_marker):]
    elif end_idx != -1:
        sql_query = sql_query[:end_idx]

    sql_query = sql_query.strip()

    # Fallback to 'select' keyword
    if not sql_query.lower().startswith("select"):
        select_index = sql_query.lower().find("select")
        if select_index != -1:
            sql_query = sql_query[select_index:]

    return sql_query.strip()

def execute_sql_query(sql_query):
    conn = psycopg2.connect(
        dbname=os.getenv("DB_NAME"),
        user=os.getenv("DB_USER"),
        password=os.getenv("DB_PASSWORD"),
        host=os.getenv("DB_HOST"),
        port=os.getenv("DB_PORT")
    )
    cursor = conn.cursor()
    try:
        cursor.execute(sql_query)
        columns = [desc[0] for desc in cursor.description]
        rows = cursor.fetchall()
        return columns, rows
    except Exception as e:
        print(f"Error executing SQL: {e}")
        return [], []
    finally:
        cursor.close()
        conn.close()

def main():
    user_query = "show the sum of amount by each payment id that is greater then 10"
    print("Generating SQL query...")
    sql_query = generate_sql_query(user_query)
    print("Generated SQL:")
    print(sql_query)

    print("\nExecuting SQL query...")
    columns, rows = execute_sql_query(sql_query)

    if columns and rows:
        print("\nQuery Result:")
        print(tabulate(rows, headers=columns, tablefmt="psql"))
    else:
        print("No results returned.")

if __name__ == "__main__":
    main()

3.2 How It Works

  • generate_sql_query(): Uses Qwen-Max to convert natural language to SQL.
  • execute_sql_query(): Connects to PostgreSQL and runs the generated SQL.
  • main(): Orchestrates the flow.

5

The results should resemble the figure above. Moreover, this code can be further developed and modified to create dashboards, and it will be integrated with ChatBI. Not as advanced as QuickBI's ChatBI, however, it's a good start.

3.3 Debugging Tips

  • Test the SQL output directly in psql or pgAdmin before running in Python.
  • Use print(repr(sql_query)) to debug hidden characters.

Why This Solution Saves Cost

  1. Reduce Manual Labor: No need for developers or analysts to write SQL queries.
  2. Low API Costs: Qwen-Max is more attractive compared to other LLMs in terms of speed and offering similar accuracy at a lower cost.
  3. Auto-Scaling Infrastructure: Alibaba Cloud's managed services handle scaling, reducing DevOps overhead.

Conclusion: Beyond Text-to-SQL

This chatbot is just the beginning. With Alibaba Cloud's Qwen series, you can expand into:

  • ChatBI: Building conversational dashboards.
  • Agent Systems: Automating complex workflows with function calling.
  • Multimodal AI: Adding image/video analysis with Qwen-VL.

Ready to cut costs and boost productivity? Start with this text-to-SQL chatbot—and unlock the full potential of AI-powered automation.

Next Steps

  • Try the code in your Alibaba Cloud environment.
  • Explore Qwen's advanced features.
  • Share your use case in the comments!
0 1 0
Share on

Farruh

34 posts | 30 followers

You may also like

Comments