256
bytes to 4500
bytes. 1024
. 1024
to 100000
. 10000
bytes. 0
. 0
to 20
. 5
. 200
to provide more data points. 200
In the Google Cloud console, go to the Cloud SQL Instances page.
To enable query insights for a Cloud SQL instance by using gcloud
, run gcloud sql instances patch
with the --insights-config-query-insights-enabled
flag as follows after replacing INSTANCE_ID with the ID of the instance.
gcloudsqlinstancespatchINSTANCE_ID\--insights-config-query-insights-enabled
Also, use one or more of the following optional flags:
--insights-config-record-client-address
Stores the client IP addresses where queries are coming from and helps you group that data to run metrics against it. Queries come from more than one host. Reviewing graphs for queries from client IP addresses can help identify the source of a problem.
--insights-config-record-application-tags
Stores application tags that help you determine the APIs and model-view-controller (MVC) routes that are making requests and group the data to run metrics against it. This option requires you to comment queries with a specific set of tags. You can do this by using the sqlcommenter open source object-relational mapping (ORM) auto-instrumentation library. This information helps Query Insights identify the source of a problem and the MVC the problem is coming from. Application paths help you with application monitoring.
--insights-config-query-string-length
Sets the default query length limit. Higher query lengths are more useful for analytical queries, but they also require more memory. Changing the query length requires you to restart the instance. You can still add tags to queries that exceed the length limit. For Cloud SQL Enterprise edition, you can specify a value in bytes from 256
to 4500
. The default query length is 1024
bytes. For Cloud SQL Enterprise Plus edition, you can specify a limit in bytes from 1024
to 100000
. The default value is 10000
bytes.
--query_plans_per_minute
By default, a maximum of 5 executed query plan samples are captured per minute across all databases on the instance. Increasing the sampling rate is likely to give you more data points but might add a performance overhead. To disable sampling, set this value to 0
. For Cloud SQL Enterprise edition, you can change the value from 0 to 20. For Cloud SQL Enterprise Plus edition, you can increase the maximum up to 200 to provide more data points. By default, the maximum sample rate is 200
query plan samples per minute across all databases on the instance.
Replace the following:
gcloudsqlinstancespatchINSTANCE_ID\ --insights-config-query-insights-enabled\ --insights-config-query-string-length=INSIGHTS_CONFIG_QUERY_STRING_LENGTH\ --query_plans_per_minute=QUERY_PLANS_PER_MINUTE\ --insights-config-record-application-tags\ --insights-config-record-client-address\ --tier=API_TIER_STRING\ --region=REGION
To enable query insights for a Cloud SQL instance by using the REST API, call the instances.patch
method with insightsConfig
settings.
Before using any of the request data, make the following replacements:
HTTP method and URL:
PATCH https://sqladmin.googleapis.com/v1/projects/PROJECT_ID/instances/INSTANCE_ID
Request JSON body:
{ "settings" : { "insightsConfig" : { "queryInsightsEnabled" : true, "recordClientAddress" : true, "recordApplicationTags" : true, "queryStringLength" : 1024, "queryPlansPerMinute" : 20, } } }
To send your request, expand one of these options:
You should receive a JSON response similar to the following:
{ "kind": "sql#operation", "targetLink": "https://sqladmin.googleapis.com/v1/projects/PROJECT_ID/instances/INSTANCE_ID", "status": "PENDING", "user": "user@example.com", "insertTime": "2025-03-28T22:43:40.009Z", "operationType": "UPDATE", "name": "OPERATION_ID", "targetId": "INSTANCE_ID", "selfLink": "https://sqladmin.googleapis.com/v1/projects/PROJECT_ID/operations/OPERATION_ID", "targetProject": "PROJECT_ID" }
To use Terraform to enable query insights for a Cloud SQL instance, set the query_insights_enabled
flag to true
.
Also, you can use one or more of the following optional flags:
query_string_length
: for Cloud SQL Enterprise edition, you can specify a value in bytes from 256
to 4500
. The default query length is 1024
bytes. For Cloud SQL Enterprise Plus edition, you can specify a limit in bytes from 1024
to 100000
. The default value is 10000
bytes. record_application_tags
: set the value to true
if you want to record application tags from the query.record_client_address
: set the value to true
if you want to record the client IP address. The default is false
.query_plans_per_minute
: for Cloud SQL Enterprise edition, you can set the value from 0
to 20
. The default is 5
. For Cloud SQL Enterprise Plus edition, you can increase the maximum up to 200
to provide more data points. The default maximum sample rate is 200
query plan samples per minute across all databases on the instance. Here's an example:
resource"google_sql_database_instance""INSTANCE_NAME"{name="INSTANCE_NAME"database_version="POSTGRESQL_VERSION"region="REGION"root_password="PASSWORD"deletion_protection=false# set to true to prevent destruction of the resourcesettings{tier="DB_TIER"insights_config{query_insights_enabled=truequery_string_length=2048# Optionalrecord_application_tags=true# Optionalrecord_client_address=true# Optionalquery_plans_per_minute=10# Optional}}}
To apply your Terraform configuration in a Google Cloud project, complete the steps in the following sections.
Set the default Google Cloud project where you want to apply your Terraform configurations.
You only need to run this command once per project, and you can run it in any directory.
export GOOGLE_CLOUD_PROJECT=PROJECT_ID
Environment variables are overridden if you set explicit values in the Terraform configuration file.
Each Terraform configuration file must have its own directory (also called a root module).
.tf
extension—for example main.tf
. In this tutorial, the file is referred to as main.tf
. mkdir DIRECTORY && cd DIRECTORY && touch main.tf
If you are following a tutorial, you can copy the sample code in each section or step.
Copy the sample code into the newly created main.tf
.
Optionally, copy the code from GitHub. This is recommended when the Terraform snippet is part of an end-to-end solution.
terraform init
Optionally, to use the latest Google provider version, include the -upgrade
option:
terraform init -upgrade
terraform plan
Make corrections to the configuration as necessary.
yes
at the prompt: terraform apply
Wait until Terraform displays the "Apply complete!" message.
Metrics are expected to be available in query insights within minutes of query completion. Review the Cloud Monitoring data retention policy.
Query insights traces are stored in Cloud Trace. Review the Cloud Trace data retention policy.
The Query insights dashboard shows the query load based on factors that you select. Query load is a measurement of the total work for all the queries in the instance in the selected time range. The dashboard provides a series of filters that help you view query load.
To open the Query insights dashboard, follow these steps:
The Query insights dashboard opens. Depending on whether you're using query insights for Cloud SQL Enterprise edition or query insights for Cloud SQL Enterprise Plus edition, the Query insights dashboard shows the following information about your instance:
Database query load is a measure of the work (in CPU seconds) that the executed queries in your selected database perform over time. Each running query is either using or waiting for CPU resources, IO resources, or lock resources. Database query load is the ratio of the amount of time taken by all the queries that are completed in a given time window to the wall-clock time.
The top-level query insights dashboard shows the Database load — all top queries graph. Drop-down menus on the dashboard let you filter the graph for a specific database, user, or client address.
Colored lines in the graph show the query load, split into categories:
Colored lines in the graph show per database load by execution time. Review the graph and use the filtering options to explore these questions:
All queries
Wait event types
Wait events
Databases
Users
Tags
Client addresses
To customize the database load chart, select a dimension from the Database Load by execution time drop-down.
To view the top contributors to the database load, you can use the Top dimensions by database load table. The Top dimensions by database load table displays the top contributors for the time period and dimension that you select in the Database Load by execution time chart drop-down. You can modify the time period or dimension to view the top contributors for a different dimension or time period.
In the Top dimensions by data load table, you can select the following tabs.
Tab | Description |
---|---|
Queries | The table displays the top normalized queries by total execution time. For each query, the data shown in columns are listed as follows:
|
Wait event types | The table displays the list of top wait event types that occurred during the selected time period. This table is only available for query insights for Cloud SQL Enterprise Plus edition.
|
Wait events | The table displays the list of top wait events that occurred during the selected time period. This table is only available for query insights for Cloud SQL Enterprise Plus edition.
|
Databases | The table shows the list of top databases that contributed to the load during the chosen time period across all executed queries.
|
Users | The table shows the list of top users for the selected time period across all executed queries.
|
Tags | For information about tags, Filter by query tags. |
Client addresses | The table shows the list of top users for the selected time period across all executed queries.
|
The Top queries table provides an overview of the queries that cause the most query load. The table shows all the normalized queries for the time range and options selected on the Query insights dashboard. It sorts queries by the total execution time during the time range that you selected.
To sort the table, select a column heading.
To sort the table, select a column heading or a property from Filter queries.
The table shows the following properties:
UTILITY COMMAND
usually include BEGIN
, COMMIT
, and EXPLAIN
commands or wrapper commands. Query insights stores and displays only normalized queries.
By default, query insights doesn't collect IP addresses or tag information. You can enable query insights to collect this information and, when required, disable collection.
Query plan traces don't collect or store any constant values and removes any PII information that the constant might show.
For PostgreSQL 9.6 and 10, query insights displays normalized queries, that is, ?
replaces the literal constant value. In the following example, the name constant is removed and ?
replaces it.
UPDATE"demo_customer"SET"customer_id"=?::uuid,"name"=?,"address"=?,"rating"=?,"balance"=?,"current_city"=?,"current_location"=?WHERE"demo_customer"."id"=?
For PostgreSQL version 11 and later, $1
, $2
, and similar variables replace literal constant values.
UPDATE"demo_customer"SET"customer_id"=$1::uuid,"name"=$2,"address"=$3,"rating"=$4,"balance"=$5,"current_city"=$6,"current_location"=$7WHERE"demo_customer"."id"=$8
To troubleshoot an application, you must first add tags to your SQL queries. Query load tags provide a breakdown of the query load of the selected tag over time.
Query insights provides application-centric monitoring to diagnose performance problems for applications built using ORMs. If you're responsible for the entire application stack, query insights provides query monitoring from an application view. Query tagging helps you find issues at higher-level constructs, such as with the business logic or a microservice.
You might tag queries by the business logic, for example, the payment, inventory, business analytics, or shipping tags. You can then find the query load that the various business logic create. For example, you might observe unexpected events, such as spikes for a business analytics tag at 1 PM or unexpected growth for a payment service trending over the previous week.
To calculate the Database load for tag, query insights uses the amount of time taken by every query that uses the tag that you select. The tool calculates the completion time at the minute boundary by using wall-clock time.
On the query insights dashboard, to view the tags table, select Tags. The table sorts tags by their total load by total time.
You can sort the table by selecting a property from Filter tags, or by clicking a column heading. The table shows the following properties:
To determine whether a specific query or tag is the root cause of the problem, do the following from the Queries tab or Tags tab, respectively:
The Query details page opens and shows the details of the selected query or tag.
The Query details page for a selected query appears as follows:
The Database load — specific query graph shows a measure of the work (in CPU seconds) that your normalized query has performed in your selected query over time. To calculate load, it uses the amount of time taken by the normalized queries that are completed at the minute boundary to the wall-clock time. At the top of the table, the first 1024 characters of the normalized query, with literals removed for aggregation and PII reasons, are displayed.
As with the total queries graph, you can filter the load for a specific query by Database, User, and Client address. Query load is split into CPU capacity, CPU and CPU wait, IO wait, and Lock wait.
The dashboard for a selected tag appears as follows. For example, if all queries from a microservices payment are tagged as payment
, you can see the amount of query load that's trending by viewing the tag payment
.
The Database load — specific tags graph shows a measure of the work (in CPU seconds) that queries matching your selected tags have performed in your selected database over time. As with the total queries graph, you can filter the load for a specific tag by Database, User, and Client address.
A query plan takes a sample of your query and breaks it down into individual operations. It explains and analyzes each operation in the query.
The Query plan samples graph shows all the query plans running at particular times and the amount of time each plan took to run. You can change the rate at which query plan samples are captured per minute. See Enable Query Insights.
By default, the panel on the right shows the details for the sample query plan that takes the longest time, as visible on the Query plan samples graph. To see the details for another sample query plan, click the relevant circle on the graph. Expanded details show a model of all the operations in the query plan.
Each operation shows the latency, rows returned, and the cost of the operation. When you select an operation, you can see more details, such as shared hit blocks, the type of schema, loops, and plan rows.
Try to narrow down the problem by looking into the following questions:
Latency is the time taken for the normalized query to complete, in wall-clock time. You use the Latency graph to examine latency on the query or tag. The latency dashboard shows the 50th, 95th, and 99th percentile latencies to find outlier behaviors.
The following image shows the database load graph at the 50th percentile for a specific query with filters selected for CPU capacity, CPU and CPU wait, IO wait, and Lock wait.
The latency of parallel queries is measured in wall-clock time even though the query load can be higher for the query due to multiple cores being used to run part of the query.
Try to narrow down the problem by looking into the following questions:
When you find the areas and times where the load was the highest, identify the source of the problem by using tracing to drill down further.
To help you identify the specific source of the problem, such as a model, view, controller, route, host, or user, query insights provides an in-context end-to-end application trace view. This view helps you understand what's going on at the Database Layer for a specific request and to find the source of a problematic query by model, view, controllers, and route.
If you enable OpenCensus or OpenTelemetry, opencensus span information is sent to the database along with the tag information inside SQL comments. Any traces from the application to Cloud Logging are linked with database query plan traces to help identify the source of the problem.
Click the End to end tab in the Sample Query screen to look at the in-context trace.
To determine the client and user causing the problem, use the Top client addresses and Top users tables to find the highest loads. You can add a user or IP address to the filter to further analyze a specific user or client address. The details in the tables include the percentage of the query load, the average execution time in milliseconds, and the times called.
You can use Cloud Trace to see end-to-end tracing for each step in the query plan. On the query insights dashboard, click the View in trace link to open the Cloud Trace tool. The trace graph shows all the traces that have been run for the selected period.
For details, see Finding and viewing traces.
Tagging SQL queries simplifies application troubleshooting. You can use sqlcommenter to add tags to your SQL queries either automatically or manually.
When you use ORM instead of directly writing SQL queries, you might not find application code that's causing performance challenges. You might also have trouble analyzing how your application code affects query performance. To tackle this issue, Query Insights provides an open source library called sqlcommenter. This library is useful for developers and administrators using ORM tools to detect which application code is causing performance problems.
If you're using ORM and sqlcommenter together, the tags are automatically created. You don't need to add or change code in your application.
You can install sqlcommenter on the application server. The instrumentation library allows application information related to your MVC framework to be propagated to the database along with the queries as a SQL comment. The database picks up these tags and starts recording and aggregating statistics by tags, which are orthogonal to statistics aggregated by normalized queries. Query insights shows the tags so that you know which application is causing the query load and can find the application code that's causing performance problems.
When you examine results in SQL database logs, they appear as follows:
SELECT*fromUSERS/action='run+this', controller='foo%3', traceparent='00-01', tracestate='rojo%2'/
Supported tags include the controller name, route, framework, and action.
The set of ORM tools in sqlcommenter is supported for the following programming languages:
Python |
|
Java |
|
Ruby |
|
Node.js |
|
For more information about sqlcommenter and how to use it in your ORM framework, see the sqlcommenter documentation.
If you're not using ORM, you must manually add sqlcommenter tags or comments in the correct SQL comment format to your SQL query. You must also augment each SQL statement with a comment containing a serialized key-value pair. Use at least one of the following keys:
action=''
controller=''
framework=''
route=''
application=''
db driver=''
Query insights drops all other keys.
To disable query insights for a Cloud SQL instance by using the Google Cloud console, follow these steps:
In the Google Cloud console, go to the Cloud SQL Instances page.
To disable query insights for a Cloud SQL instance by using gcloud
, run gcloud sql instances patch
with the --no-insights-config-query-insights-enabled
flag as follows, after replacing INSTANCE_ID with the ID of the instance.
gcloudsqlinstancespatchINSTANCE_ID\--no-insights-config-query-insights-enabled
To disable query insights for a Cloud SQL instance by using the REST API, call the instances.patch
method with queryInsightsEnabled
set to false
as follows.
Before using any of the request data, make the following replacements:
HTTP method and URL:
PATCH https://sqladmin.googleapis.com/sql/v1beta4/projects/project-id/instances/instance-id
Request JSON body:
{ "settings" : { "insightsConfig" : { "queryInsightsEnabled" : false } } }
To send your request, expand one of these options:
You should receive a JSON response similar to the following:
{ "kind": "sql#operation", "targetLink": "https://sqladmin.googleapis.com/sql/v1beta4/projects/project-id/instances/instance-id", "status": "PENDING", "user": "user@example.com", "insertTime": "2021-01-28T22:43:40.009Z", "operationType": "UPDATE", "name": "operation-id", "targetId": "instance-id", "selfLink": "https://sqladmin.googleapis.com/sql/v1beta4/projects/project-id/operations/operation-id", "targetProject": "project-id" }
To disable query insights for Cloud SQL Enterprise Plus edition, do the following:
In the Google Cloud console, go to the Cloud SQL Instances page.
database/postgresql/insights
.Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-04-17 UTC.