A slow SQL query can affect an entire application. A page that takes two seconds to load might be acceptable during development, but when the same query runs thousands of times in production, it can increase database load, consume CPU, and affect other operations.
Traditionally, database developers investigate these problems by checking execution plans, reviewing indexes, examining table statistics, and testing different query structures. This process requires experience and can take considerable time.
AlloyDB for PostgreSQL introduces an AI-powered SQL tuning capability that helps developers investigate query performance and identify possible optimizations. Its ai.tune_sql function uses a large language model to analyze query execution plans and provide recommendations.
In this article, we will explore how AI-assisted SQL tuning works in AlloyDB, how to enable it, and how to use it to investigate a slow query.
Understanding AI-Powered SQL Tuning in AlloyDB
AlloyDB is Google's managed PostgreSQL-compatible database service. It provides database performance features such as Query Insights, an index advisor, and advanced monitoring capabilities.
The AI-powered SQL tuning capability adds another layer to this process.
Instead of manually examining every part of an execution plan, developers can submit a SQL query to the ai.tune_sql function. The function analyzes the query and provides recommendations based on its execution plan and related database information.
The recommendations can cover several areas:
Area | What AI analyzes |
|---|
Query summary | Potential performance bottlenecks |
Query rewrite | Alternative ways to write the query |
Index recommendations | Possible indexes that can improve execution |
Statistics | Whether table statistics need updating |
Database configuration | Potential PostgreSQL configuration changes |
Analyze and vacuum | Whether maintenance operations might help |
For example, consider an application that retrieves customer orders from a large table. The query might be correct, but its execution plan could show an inefficient scan or an expensive sorting operation.
AI-assisted tuning can help identify these possibilities and suggest changes worth investigating.
It is important to understand that these are recommendations, not guaranteed fixes. Developers still need to validate them against their actual workload.
Requirements Before Enabling AI SQL Tuning
Before using ai.tune_sql, make sure your AlloyDB environment meets the required conditions.
The documented requirements include:
- An AlloyDB instance running PostgreSQL 18 or later.
- Vertex AI integration enabled.
- The google_ml_integration extension version 1.6.2 or later.
- The google_db_advisor extension enabled.
- The hypopg extension enabled.
- Access to AlloyDB Studio or a PostgreSQL client such as psql.
The ai.tune_sql capability is currently documented as a Preview feature. Check its availability and applicable terms before using it in a production environment.
You also need the appropriate permissions to configure the AlloyDB instance and use its Vertex AI integration.
Enable the Required Extensions
Connect to your AlloyDB database using AlloyDB Studio or psql.
First, enable the required extensions:
CREATE EXTENSION IF NOT EXISTS google_ml_integration;
CREATE EXTENSION IF NOT EXISTS google_db_advisor;
CREATE EXTENSION IF NOT EXISTS hypopg;
The google_ml_integration extension provides the integration used by the AI tuning functionality.
The google_db_advisor extension provides database advisor capabilities, while hypopg helps evaluate potential index recommendations without immediately creating physical indexes.
Make sure the installed google_ml_integration version is at least 1.6.2.
You can inspect the installed extension versions with:
SELECT
extname,
extversion
FROM pg_extension
WHERE extname IN (
'google_ml_integration',
'google_db_advisor',
'hypopg'
);
If an extension is missing or its version is incompatible, resolve that before proceeding.
Configure the Gemini Model Endpoint
The next step is to register a supported Gemini model endpoint for the AI tuning function.
AlloyDB uses the google_ml.create_model procedure to register the model.
For example, the following statement registers a global Gemini model endpoint:
CALL google_ml.create_model(
model_id => 'gemini-3.5-flash-global',
model_request_url =>
'https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/publishers/google/models/gemini-3.5-flash:generateContent',
model_qualified_name => 'gemini-3.5-flash',
model_provider => 'google',
model_type => 'llm',
model_auth_type => 'alloydb_service_agent_iam'
);
Replace PROJECT_ID with your Google Cloud project ID.
The model endpoint must be available to your project, and the AlloyDB service agent needs the required IAM permissions to invoke it through Vertex AI.
Next, configure the model ID for the database advisor:
SET google_db_advisor.llm_model_id =
'gemini-3.5-flash-global';
Enable AI SQL tuning for the current database session:
SET google_db_advisor.enable_ai_tune_sql = on;
These SET statements apply to the current session. If you need the settings to persist across sessions, configure the appropriate database-level settings or instance database flags.
Tune a Slow SQL Query Using ai.tune_sql
Let's consider a practical example.
Suppose an e-commerce application stores customer orders in an orders table. The application frequently retrieves recent orders for a particular customer.
The table contains millions of records, and users have started reporting slow order-history pages.
Here is a sample query:
SELECT
order_id,
customer_id,
order_date,
order_status,
total_amount
FROM orders
WHERE customer_id = 1050
AND order_status = 'Completed'
ORDER BY order_date DESC
LIMIT 20;
The query looks straightforward, but its performance depends on several factors:
- The number of rows in the table.
- The distribution of customer IDs and order statuses.
- Available indexes.
- Table statistics.
- The execution plan selected by PostgreSQL.
Before changing anything, inspect the execution plan:
EXPLAIN (ANALYZE, BUFFERS)
SELECT
order_id,
customer_id,
order_date,
order_status,
total_amount
FROM orders
WHERE customer_id = 1050
AND order_status = 'Completed'
ORDER BY order_date DESC
LIMIT 20;
Review the plan for expensive operations, such as large sequential scans, unnecessary sorting, and significant buffer reads.
You can now submit the query to the AI tuning function:
SELECT ai.tune_sql(
query => $$
SELECT
order_id,
customer_id,
order_date,
order_status,
total_amount
FROM orders
WHERE customer_id = 1050
AND order_status = 'Completed'
ORDER BY order_date DESC
LIMIT 20
$$,
explain_analyze => TRUE
);
The function analyzes the query and provides performance insights and possible optimizations.
When explain_analyze is TRUE, the function uses EXPLAIN ANALYZE to execute the query and collect execution-plan information. This can provide more useful tuning insights, but it also means the query actually runs.
Only use this option for supported, read-only SELECT statements. Do not use it with statements that modify data.
If you want to inspect the estimated execution plan without executing the query, use:
SELECT ai.tune_sql(
query => $$
SELECT
order_id,
customer_id,
order_date,
order_status,
total_amount
FROM orders
WHERE customer_id = 1050
AND order_status = 'Completed'
ORDER BY order_date DESC
LIMIT 20
$$,
explain_analyze => FALSE
);
The second approach is useful when you want an initial plan-based analysis without running the query.
Understand the AI Recommendations
After analyzing the query, AlloyDB can provide recommendations in different categories.
For example, suppose the execution plan indicates that PostgreSQL is reading many rows before returning the requested orders.
The AI analysis might suggest reviewing the existing indexes or considering a composite index that supports the filtering and sorting conditions.
An example candidate index could be:
CREATE INDEX idx_orders_customer_status_date
ON orders (
customer_id,
order_status,
order_date DESC
);
This is an illustrative index, not a guaranteed recommendation from AlloyDB.
Whether it helps depends on the actual query workload, data distribution, existing indexes, and write activity.
Similarly, the AI might recommend:
- Rewriting a query to reduce unnecessary operations.
- Collecting fresh statistics using
ANALYZE. - Reviewing indexes for frequently executed queries.
- Investigating memory or database configuration settings.
- Running maintenance operations when table statistics or dead tuples indicate a problem.
Do not apply every recommendation automatically. An index can improve read performance but increase storage requirements and the cost of INSERT, UPDATE, and DELETE operations.
Use Query Insights Alongside AI Tuning
The ai.tune_sql function is useful when you want to analyze an individual SQL statement. However, production database performance requires continuous monitoring.
AlloyDB Query Insights helps identify which queries contribute most to database load.
You can use it to:
- Identify queries with high execution latency.
- Compare query performance across different time ranges.
- Review database load and query activity.
- Investigate queries that have become slower than their normal baseline.
- Find queries that might benefit from additional indexes.
AlloyDB also provides AI-assisted troubleshooting through Gemini Cloud Assist. This feature can analyze performance anomalies and provide observations and hypotheses about possible causes.
It is useful to understand the distinction:
Capability | Primary purpose |
|---|
ai.tune_sql
| Analyze a specific SQL query and suggest tuning changes |
Query Insights | Monitor query performance and identify expensive queries |
Index advisor | Analyze workload patterns and recommend indexes |
Gemini Cloud Assist | Investigate performance anomalies and provide troubleshooting hypotheses |
These capabilities complement each other. Query Insights can help you identify which query needs attention, while ai.tune_sql can help investigate how that query might be improved.
Best Practices for AI-Assisted SQL Tuning
AI can reduce the time required to investigate database performance, but it should remain part of a controlled tuning process.
Consider the following practices:
- Start with actual performance data rather than assuming a query is slow.
- Capture the existing execution plan before making changes.
- Use representative parameter values when testing query rewrites.
- Review existing indexes before creating new ones.
- Validate index recommendations against read and write workloads.
- Compare execution time, buffer usage, and database load before and after changes.
- Test recommendations in a development or staging environment.
- Monitor the query after deployment to confirm that the improvement continues.
- Avoid sending sensitive data or confidential information to an AI model without reviewing your organization's data-handling requirements.
One important limitation concerns prepared and parameterized statements. When a query contains placeholders such as $1 or $2, ai.tune_sql does not provide query rewrite recommendations. Other tuning recommendations can still be available.
If you need query rewrite suggestions, use representative literal values when submitting the query for analysis.
Also remember that AI-generated recommendations can be incorrect or unsuitable for a particular workload. AlloyDB's architecture has characteristics that differ from standard PostgreSQL deployments, so validate recommendations using actual AlloyDB metrics.
Summary
AI-powered SQL tuning in AlloyDB gives developers another way to investigate slow queries. The ai.tune_sql function analyzes SQL execution plans and provides recommendations for query rewrites, indexes, statistics, database configuration, and maintenance operations. When combined with Query Insights and the index advisor, it can help database teams identify performance problems and prioritize tuning work. However, AI should support database engineering decisions, not replace them. Always validate recommendations against real execution plans, application workloads, and production performance measurements before applying changes.
Join the conversation! Your thoughts help the community grow.