ADD COLUMN

The ALTER TABLE.. ADD COLUMN statement adds a column to an existing table. This operation is online in TiDB, which means that neither reads or writes to the table are blocked by adding a column.

Synopsis

AlterTableStmt

ADD COLUMN - 图1

TableName

ADD COLUMN - 图2

AddColumnSpec

ADD COLUMN - 图3

ColumnType

ADD COLUMN - 图4

ColumnOption

ADD COLUMN - 图5

  1. AlterTableStmt
  2. ::= 'ALTER' 'IGNORE'? 'TABLE' TableName AddColumnSpec ( ',' AddColumnSpec )*
  3. TableName ::=
  4. Identifier ('.' Identifier)?
  5. AddColumnSpec
  6. ::= 'ADD' 'COLUMN' 'IF NOT EXISTS'? ColumnName ColumnType ColumnOption+ ( 'FIRST' | 'AFTER' ColumnName )?
  7. ColumnType
  8. ::= NumericType
  9. | StringType
  10. | DateAndTimeType
  11. | 'SERIAL'
  12. ColumnOption
  13. ::= 'NOT'? 'NULL'
  14. | 'AUTO_INCREMENT'
  15. | 'PRIMARY'? 'KEY' ( 'CLUSTERED' | 'NONCLUSTERED' )?
  16. | 'UNIQUE' 'KEY'?
  17. | 'DEFAULT' ( NowSymOptionFraction | SignedLiteral | NextValueForSequence )
  18. | 'SERIAL' 'DEFAULT' 'VALUE'
  19. | 'ON' 'UPDATE' NowSymOptionFraction
  20. | 'COMMENT' stringLit
  21. | ( 'CONSTRAINT' Identifier? )? 'CHECK' '(' Expression ')' ( 'NOT'? ( 'ENFORCED' | 'NULL' ) )?
  22. | 'GENERATED' 'ALWAYS' 'AS' '(' Expression ')' ( 'VIRTUAL' | 'STORED' )?
  23. | 'REFERENCES' TableName ( '(' IndexPartSpecificationList ')' )? Match? OnDeleteUpdateOpt
  24. | 'COLLATE' CollationName
  25. | 'COLUMN_FORMAT' ColumnFormat
  26. | 'STORAGE' StorageMedia
  27. | 'AUTO_RANDOM' ( '(' LengthNum ')' )?

Examples

  1. mysql> CREATE TABLE t1 (id INT NOT NULL PRIMARY KEY AUTO_INCREMENT);
  2. Query OK, 0 rows affected (0.11 sec)
  3. mysql> INSERT INTO t1 VALUES (NULL);
  4. Query OK, 1 row affected (0.02 sec)
  5. mysql> SELECT * FROM t1;
  6. +----+
  7. | id |
  8. +----+
  9. | 1 |
  10. +----+
  11. 1 row in set (0.00 sec)
  12. mysql> ALTER TABLE t1 ADD COLUMN c1 INT NOT NULL;
  13. Query OK, 0 rows affected (0.28 sec)
  14. mysql> SELECT * FROM t1;
  15. +----+----+
  16. | id | c1 |
  17. +----+----+
  18. | 1 | 0 |
  19. +----+----+
  20. 1 row in set (0.00 sec)
  21. mysql> ALTER TABLE t1 ADD c2 INT NOT NULL AFTER c1;
  22. Query OK, 0 rows affected (0.28 sec)
  23. mysql> SELECT * FROM t1;
  24. +----+----+----+
  25. | id | c1 | c2 |
  26. +----+----+----+
  27. | 1 | 0 | 0 |
  28. +----+----+----+
  29. 1 row in set (0.00 sec)

MySQL compatibility

  • Adding a new column and setting it to the PRIMARY KEY is not supported.
  • Adding a new column and setting it to AUTO_INCREMENT is not supported.
  • There are limitations on adding generated columns, refer to: generated column limitations.

See also