All Products
Search
Document Center

Hologres:GUC parameters

Last Updated:Aug 24, 2026

Hologres supports Grand Unified Configuration (GUC) parameters to control query behavior, connection management, performance, and security at the session or database level.

Limits

GUC parameters do not apply to system tables.

GUC parameter reference

Parameters are grouped by function. The Level column indicates where each parameter can be configured: Session (takes effect immediately for the current connection) or Database (takes effect after reconnecting).

Auto-analyze

These parameters control the auto-analyze feature, which automatically collects statistics to keep query plans accurate.

Parameter

Description

Default

Level

hg_enable_start_auto_analyze_worker

Enables or disables auto-analyze.

on (Hologres V1.1+)

Session / Database

hg_auto_check_table_changes_interval

Interval at which Hologres checks internal tables for changes and triggers auto-analyze.

10min

Session / Database

hg_auto_check_foreign_table_changes_interval

Interval at which Hologres checks foreign tables for changes and triggers auto-analyze.

4h

Session / Database

hg_auto_analyze_max_sample_row_count

Maximum number of rows sampled per auto-analyze run.

16777216

Session / Database

hg_fixed_api_modify_max_delay_interval

Maximum delay before auto-analyze picks up changes made through fixed APIs.

3day

Session / Database

MaxCompute foreign table query

These parameters tune how Hologres queries MaxCompute foreign tables. For tuning guidance, see Optimize query performance for MaxCompute foreign tables.

Parameter

Description

Default

Valid values

Level

hg_foreign_table_max_partition_limit

Maximum number of partitions hit per query. A value of 0 means no limit.

512 (before V3.0.7); 0 (V3.0.7+)

0–1024

Session / Database

hg_experimental_query_batch_size

Number of rows fetched per batch when scanning a MaxCompute table.

8192

—

Session / Database

hg_foreign_table_split_size

Data split size (in MB) for parallel reads. Avoid setting an excessively large value.

64

—

Session / Database

hg_foreign_table_executor_max_dop

Maximum degree of parallelism (DOP) for query execution.

Number of CPU cores (max 128)

—

Session / Database

hg_foreign_table_executor_dml_max_dop

Maximum DOP for DML operations on foreign tables.

32

—

Session / Database

hg_enable_access_odps_orc_via_holo

Enables reading MaxCompute ORC files through the Hologres native reader.

on (Hologres V1.1+)

—

Session / Database

Result cache

Parameter

Description

Default

Level

hg_experimental_enable_result_cache

Enables result caching for identical queries. Disable only when stale cache results cause issues.

on

Session / Database

Internal table query optimization

These parameters tune the query optimizer for internal tables. For details, see Optimize query performance.

Parameter

Description

Default

Level

optimizer_join_order

Controls how the optimizer searches for the optimal join order. Set to query to use the query-specified order.

exhaustive

Session

optimizer_force_multistage_agg

Forces multi-stage aggregation. Enable for queries with high-cardinality GROUP BY that show poor performance.

off

Session

Security and encryption

Parameter

Description

Default

Level

hg_anon_enable

Enables data masking. Configure at the database level so the setting applies to all sessions.

off

Database (recommended)

hg_experimental_encryption_options

Enables and configures data encryption at rest. Configure at the database level.

off

Database (recommended)

Query and connection timeouts

Important

Configure idle_session_timeout at the database level. The default value of 0 disables automatic idle connection release, which can exhaust the connection limit and cause connection leaks.

Parameter

Description

Default

Level

statement_timeout

Cancels any active query that runs longer than the specified duration. Value is in milliseconds; 0 disables the timeout. For details, see Manage queries.

8h

Session (recommended)

idle_in_transaction_session_timeout

Terminates sessions that are idle within an open transaction for longer than the specified duration. Value is in milliseconds; 0 disables the timeout. Configure at the database level to prevent transaction leaks from locking the database. For details, see Manage queries.

10min

Database (recommended)

idle_session_timeout

Releases idle connections that have been inactive for longer than the specified duration. Value is in milliseconds; 0 disables automatic release. For details, see Manage connections.

0 (disabled)

Database (recommended)

Data type conversion

Parameter

Description

Default

Level

hg_experimental_functions_use_pg_implementation

Switches the specified conversion function (to_char, to_date, or to_timestamp) to the PostgreSQL implementation, which supports the year range 0000–9999. The default Hologres implementation supports 1925–2282. Supported in Hologres V1.1.31+. For details, see Data type conversion function.

—

Session / Database

Example: To extend the year range for to_char:

set hg_experimental_functions_use_pg_implementation = 'to_char';

Aggregate functions

Parameter

Description

Default

Valid values

Level

hg_experimental_approx_count_distinct_precision

Controls the precision (and memory usage) of the APPROX_COUNT_DISTINCT function. Higher values reduce error margin but increase memory.

17

12–20

Session / Database

Time zone

Parameter

Description

Default

Level

timezone

Sets the time zone for the session or database.

GMT-8:00

Session / Database

Table operations

Parameter

Description

Default

Level

hg_experimental_enable_create_table_like_properties

When enabled, CREATE TABLE LIKE copies both the table schema and table properties (primary key, index). When disabled, only the schema is copied.

off

Session / Database

hg_experimental_affect_row_multiple_times_keep_first

Sets the INSERT ON CONFLICT conflict resolution policy to keep the first occurrence when a batch contains duplicate primary key values.

off

Session / Database

hg_experimental_affect_row_multiple_times_keep_last

Sets the INSERT ON CONFLICT resolution policy to keep the last occurrence when a batch contains duplicate primary key values.

off

Session / Database

Replication and monitoring

Parameter

Description

Default

Level

hg_experimental_enable_read_replica

Enables shard-level replication.

on

Session / Database

hg_experimental_display_query_id

Displays the query ID through a NOTICE message on the client, so that you can locate a query in hologres.hg_query_log for troubleshooting. Works with HoloWeb, PSQL, JDBC, Python (Psycopg), and other clients. The query ID is returned as a NOTICE message rather than a column in the result set. For more information, see Obtain the query ID.

off

Session / Database

Check the current value of a GUC parameter

Run SHOW to check the current or default value of a parameter:

-- Check whether auto-analyze is enabled
SHOW hg_enable_start_auto_analyze_worker;

-- Check the MaxCompute partition limit
SHOW hg_foreign_table_max_partition_limit;

-- Check whether query ID display is enabled
SHOW hg_experimental_display_query_id;

Configure GUC parameters

Configure GUC parameters at the session level or database level depending on the parameter's scope and your use case. Not all parameters need to be set at the database level.

Session level

The SET statement configures a parameter for the current connection only. The setting is discarded when the connection closes. Use session-level configuration when the behavior should apply to a specific query or workload, not globally.

Syntax:

set <GUC_NAME> = <VALUE>;

Examples:

-- Enable auto-analyze for this session
set hg_enable_start_auto_analyze_worker = on;

-- Limit MaxCompute partition hits to 1024 for this session
set hg_foreign_table_max_partition_limit = 1024;

-- Enable query ID display for this session
set hg_experimental_display_query_id = on;

Database level

The ALTER DATABASE statement sets a parameter at the database level. The change applies to the entire database without an instance restart. Your current connection must be closed and reopened before the new value takes effect; connections opened afterward inherit the parameter automatically. When you create a new database, configure its GUC parameters explicitly — they are not inherited automatically.

Syntax:

alter database <DB_NAME> set <GUC_NAME> = <VALUE>;

Examples:

-- Enable auto-analyze for all connections to testdb
alter database testdb set hg_enable_start_auto_analyze_worker = on;

-- Limit MaxCompute partition hits to 1024 for all connections to testdb
alter database testdb set hg_foreign_table_max_partition_limit = 1024;

-- Enable data masking for all connections to a database
alter database <DB_NAME> set hg_anon_enable = on;

-- Enable data encryption for all connections to a database
alter database <DB_NAME> set hg_experimental_encryption_options='AES256,623c26ee-xxxx-xxxx-xxxx-91d323cc4855,AliyunHologresEncryptionDefaultRole,187xxxxxxxxxxxxx';

-- Release idle connections after 10 minutes (600,000 ms) of inactivity
alter database <DB_NAME> SET idle_session_timeout = 600000;

Obtain the query ID

The query ID uniquely identifies each query in Hologres and is part of the primary key of the slow query log hologres.hg_query_log. Once you have the query ID of a statement, you can look up its duration, status, number of rows read, and other execution details. This makes the query ID the main entry point for troubleshooting.

Hologres does not return the query ID to the client by default. After you enable hg_experimental_display_query_id, the server returns the query ID in a NOTICE message when the statement runs.

Parameter description

Item

Description

Parameter

hg_experimental_display_query_id

Effect

Prints the query ID on the client in a NOTICE message when a statement runs.

Default value

off

Valid values

on or off.

Level

Session or database.

Return format

A NOTICE message in the format QueryID: <QUERY_ID>, for example QueryID: 1002002606817130830.

Keep the following two mechanisms in mind:

  • The query ID arrives in a NOTICE message, not as a column in the result set. Reading query results alone (for example, with fetchall()) does not give you the query ID. You must use the NOTICE mechanism that your driver provides.

  • The parameter applies to a single session and is discarded when the connection closes, so you must set it again on every new connection. This matters most with connection pools, where the statement belongs in the connection initialization step. For more information, see Connection pools.

Enable query ID display

-- Session level. Run this together with your business SQL.
set hg_experimental_display_query_id = on;

-- Check the current value.
SHOW hg_experimental_display_query_id;

-- Database level. Applies to new connections; reopen existing connections.
alter database <DB_NAME> set hg_experimental_display_query_id = on;

Retrieve the query ID from a client

Java (JDBC)

In JDBC, NOTICE messages arrive as a chain of SQLWarning objects. Walk the chain with statement.getWarnings() after the statement runs and parse the query ID from it. The ResultSet does not contain the query ID.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLWarning;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HologresQueryIdDemo {

    // Matches "QueryID: <QUERY_ID>" in a NOTICE message.
    private static final Pattern QUERY_ID_PATTERN = Pattern.compile(
            "query[_ ]?id\\s*(?:is\\b|[=:])?\\s*([0-9a-zA-Z_\\-]{6,})", Pattern.CASE_INSENSITIVE);

    public static void main(String[] args) throws Exception {
        // Use the endpoint that matches your network environment (Internet or VPC).
        // Find it on the instance details page in the console.
        String url = "jdbc:postgresql://<ENDPOINT>:80/<DB_NAME>";
        String user = "<ACCESS_KEY_ID>";
        String password = "<ACCESS_KEY_SECRET>";

        try (Connection conn = DriverManager.getConnection(url, user, password);
             Statement stmt = conn.createStatement()) {

            // Enable query ID display. The parameter is off by default and applies to this session only.
            stmt.execute("set hg_experimental_display_query_id = on;");

            String sql = "select count(*), sum(id) from holo_query_id_demo;";

            // Clear warnings left by the previous statement so that each query ID maps to one SQL statement.
            stmt.clearWarnings();
            boolean hasResultSet = stmt.execute(sql);

            // Read the result set. The query ID is not part of it.
            if (hasResultSet) {
                try (ResultSet rs = stmt.getResultSet()) {
                    while (rs.next()) {
                        System.out.println("rows      : (" + rs.getLong(1) + ", " + rs.getLong(2) + ")");
                    }
                }
            }

            // NOTICE messages arrive as a chain of SQLWarning objects. Walk the chain to parse the query ID.
            String queryId = null;
            List<String> notices = new ArrayList<>();
            for (SQLWarning w = stmt.getWarnings(); w != null; w = w.getNextWarning()) {
                notices.add(w.getMessage());
                Matcher m = QUERY_ID_PATTERN.matcher(w.getMessage());
                if (m.find()) {
                    queryId = m.group(1);
                }
            }

            System.out.println("query_id  : " + queryId);
            System.out.println("notices   : " + notices);
        }
    }
}

Sample output:

rows      : (1000, 500500)
query_id  : 1002002606817139331
notices   : [One or more columns in the following table(s) do not have statistics: holo_query_id_demo, QueryID: 1002002606817139331]

Note the following:

  • PreparedStatement works the same way. Call pstmt.getWarnings() after the statement runs.

  • Call clearWarnings() before each statement. Otherwise warnings accumulate on the same Statement object and you can no longer tell which query ID belongs to which statement.

  • A NOTICE chain can carry unrelated messages, such as a missing-statistics warning. Match on the QueryID: prefix when you parse it.

Python (Psycopg 3)

Hologres is compatible with PostgreSQL 11. Use the Psycopg 3 driver, which you install with pip install "psycopg[binary]". Register a callback with conn.add_notice_handler() to receive NOTICE messages. The rows returned by cur.fetchall() do not contain the query ID.

import re
import psycopg

NOTICES = []
QUERY_IDS = []

QUERY_ID_PATTERN = re.compile(
    r"query[_ ]?id\s*(?:is\b|[=:])?\s*([0-9a-zA-Z_\-]{6,})", re.IGNORECASE
)

def notice_handler(diag):
    """Called once for every NOTICE the server sends. Parses the query ID from it."""
    text = diag.message_primary or ""
    NOTICES.append(text)
    match = QUERY_ID_PATTERN.search(text)
    if match:
        QUERY_IDS.append(match.group(1))

conn = psycopg.connect(
    host="<ENDPOINT>",          # Find it on the instance details page in the console.
    port=80,
    dbname="<DB_NAME>",
    user="<ACCESS_KEY_ID>",
    password="<ACCESS_KEY_SECRET>",
)
conn.autocommit = True
conn.add_notice_handler(notice_handler)   # Register the NOTICE callback.

cur = conn.cursor()
# Enable query ID display. The parameter is off by default and applies to this session only.
cur.execute("set hg_experimental_display_query_id = on;")

def run_sql(sql, params=None, fetch=True):
    """Runs a statement and returns (rows, query_id, notices). rows is None when there is no result set."""
    NOTICES.clear()
    QUERY_IDS.clear()
    cur.execute(sql, params)
    rows = None
    if fetch and cur.description is not None:
        rows = cur.fetchall()
    query_id = QUERY_IDS[-1] if QUERY_IDS else None
    return rows, query_id, list(NOTICES)

rows, query_id, notices = run_sql("select count(*) from holo_query_id_demo;")
print("rows:", rows)
print("query_id:", query_id)

Sample output. Both DML and query statements return a query ID:

SQL       : insert into holo_query_id_demo select i, 'v' || i from generate_series(1, 1000) i;
query_id  : 1002002606817130830
notices   : ['QueryID: 1002002606817130830']

SQL       : select count(*), sum(id) from holo_query_id_demo;
query_id  : 1002002606817139331
rows      : [(1000, 500500)]
notices   : ['One or more columns in the following table(s) do not have statistics: holo_query_id_demo', 'QueryID: 1002002606817139331']

Connection pools

Because the parameter applies to a single session, every physical connection needs it. With a connection pool, set it in the connection initialization step instead of before each query.

The following example uses psycopg_pool for Python:

# Run pip install psycopg_pool first.
from psycopg_pool import ConnectionPool

def configure(conn):
    conn.autocommit = True
    conn.add_notice_handler(notice_handler)
    conn.execute("set hg_experimental_display_query_id = on;")

pool = ConnectionPool(kwargs=CONN_INFO, configure=configure, min_size=1, max_size=4)

with pool.connection() as conn:
    conn.execute("select 1;").fetchall()

For Java, use the initialization SQL of your pool so that every physical connection has the parameter enabled. The following examples use HikariCP and Druid:

// HikariCP: connectionInitSql runs when each physical connection is established.
HikariConfig config = new HikariConfig();
config.setJdbcUrl(url);
config.setUsername(user);
config.setPassword(password);
config.setConnectionInitSql("set hg_experimental_display_query_id = on;");
HikariDataSource dataSource = new HikariDataSource(config);

// Druid: connectionInitSqls accepts multiple initialization statements.
DruidDataSource druid = new DruidDataSource();
druid.setUrl(url);
druid.setUsername(user);
druid.setPassword(password);
druid.setConnectionInitSqls(Collections.singletonList("set hg_experimental_display_query_id = on;"));

After you borrow a connection from the pool, you still retrieve the query ID with statement.getWarnings() after each statement. For more information, see Java (JDBC).

Look up execution details by query ID

With the query ID, you can pinpoint the duration, status, number of rows read, and other details of a query in the slow query log:

select query_id, status, duration, query_start, application_name, command_tag
from hologres.hg_query_log
where query_id = '<QUERY_ID>';

Writes to hologres.hg_query_log lag by about one minute. A query that just finished may not appear yet, so retry after a short wait.

Usage notes

  • The parameter applies to a single session and is discarded when the connection closes. Run set hg_experimental_display_query_id = on; on every new connection, or queries on that connection return no query ID.

  • Not every statement returns a query ID. DDL statements such as CREATE TABLE and DROP TABLE, and simple queries that do not reach the compute engine such as select 1;, return no query ID. This is expected. DML statements such as INSERT and regular queries such as SELECT do return one.

  • A NOTICE chain can carry other messages, such as a missing-statistics warning. Match on the QueryID: prefix so that you do not pick up the wrong value.

Troubleshoot a missing query ID

Check the following in order:

  1. Run SHOW hg_experimental_display_query_id; to confirm that the value is on. If it is off, the current connection never ran the statement — with a connection pool you may have been handed a different connection. Set it again or review your connection initialization logic.

  2. Check whether any NOTICE message arrived. If none did, the server sent nothing. Confirm that your instance version supports the parameter and that the statement type produces a query ID.

  3. If NOTICE messages arrived but no query ID was parsed, the wording does not match your parsing rule. Print the raw message and adjust the rule to the format your instance returns.

  4. With a connection pool, confirm that the statement runs in the connection initialization step so that every physical connection has it applied.