ALTER TABLE modifies the schema of an existing table in AnalyticDB for MySQL. Use it to rename tables and columns, change column data types and constraints, manage indexes, adjust partition lifecycles, and configure tiered storage policies.
Sample table
Most examples in this topic use the customer table. If you have not created it yet, run the following statement:
Examples for JSON indexes, foreign keys, and vector indexes use their own table definitions.
Syntax
ALTER TABLE table_name
{ ADD [COLUMN] column_name column_definition
| ADD [COLUMN] (column_name column_definition,...)
| ADD [CONSTRAINT [symbol]] FOREIGN KEY (fk_column_name) REFERENCES pk_table_name (pk_column_name)
| ADD {INDEX|KEY} [index_name] (column_name)
| ADD {INDEX|KEY} [index_name] (column_name|column_name->'$.json_path')
| ADD {INDEX|KEY} [index_name] (column_name->'$[*]')
| ADD CLUSTERED [INDEX|KEY] [index_name] (column_name [ASC|DESC])
| ADD FULLTEXT [INDEX|KEY] index_name (column_name) [index_option]
| ADD ANN [INDEX|KEY] [index_name] (column_name) [algorithm=HNSW_PQ ] [distancemeasure=SquaredL2]
| COMMENT 'comment'
| DROP CLUSTERED KEY index_name
| DROP [COLUMN] column_name
| DROP FOREIGN KEY symbol
| DROP FULLTEXT INDEX index_name
| DROP {INDEX|KEY} index_name
| DROP PARTITION (partition_name,...)
| MODIFY [COLUMN] column_name column_definition
| RENAME COLUMN column_name TO new_column_name
| RENAME new_table_name
| INDEX_ALL = {'Y'|'N'}
| storage_policy
| PARTITION BY VALUE{(column_name)|(DATE_FORMAT(column_name, 'format'))|(FROM_UNIXTIME(column_name, 'format'))} LIFECYCLE N
}
column_definition:
column_type [column_attributes][column_constraints][COMMENT 'comment']
column_attributes:
[DEFAULT{constant|CURRENT_TIMESTAMP}|AUTO_INCREMENT]
column_constraints:
[NULL|NOT NULL]
storage_policy:
STORAGE_POLICY= {'HOT'|'COLD'|'MIXED' hot_partition_count=N}Tables
Rename a table
ALTER TABLE db_name.table_name RENAME new_table_nameExample: Rename customer to new_customer.
ALTER TABLE customer RENAME new_customer;Change a table comment
ALTER TABLE db_name.table_name COMMENT 'comment'Example: Update the comment on the customer table.
ALTER TABLE customer COMMENT 'Customer table';Columns
Add a column
ALTER TABLE db_name.table_name ADD [COLUMN]
{column_name column_type [DEFAULT {constant|CURRENT_TIMESTAMP}|AUTO_INCREMENT] [NULL|NOT NULL] [COMMENT 'comment']
| (column_name column_type [DEFAULT {constant|CURRENT_TIMESTAMP}|AUTO_INCREMENT] [NULL|NOT NULL] [COMMENT 'comment'],...)}Primary key columns cannot be added.
Example 1: Add a province column of the VARCHAR type to customer.
ALTER TABLE adb_demo.customer ADD COLUMN province VARCHAR COMMENT 'Province';Example 2: Add two columns at once — vip of the BOOLEAN type and tags of the VARCHAR type.
ALTER TABLE adb_demo.customer ADD COLUMN (vip BOOLEAN COMMENT 'Is VIP', tags VARCHAR DEFAULT 'None' COMMENT 'Tag');Drop a column
ALTER TABLE db_name.table_name DROP [COLUMN] column_namePrimary key columns cannot be dropped.
Example: Drop the province column from customer.
ALTER TABLE adb_demo.customer DROP COLUMN province;Rename a column
ALTER TABLE db_name.table_name RENAME COLUMN column_name TO new_column_namePrimary key columns cannot be renamed.
Example: Rename city_name to city in customer.
ALTER TABLE customer RENAME COLUMN city_name TO city;Change a column data type
ALTER TABLE db_name.table_name MODIFY [COLUMN] column_name new_column_typeData type changes follow widening-only rules — you can expand a type's range but not shrink it. The table below summarizes supported changes:
| Change | Supported |
|---|---|
| Smaller integer to larger integer (e.g., TINYINT to BIGINT) | Yes |
| Larger integer to smaller integer (e.g., BIGINT to TINYINT) | No |
| FLOAT to DOUBLE | Yes |
| DOUBLE to FLOAT | No |
| Integer type to floating-point type (FLOAT or DOUBLE) | Yes (version requirement applies) |
| Increase DECIMAL precision | Yes (version requirement applies) |
| Decrease DECIMAL precision | No |
| Primary key column data type change | No |
Changing an integer type to a floating-point type and increasing DECIMAL precision require a cluster with kernel version 3.1.8.10–3.1.8.x, 3.1.9.6–3.1.9.x, 3.1.10.3–3.1.10.x, or 3.2.0.1 or later.
Example: Change the age column from INT to BIGINT.
ALTER TABLE adb_demo.customer MODIFY COLUMN age BIGINT;Change a column default value
ALTER TABLE db_name.table_name MODIFY [COLUMN] column_name column_type DEFAULT {constant | CURRENT_TIMESTAMP}Example 1: Set the default value of sex to 0.
ALTER TABLE adb_demo.customer MODIFY COLUMN sex INT NOT NULL DEFAULT 0;Example 2: Set the default value of login_time to CURRENT_TIMESTAMP.
ALTER TABLE adb_demo.customer MODIFY COLUMN login_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;Allow NULL values
ALTER TABLE db_name.table_name MODIFY [COLUMN] column_name column_type NULLOnly NOT NULL to NULL changes are supported. Changing NULL to NOT NULL is not supported.
Example: Allow province to accept NULL values.
ALTER TABLE adb_demo.customer MODIFY COLUMN province VARCHAR NULL;Change a column comment
ALTER TABLE db_name.table_name MODIFY [COLUMN] column_name column_type COMMENT 'new_comment'Example: Update the comment on the province column.
ALTER TABLE adb_demo.customer MODIFY COLUMN province VARCHAR COMMENT 'The province where the customer is located';Indexes
Add a regular index
By default, XUANWU_V2 tables are created without full-column indexes (INDEX_ALL='N'), while XUANWU tables include them (INDEX_ALL='Y'). Add an index to individual columns as needed.
ALTER TABLE db_name.table_name ADD {INDEX|KEY} [index_name] (column_name)The column must have a simple data type. For JSON columns, see Add a JSON index.
Example: Add an index to the age column.
ALTER TABLE adb_demo.customer ADD KEY age_idx(age);Modify full-column indexes
For XUANWU_V2 tables, toggle full-column indexing after table creation using the INDEX_ALL property. This setting does not affect JSON, full-text, or vector indexes.
Prerequisites
The XUANWU_V2 table must be in a cluster with kernel version 3.2.3.7 or later, or 3.2.4.3 or later.
To view and update the minor version of your cluster, log on to the AnalyticDB for MySQL console and go to the Configuration Information section of the Cluster Information page.
ALTER TABLE db_name.table_name INDEX_ALL = {'Y'|'N'};| Value | Effect |
|---|---|
Y | Full-column index mode: creates regular indexes for all columns |
N | Non-full-column index mode: keeps only the primary key index; all other regular indexes are removed |
Usage notes:
For XUANWU tables, full-column indexing can only be configured at table creation time. To disable it, drop indexes individually.
If
INDEX_ALL='Y'and you drop a regular index using a Data Definition Language (DDL) statement, the property automatically changes toINDEX_ALL='N'. Only the target index is removed; other indexes are unaffected.When
INDEX_ALL='N',SHOW CREATE TABLEmay not explicitly display this property, but it is still in effect.
Example 1: Disable full-column indexing on customer (currently INDEX_ALL='Y').
ALTER TABLE adb_demo.customer INDEX_ALL = 'N';After execution, regular indexes on non-primary key columns such as customer_name, city_name, and sex are dropped.
Example 2: Enable full-column indexing on customer (currently INDEX_ALL='N', with existing indexes on customer_id, phone_num, and login_time).
ALTER TABLE adb_demo.customer INDEX_ALL = 'Y';After execution, regular indexes are created for all columns that do not already have one, such as customer_name, city_name, and sex.
Add a JSON index
Usage notes
JSON index behavior differs by table engine:
XUANWU_V2 tables (partitioned and non-partitioned): the index takes effect immediately — no BUILD job needed.
Non-partitioned XUANWU tables: the index takes effect only after a BUILD job completes.
Partitioned XUANWU tables: manually trigger a full-table BUILD job. The index takes effect only after the BUILD job completes.
JSON indexes
ALTER TABLE db_name.table_name ADD {INDEX|KEY} [index_name] (column_name|column_name->'$.json_path')| Parameter | Description |
|---|---|
column_name | Creates an index on a JSON column. The column must be of the JSON type. |
column_name->'$.json_path' | Creates an index on a specific property key in a JSON object. For more information, see JSON indexes. |
The
column_name->'$.json_path'syntax requires cluster version V3.1.6.8 or later. To view and update the minor version, log on to the AnalyticDB for MySQL console and go to the Configuration Information section of the Cluster Information page.If a JSON column already has an index, drop it before creating an index on a property key of that column.
Example: Create a JSON index on the a property of the vj column.
CREATE TABLE json_test(
id INT,
vj JSON
)
DISTRIBUTED BY HASH(id);
INSERT INTO json_test VALUES(1,'{"a":1,"b":2}'),(2,'{"a":2,"b":3}');ALTER TABLE json_test ADD KEY age_idx(vj->'$.a');JSON Array indexes
ALTER TABLE db_name.table_name ADD {INDEX|KEY} [index_name] (column_name->'$[*]')column_name->'$[*]' specifies the JSON Array column to index. For example, vj->'$[*]' creates a JSON Array index on the vj column.
Example: Create a JSON Array index on the vj column.
CREATE TABLE json_test(
id INT,
vj JSON
)
DISTRIBUTED BY HASH(id);
INSERT INTO json_test VALUES(1, '["CP-018673", 1, false]');ALTER TABLE json_test ADD KEY index_vj(vj->'$[*]');Drop a regular or JSON index
ALTER TABLE db_name.table_name DROP KEY index_nameRun SHOW INDEX FROM db_name.table_name; to find the index name.
Example 1: Drop the age_idx index from customer.
ALTER TABLE adb_demo.customer DROP KEY age_idx;Example 2: Drop the JSON Array index index_vj from json_test.
ALTER TABLE adb_demo.customer DROP KEY index_vj;Add a clustered index
ALTER TABLE db_name.table_name ADD CLUSTERED [INDEX|KEY] [index_name] (column_name1 [ASC|DESC], column_name2 [ASC|DESC])Usage notes:
Clustered indexes sort in ascending order (ASC) by default. For workloads that sort in descending order, set DESC when you create the table.
A table can have only one clustered index.
After adding a clustered index, trigger and complete a BUILD job for it to take effect. Run
SHOW CREATE TABLE db_name.table_name;to confirm.
Example: Add a clustered index on customer_id.
ALTER TABLE adb_demo.customer ADD CLUSTERED KEY (customer_id ASC);Drop a clustered index
ALTER TABLE db_name.table_name DROP CLUSTERED KEY index_nameRun SHOW CREATE TABLE db_name.table_name to find the clustered index name.
Example: Drop the clustered index named index from customer.
ALTER TABLE adb_demo.customer DROP CLUSTERED KEY index;Add a full-text index
Prerequisites
An AnalyticDB for MySQL cluster of V3.1.4.9 or later. For best results, use V3.1.4.17 or later.
For information about how to query the minor version, see How do I query the version of an AnalyticDB for MySQL cluster?
ALTER TABLE db_name.table_name ADD FULLTEXT [INDEX|KEY] index_name (column_name) [index_option]| Parameter | Description |
|---|---|
column_name | The column to index. Must be of the VARCHAR type. |
index_option | Optional. Specifies the tokenizer and custom dictionary. |
WITH ANALYZER analyzer_name | The analyzer for the full-text index. See Analyzers for full-text indexes. |
WITH DICT tbl_dict_name | The custom dictionary for the full-text index. See Custom dictionaries for full-text indexes. |
A full-text index takes effect only after a BUILD job is triggered and completed.
Example: Add a full-text index to the home_address column using the standard analyzer.
ALTER TABLE adb_demo.customer ADD FULLTEXT INDEX fidx_k(home_address) WITH ANALYZER standard;For more information, see Create a full-text index.
Drop a full-text index
ALTER TABLE db_name.table_name DROP FULLTEXT INDEX index_nameExample: Drop the fidx_k full-text index from customer.
ALTER TABLE adb_demo.customer DROP FULLTEXT INDEX fidx_k;Add a vector index
Prerequisites
An AnalyticDB for MySQL cluster of V3.1.4.0 or later. Recommended minor versions: 3.1.5.16, 3.1.6.8, 3.1.8.6, and later.
If your cluster is not on one of the recommended versions, set CSTORE_PROJECT_PUSH_DOWN and CSTORE_PPD_TOP_N_ENABLE to false before using vector search. To update the minor version, contact technical support. For information about how to query the minor version, see How do I query the version of an AnalyticDB for MySQL cluster?
ALTER TABLE db_name.table_name ADD ANN [INDEX|KEY] [index_name] (column_name) [algorithm=HNSW_PQ] [distancemeasure=SquaredL2]| Parameter | Description |
|---|---|
index_name | The index name. For naming conventions, see the Naming limits section. |
column_name | The vector column to index. The column type must be array<float>, array<byte>, or array<smallint>. |
algorithm | The algorithm used to calculate vector distance. Set to HNSW_PQ. |
distancemeasure | The distance formula. Set to SquaredL2. Formula: (x1-y1)^2 + (x2-y2)^2 + ... + (xn-yn)^2. |
Example: Create vector indexes on the float_feature and short_feature columns.
CREATE TABLE vector (
xid BIGINT NOT NULL,
cid BIGINT NOT NULL,
uid VARCHAR NOT NULL,
vid VARCHAR NOT NULL,
wid VARCHAR NOT NULL,
float_feature array<FLOAT>(4),
short_feature array<SMALLINT>(4),
PRIMARY KEY (xid, cid, vid)
) DISTRIBUTED BY HASH(xid);ALTER TABLE vector ADD ANN INDEX idx_float_feature(float_feature);
ALTER TABLE vector ADD ANN INDEX idx_short_feature(short_feature);Add a foreign key
Prerequisites
An AnalyticDB for MySQL cluster of V3.1.10 or later.
To view and update the minor version, log on to the AnalyticDB for MySQL console and go to the Configuration Information section of the Cluster Information page.
ALTER TABLE db_name.table_name ADD [CONSTRAINT [symbol]] FOREIGN KEY (fk_column_name) REFERENCES db_name.pk_table_name (pk_column_name)| Parameter | Description |
|---|---|
db_name.table_name | The table to add the foreign key to. |
symbol | Optional. The name of the foreign key constraint — must be unique within the table. If omitted, the parser uses <fk_column_name>_fk as the constraint name. |
fk_column_name | The foreign key column. Must already exist. |
pk_table_name | The primary table. Must already exist. |
pk_column_name | The primary key column of the primary table. Must already exist. |
Usage notes:
A table can have multiple foreign key indexes.
A foreign key index cannot span multiple columns (e.g.,
FOREIGN KEY (sr_item_sk, sr_ticket_number)is not supported).AnalyticDB for MySQL does not enforce data constraints. Validate the constraint relationship between primary and foreign keys in your application.
Foreign key constraints cannot be added to external tables.
Example: Add a foreign key on store_sales referencing the item table.
CREATE TABLE item
(
i_item_sk BIGINT NOT NULL,
i_current_price BIGINT,
PRIMARY KEY(i_item_sk)
)
DISTRIBUTED BY HASH(i_item_sk);
CREATE TABLE store_sales
(
ss_sale_id BIGINT,
ss_store_sk BIGINT,
ss_item_sk BIGINT NOT NULL,
PRIMARY KEY(ss_sale_id)
);ALTER TABLE store_sales ADD CONSTRAINT ss_item_sk FOREIGN KEY (ss_item_sk) REFERENCES item (i_item_sk);For more information, see Eliminate unnecessary joins using primary and foreign key constraints.
Drop a foreign key
ALTER TABLE db_name.table_name DROP FOREIGN KEY fk_symbolExample:
ALTER TABLE store_returns DROP FOREIGN KEY sr_item_sk_fk;Partitions
Change the partition function format
Prerequisites
To change the partition function, your AnalyticDB for MySQL cluster must meet all of the following conditions:
The kernel version is 3.2.1.6, 3.2.2.5, 3.2.3.1, or 3.2.4.0 or later.
NoteTo view and update the minor version, go to the Configuration Information section on the Cluster Information page in the AnalyticDB for MySQL console.
Contact Alibaba Cloud technical support to enable the feature that lets you change the partition function.
Syntax
ALTER TABLE table_name PARTITION BY VALUE{(column_name)|(DATE_FORMAT(column_name, 'format'))|(FROM_UNIXTIME(column_name, 'format'))} LIFECYCLE N Notes
For XUANWU tables in clusters with a kernel version of 3.2.4.1 or later, you can remove the partition lifecycle by setting the LIFECYCLE parameter
Nto0or by omittingLIFECYCLE N.You cannot change a non-partitioned table to a partitioned table, or a partitioned table to a non-partitioned table. This means you cannot add or delete partition keys.
You cannot add, delete, or change partition fields based on existing partition keys.
You can change the partition function between
PARTITION BY VALUE(column)andPARTITION BY VALUE(DATE_FORMAT(...))orPARTITION BY VALUE(FROM_UNIXTIME(...)).You can change the
format.After you change the partition function, the new partition function format takes effect only after a BUILD job for the table is re-triggered and completed. You can run the
SHOW CREATE TABLE db_name.table_name;statement to check whether the new partition function format has taken effect.
Examples
Change the partitioning method for the
customertable fromPARTITION BY VALUE(login_time) LIFECYCLE 10toPARTITION BY VALUE(DATE_FORMAT(login_time, '%Y%m')) LIFECYCLE 20.ALTER TABLE adb_demo.test PARTITION BY VALUE(DATE_FORMAT(login_time, '%Y%m')) LIFECYCLE 20;Change the partitioning method for the
customertable fromPARTITION BY VALUE(FROM_UNIXTIME(login_time, '%Y%m%d')) LIFECYCLE 20toPARTITION BY VALUE(FROM_UNIXTIME(login_time, '%Y%m')) LIFECYCLE 30.ALTER TABLE adb_demo.test PARTITION BY VALUE(FROM_UNIXTIME(login_time, '%Y%m')) LIFECYCLE 30;Change the partitioning method for the
customertable fromPARTITION BY VALUE(login_time) LIFECYCLE 20toPARTITION BY VALUE(DATE_FORMAT(login_time, '%Y%m')).ALTER TABLE adb_demo.test PARTITION BY VALUE(DATE_FORMAT(login_time, '%Y%m'));
Change the partition function format
Prerequisites
To change the partition function, your AnalyticDB for MySQL cluster must meet all of the following conditions:
The kernel version is 3.2.1.6, 3.2.2.5, 3.2.3.1, or 3.2.4.0 or later.
NoteTo view and update the minor version, go to the Configuration Information section on the Cluster Information page in the AnalyticDB for MySQL console.
Contact Alibaba Cloud technical support to enable the feature that lets you change the partition function.
Syntax
ALTER TABLE table_name PARTITION BY VALUE{(column_name)|(DATE_FORMAT(column_name, 'format'))|(FROM_UNIXTIME(column_name, 'format'))} LIFECYCLE N Notes
For XUANWU tables in clusters with a kernel version of 3.2.4.1 or later, you can remove the partition lifecycle by setting the LIFECYCLE parameter
Nto0or by omittingLIFECYCLE N.You cannot change a non-partitioned table to a partitioned table, or a partitioned table to a non-partitioned table. This means you cannot add or delete partition keys.
You cannot add, delete, or change partition fields based on existing partition keys.
You can change the partition function between
PARTITION BY VALUE(column)andPARTITION BY VALUE(DATE_FORMAT(...))orPARTITION BY VALUE(FROM_UNIXTIME(...)).You can change the
format.After you change the partition function, the new partition function format takes effect only after a BUILD job for the table is re-triggered and completed. You can run the
SHOW CREATE TABLE db_name.table_name;statement to check whether the new partition function format has taken effect.
Examples
Change the partitioning method for the
customertable fromPARTITION BY VALUE(login_time) LIFECYCLE 10toPARTITION BY VALUE(DATE_FORMAT(login_time, '%Y%m')) LIFECYCLE 20.ALTER TABLE adb_demo.test PARTITION BY VALUE(DATE_FORMAT(login_time, '%Y%m')) LIFECYCLE 20;Change the partitioning method for the
customertable fromPARTITION BY VALUE(FROM_UNIXTIME(login_time, '%Y%m%d')) LIFECYCLE 20toPARTITION BY VALUE(FROM_UNIXTIME(login_time, '%Y%m')) LIFECYCLE 30.ALTER TABLE adb_demo.test PARTITION BY VALUE(FROM_UNIXTIME(login_time, '%Y%m')) LIFECYCLE 30;Change the partitioning method for the
customertable fromPARTITION BY VALUE(login_time) LIFECYCLE 20toPARTITION BY VALUE(DATE_FORMAT(login_time, '%Y%m')).ALTER TABLE adb_demo.test PARTITION BY VALUE(DATE_FORMAT(login_time, '%Y%m'));
Change the partition lifecycle
ALTER TABLE db_name.table_name PARTITIONS NUsage notes:
On clusters with kernel version 3.2.4.1 or later, set
Nto0to remove partition lifecycle management.The new lifecycle takes effect only after a BUILD job is triggered and completed. Run
SHOW CREATE TABLE db_name.table_name;to verify.
Example 1: Remove the lifecycle from customer.
ALTER TABLE customer PARTITIONS 0;Example 2: Change the lifecycle from 30 days to 40 days.
ALTER TABLE customer PARTITIONS 40;Drop a partition
ALTER TABLE DROP PARTITIONhas the same effect asTRUNCATE TABLE PARTITION.
ALTER TABLE db_name.table_name DROP PARTITION (partition_name,...)Dropping a partition permanently deletes all data in that partition. This action cannot be undone.
Example 1: Drop the 20241220 partition from customer.
ALTER TABLE adb_demo.customer DROP PARTITION (20241220);Example 2: Drop the 20241218 and 20241219 partitions.
ALTER TABLE adb_demo.customer DROP PARTITION (20241218,20241219);Storage policies
Change the tiered storage policy
Prerequisites
The cluster is the Enterprise Edition, Basic Edition, Data Lakehouse Edition, or Data Warehouse Edition (Elastic mode).
Kernel version requirements:
XUANWU tables: no kernel version restriction.
XUANWU_V2 tables: kernel version must be 3.2.2.15 or later, 3.2.3.13 or later, 3.2.4.9 or later, or 3.2.5.3 or later.
To view and update the minor version, log on to the AnalyticDB for MySQL console and go to the Configuration Information section of the Cluster Information page.
For XUANWU_V2 tables, the scheduled task for moving data between hot and cold storage must be enabled:
Check the status:
SHOW ADB_CONFIG KEY=SERVERLESS_DATA_STORAGE_CHANGE_SCHEDULE_ENABLE;If the result is
FALSE, the task is disabled and must be enabled.If an error is returned, the parameter has not been set and defaults to
TRUE.
Enable the task:
SET ADB_CONFIG SERVERLESS_DATA_STORAGE_CHANGE_SCHEDULE_ENABLE = true;
ALTER TABLE db_name.table_name STORAGE_POLICY= {'HOT'|'COLD'|'MIXED' hot_partition_count=N}The new storage policy takes effect only after a BUILD job is triggered and completed for the table. By default, this job runs automatically in the background. Before the BUILD job completes, the number of hot partitions reported byinformation_schema.table_usagemay differ from the configured policy. RunSHOW CREATE TABLE db_name.table_name;to confirm the policy is in effect.
Example 1: Set the storage policy to COLD.
ALTER TABLE customer storage_policy = 'COLD';Example 2: Set the storage policy to HOT.
ALTER TABLE customer storage_policy = 'HOT';Example 3: Set the storage policy to MIXED with 10 hot partitions.
ALTER TABLE customer storage_policy = 'MIXED' hot_partition_count = 10;Clear partitions in a table
Syntax
ALTER TABLE table_name TRUNCATE PARTITION {partition_names | ALL}Example
ALTER TABLE adb_demo.customer TRUNCATE PARTITION ALL;