Skip to content

Checking your reading list…

Retry verification

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

GaussDB DDL Internals: Three Execution Paths, Lock Behavior & Performance Impact
Databases 23 min read

GaussDB DDL Internals: Three Execution Paths, Lock Behavior & Performance Impact

This article details GaussDB's three DDL execution paths—metadata-only, table rewrite, and online DDL—explains their lock mechanisms, compares them with MySQL 8's algorithms, and provides performance estimates for common DDL operations on a 10GB table.

GaussDB DDL Algorithm System

GaussDB (derived from PostgreSQL via openGauss) handles DDL through three internal execution paths that behaviorally correspond to MySQL 8.0's ALGORITHM options ( INSTANT, INPLACE, COPY), but GaussDB does not expose a user‑specifiable ALGORITHM parameter. The optimizer automatically selects the path based on the operation type.

1.1 Three Execution Paths

Metadata‑Only (Catalog‑Only) : Modifies only system catalogs ( pg_attribute, pg_class, pg_description), no user data pages touched. Completes in milliseconds, holds AccessExclusiveLock briefly. Corresponds to MySQL INSTANT.

Table Rewrite : Creates a new physical relfilenode, copies and converts every row, rebuilds all indexes and constraints, then atomically swaps the file pointer. Holds AccessExclusiveLock for the entire duration (proportional to data size). Corresponds to MySQL COPY.

Online DDL (V500R002C00+) : Builds a shadow table, performs baseline copy while capturing incremental changes via logical decoding, replays increments until caught up, then acquires a short AccessExclusiveLock to swap pointers. Mechanism mirrors gh‑ost / pt‑osc but implemented natively in the kernel. Corresponds to MySQL INPLACE.

Additionally, index creation has a separate parallel path: CREATE INDEX CONCURRENTLY uses a two‑phase scan with incremental merge, similar to MySQL's online index build. A key difference from MySQL: GaussDB's ALTER TABLE is fully transactional—the entire rewrite runs inside a single transaction and rolls back completely on failure, leaving no orphan temporary tables.

DDL execution path overview
DDL execution path overview
ALTER TABLE execution path decision flowchart
ALTER TABLE execution path decision flowchart

1.2 Lock Mechanism

GaussDB uses an 8‑level table lock model (identical to PostgreSQL), from weakest to strongest:

AccessShareLock → RowShareLock → RowExclusiveLock → ShareUpdateExclusiveLock → ShareLock → ShareRowExclusiveLock → ExclusiveLock → AccessExclusiveLock

Most DDL operations default to AccessExclusiveLock (level 8), which conflicts with all other lock modes. A few operations use lower levels (e.g., CREATE INDEX CONCURRENTLY uses ShareUpdateExclusiveLock).

8‑level lock conflict matrix
8‑level lock conflict matrix
Lock levels used by specific DDL operations
Lock levels used by specific DDL operations

Both metadata‑only and table‑rewrite paths hold AccessExclusiveLock, but the lock window differs drastically: metadata‑only holds it for milliseconds, while table rewrite holds it for minutes to hours (e.g., 10 GB table → tens of minutes). A long‑running transaction holding a lower‑level lock (e.g., RowExclusiveLock) can block the DDL, and once the DDL enters the wait queue, all subsequent AccessShareLock requests (ordinary SELECT) are also blocked, causing a "queue‑head blocking" avalanche—the most common cause of production DDL failures.

1.3 Execution Flow Details

1.3.1 Path ①: Metadata‑Only (including "Fast Default")

When the ALTER TABLE sub‑command is marked as not requiring rewrite (does not trigger AT_PASS_REWRITE), only system catalogs are updated. For ADD COLUMN … DEFAULT, GaussDB adopts PostgreSQL 11's "fast default / missing value" mechanism: the default is stored in pg_attribute.attmissingval, and existing rows materialize the default on read without a full table update. Conditions for fast default (per official docs):

Column type in whitelist: BOOL, SMALLINT, INTEGER, BIGINT, NUMERIC, FLOAT, DOUBLE PRECISION, CHAR, VARCHAR, TEXT, TIMESTAMP(TZ), DATE, TIME(TZ), INTERVAL, BYTEA.

Default value serialized length ≤ 128 bytes.

Column has a non‑ NULL default.

Default contains no volatile functions (e.g., nextval(), random(); check pg_proc.provolatile='v').

Violating any condition (e.g., ADD COLUMN c serial or DEFAULT nextval(...)) falls back to Path ② (full table rewrite).

1.3.2 Path ②: Table Rewrite

Driven by ATRewriteTables → ExecRewriteRowTable / ExecRewriteCStoreTable (row‑store / column‑store). Row‑store rewrite steps:

Create new physical file.

Sequentially scan old table, evaluate expressions and convert types per row.

Batch‑write to new file.

Rebuild all indexes and constraints.

At transaction commit, atomically replace file pointer.

Entire process runs in a single large transaction holding AccessExclusiveLock. All DML queues; if a long‑running transaction exists, the DDL is first blocked by it, then blocks all new sessions.

Table rewrite flow
Table rewrite flow

Full AccessExclusiveLock blocks all SELECT / INSERT / UPDATE / DELETE.

Requires extra disk space ≈ 2× original table size at peak.

WAL volume ≈ new table data size; primary‑standby replication lag spikes.

Indexes rebuilt on new table, adding I/O; multiple indexes increase duration further.

1.3.3 Path ③: Online DDL (Four Phases)

Available from V500R002C00 for ALTER TABLE (column type changes, etc.), VACUUM FULL, tablespace moves, and index create/rebuild. Four phases:

Phase 1 – Prepare : Acquire AccessExclusiveLock, create shadow table, start logical decoding to capture increments, release lock. Lock held for seconds; business impact milliseconds to seconds.

Phase 2 – Baseline Copy (no lock on original) : Background task scans old table in batches, converts types, writes to shadow table. Business DML continues on old table; changes decoded to incremental log. Original table only read (no exclusive lock), shadow table uses RowExclusiveLock (compatible with DML). Duration proportional to data size (10 GB ≈ 20–30 min). Business impact: resource consumption only.

Phase 3 – Incremental Catch‑up (no lock) : Loop replaying incremental logs to shadow table; remaining increments shrink each round. When increment water‑mark falls below threshold, prepare for switch. Same lock level as Phase 2. Duration depends on write rate. No business impact.

Phase 4 – Atomic Switch (short lock) : Wait for in‑flight DML to finish, acquire AccessExclusiveLock, replay final increment batch, swap file pointers, commit DDL, release lock. Lock held for seconds; DML briefly waits during switch window.

Online DDL four phases
Online DDL four phases

Two auxiliary tables are used: ddlDeltaLog (stores all concurrent INSERT / UPDATE / DELETE during online DDL) and ctidMap (maps old ctid → new ctid during baseline copy).

1.3.4 Index Build Paths

Regular CREATE INDEX : Holds ShareLock (level 5), blocks writes but allows reads. Single scan, shorter duration.

CREATE INDEX CONCURRENTLY : Two full scans—first builds index without blocking reads/writes, second merges increments. Holds ShareUpdateExclusiveLock (level 4), no read/write blocking. Total time ~1.5–2× regular mode. Consumes extra CPU/IO. On failure leaves an INVALID index (must DROP INDEX and rebuild). Cannot run inside a transaction block. Partitioned table support varies by version; check version‑specific docs.

Index build comparison
Index build comparison

1.3.5 DROP COLUMN Logical Deletion

GaussDB (like PostgreSQL) does not physically remove column data on DROP COLUMN. Steps:

Set pg_attribute.attisdropped = true and clear attname.

Update pg_class.relnatts (valid column count).

Subsequent INSERT / UPDATE omit the column.

Old rows retain the physical space until the row is updated or VACUUM FULL rewrites the table.

Thus DROP COLUMN is an instantaneous metadata operation, but leaves "holes". Space reclamation requires a later VACUUM FULL (full table rewrite, incurring rewrite overhead).

1.4 Common DDL Operation Assessment (10 M rows / 10 GB row‑store table)

Assumptions: NVMe SSD, sequential write 200–400 MB/s, off‑peak, no long transactions, single DN / centralized deployment. Actual results vary with compression, index count, concurrent write rate, resource controls. Test in staging with same specs before production. Distributed deployments run in parallel across DNs (wall‑clock time usually lower) but add GTM/two‑phase commit overhead and node imbalance.

Add column (no default / default NULL) : Metadata‑only, online, milliseconds impact.

Add column with constant default (meets fast‑default conditions) : Metadata‑only, online, milliseconds impact.

Add column with default nextval / volatile function / long default : Table rewrite, offline, full blocking, 20–60 min.

Add multiple columns (all no default) : Metadata‑only, online, milliseconds.

Add column at specific position ( FIRST / AFTER col ) : Table rewrite, offline, 20–60 min.

Drop column ( DROP COLUMN ) : Metadata‑only, online, milliseconds. Logical delete.

Add regular secondary index ( CREATE INDEX ) : Semi‑online, blocks writes, 5–20 min.

Add secondary index concurrently ( CREATE INDEX CONCURRENTLY ) : Online, only first/last seconds affect business.

Change primary key ( DROP PK + ADD PK different column) : Offline by default, ADD phase blocks fully, 10–30 min.

Add partition ( ADD PARTITION ) : Metadata‑only, online, milliseconds.

Drop partition ( DROP PARTITION ) : File‑level delete, brief exclusive lock, seconds impact.

TRUNCATE TABLE : File‑level recreate, brief exclusive lock, seconds impact.

Increase VARCHAR length (e.g., 64→255) : Metadata‑only, online, milliseconds.

Decrease VARCHAR length (e.g., 255→64) : Table rewrite, offline, 20–60 min.

Change type char(n) → varchar(n) : Version‑dependent; typically table rewrite, offline, 20–60 min.

Increase numeric precision (e.g., numeric(10,2) → numeric(14,2) ) : Table rewrite, offline, 20–60 min.

Decrease numeric precision or change scale (e.g., numeric(10,2) → numeric(10,4) ) : Table rewrite, offline, 20–60 min.

Change table comment ( COMMENT ON TABLE ) : Metadata‑only, online, milliseconds.

Change column comment ( COMMENT ON COLUMN ) : Metadata‑only, online, milliseconds.

Add NOT NULL constraint ( SET NOT NULL ) : Full table scan validation (no physical rewrite), offline, exclusive lock during scan, 5–15 min.

Drop NOT NULL constraint ( DROP NOT NULL ) : Metadata‑only, online, milliseconds.

Change column default ( SET / DROP DEFAULT ) : Metadata‑only, online, milliseconds. Affects only future INSERT s; existing data not backfilled.

Change table charset : Major difference from MySQL: GaussDB (PG kernel) sets encoding at CREATE DATABASE; database‑level encoding cannot be altered online.

DDL operation assessment table 1
DDL operation assessment table 1
DDL operation assessment table 2
DDL operation assessment table 2
DDL operation assessment table 3
DDL operation assessment table 3

1.5 WAL and Undo Space Usage

Estimates for Ustore storage engine:

Metadata DDL : WAL only catalog page changes (KB–MB); undo negligible.

Table‑rewrite DDL : Equivalent to inserting full data into new file. WAL increment ≈ 1–2× table size. Undo generated per inserted row; testing shows ~55 bytes per row on average. Large rewrites must monitor undo space.

CREATE INDEX : WAL ≈ physical index size (mostly full‑page writes); undo for index‑build transaction.

WAL and undo usage
WAL and undo usage

The parameter undo_limit_size_per_transaction caps undo per transaction. If a huge table rewrite exceeds this limit, the DDL fails. Pre‑evaluate undo consumption based on row count before running.

1.6 Comparison with MySQL 8

GaussDB has no explicit ALGORITHM option; some versions support an ONLINE parameter to force online DDL.

GaussDB DDL is a single transaction—failure rolls back entirely; MySQL COPY can leave temporary tables.

Adding a column with non‑ NULL default triggers table rewrite in GaussDB (unless fast‑default conditions met); MySQL 8 may use INSTANT for some cases. DROP COLUMN is logical (instant) in GaussDB; MySQL typically rebuilds table.

Both default to strongest exclusive lock ( AccessExclusiveLock / MDL exclusive), so both suffer "long transaction blocks DDL, DDL blocks all subsequent sessions" queue‑head blocking.

MySQL vs GaussDB DDL comparison
MySQL vs GaussDB DDL comparison
Note: Mechanisms based on GaussDB/openGauss public docs and kernel source analysis. Duration and log estimates assume specific hardware; behavior varies across versions (especially V500R002/503/505 vs V2.0‑25.x online DDL scope), deployment modes (centralized/distributed/disaggregated), and storage engines (row/column/Ustore/Astore). Always verify with the official SQL Reference and Feature Description · High Availability · Online DDL for your version, and validate in staging.
References:

openGauss Online DDL Feature Overview

Huawei Cloud GaussDB Centralized Developer Guide: Online DDL and Related Operations

Huawei Cloud GaussDB ALTER TABLE Syntax

Database Series: Large Table DDL Change Issues

Database Series: InnoDB Online DDL Implementation Mechanism

Database DDL Operation Algorithms and Impact Analysis

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

MySQL comparisonOnline DDLPostgreSQLWALDDLGaussDBlock mechanismsindex buildingdrop columntable rewriteundo logs

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion