Изменение таблиц и столбцов
Последнее обновление: 11.05.2018
Если таблица уже была ранее создана, и ее необходимо изменить, то для этого применяется команда ALTER TABLE. Ее
сокращенный формальный синтаксис:
ALTER TABLE название_таблицы { ADD название_столбца тип_данных_столбца [атрибуты_столбца] | DROP COLUMN название_столбца | MODIFY COLUMN название_столбца тип_данных_столбца [атрибуты_столбца] | ALTER COLUMN название_столбца SET DEFAULT значение_по_умолчанию | ADD [CONSTRAINT] определение_ограничения | DROP [CONSTRAINT] имя_ограничения}
Вообще данная команда поддерживает гораздо больше опций и возможностей. Все их можно посмотреть в документации. Рассмотрим лишь основные сценарии,
с которыми мы можем столкнуться.
Добавление нового столбца
Добавим в таблицу Customers новый столбец Address:
ALTER TABLE Customers ADD Address VARCHAR(50) NULL;
В данном случае столбец Address имеет тип VARCHAR и для него определен атрибут NULL.
Удаление столбца
Удалим столбец Address из таблицы Customers:
ALTER TABLE Customers DROP COLUMN Address;
Изменение значения по умолчанию
Установим в таблице Customers для столбца Age значение по умолчанию 22:
ALTER TABLE Customers ALTER COLUMN Age SET DEFAULT 22;
Изменение типа столбца
Изменим в таблице Customers тип данных у столбца FirstName на CHAR(100)
и установим для него атрибут NULL
:
ALTER TABLE Customers MODIFY COLUMN FirstName CHAR(100) NULL;
Добавление и удаление внешнего ключа
Пусть изначально в базе данных будут добавлены две таблицы, никак не связанные:
CREATE TABLE Customers ( Id INT PRIMARY KEY AUTO_INCREMENT, Age INT, FirstName VARCHAR(20) NOT NULL, LastName VARCHAR(20) NOT NULL ); CREATE TABLE Orders ( Id INT PRIMARY KEY AUTO_INCREMENT, CustomerId INT, CreatedAt Date );
Добавим ограничение внешнего ключа к столбцу CustomerId таблицы Orders:
ALTER TABLE Orders ADD FOREIGN KEY(CustomerId) REFERENCES Customers(Id);
При добавлении ограничений мы можем указать для них имя, используя оператор CONSTRAINT, после которого указывается имя
ограничения:
ALTER TABLE Orders ADD CONSTRAINT orders_customers_fk FOREIGN KEY(CustomerId) REFERENCES Customers(Id);
В данном случае ограничение внешнего ключа называется orders_customers_fk. Затем по этому имени мы можем удалить ограничение:
ALTER TABLE Orders DROP FOREIGN KEY orders_customers_fk;
Добавление и удаление первичного ключа
Добавим в таблицу Products первичный ключ:
CREATE TABLE Products ( Id INT, Model VARCHAR(20) ); ALTER TABLE Products ADD PRIMARY KEY (Id);
Теперь удалим первичный ключ:
ALTER TABLE Products DROP PRIMARY KEY;
Summary: in this tutorial, you will learn how to use the MySQL ALTER TABLE
statement to add a column, alter a column, rename a column, drop a column and rename a table.
Setting up a sample table
Let’s create a table named vehicles
for the demonstration:
Code language: SQL (Structured Query Language) (sql)
CREATE TABLE vehicles ( vehicleId INT, year INT NOT NULL, make VARCHAR(100) NOT NULL, PRIMARY KEY(vehicleId) );
MySQL ALTER TABLE
– Add columns to a table
The ALTER TABLE ADD
statement allows you to add one or more columns to a table.
1) Add a column to a table
To add a column to a table, you use the ALTER TABLE ADD
syntax:
Code language: SQL (Structured Query Language) (sql)
ALTER TABLE table_name ADD new_column_name column_definition [FIRST | AFTER column_name]
In this syntax:
table_name
– specify the name of the table that you want to add a new column or columns after theALTER TABLE
keywords.new_column_name
– specify the name of the new column.column_definition
– specify the datatype, maximum size, and column constraint of the new columnFIRST | AFTER column_name
specify the position of the new column in the table. You can add a column after an existing column (ATER column_name
) or as the first column (FIRST
). If you omit this clause, the column is appended at the end of the column list of the table.
The following example uses the ALTER TABLE ADD
statement to add a column at the end of the vehicles
table:
ALTER TABLE vehicles ADD model VARCHAR(100) NOT NULL;
Code language: SQL (Structured Query Language) (sql)
This statement shows the column list of the vehicles
table:
Code language: SQL (Structured Query Language) (sql)
DESCRIBE vehicles;
As shown clearly from the output, the column model
has been added to the vehicles
table.
2) Add multiple columns to a table
To add multiple columns to a table, you use the following form of the ALTER TALE ADD
statement:
Code language: SQL (Structured Query Language) (sql)
ALTER TABLE table_name ADD new_column_name column_definition [FIRST | AFTER column_name], ADD new_column_name column_definition [FIRST | AFTER column_name], ...;
For example, this statement adds two columns color
and note
to the vehicles
table:
Code language: SQL (Structured Query Language) (sql)
ALTER TABLE vehicles ADD color VARCHAR(50), ADD note VARCHAR(255);
This statement shows the new structure of the vehicles
table:
DESCRIBE vehicles;
Code language: SQL (Structured Query Language) (sql)
MySQL ALTER TABLE
– Modify columns
1) Modify a column
Here is the basic syntax for modifying a column in a table:
Code language: SQL (Structured Query Language) (sql)
ALTER TABLE table_name MODIFY column_name column_definition [ FIRST | AFTER column_name];
It’s a good practice to view the attributes of a column before modifying it.
Suppose that you want to change the note
column a NOT NULL
column with a maximum of 100 characters.
First, show the column list of the vehicles
table:
Code language: SQL (Structured Query Language) (sql)
DESCRIBE vehicles;
Then, modify the note
column:
Code language: SQL (Structured Query Language) (sql)
ALTER TABLE vehicles MODIFY note VARCHAR(100) NOT NULL;
Finally, show the column list of the vehicles
table to verify the change:
Code language: SQL (Structured Query Language) (sql)
DESCRIBE vehicles;
2) Modify multiple columns
The following statement allows you to modify multiple columns:
Code language: SQL (Structured Query Language) (sql)
ALTER TABLE table_name MODIFY column_name column_definition [ FIRST | AFTER column_name], MODIFY column_name column_definition [ FIRST | AFTER column_name], ...;
First, show the current columns of the vehicles
table:
Second, use the ALTER TABLE MODIFY
statement to modify multiple columns:
Code language: SQL (Structured Query Language) (sql)
ALTER TABLE vehicles MODIFY year SMALLINT NOT NULL, MODIFY color VARCHAR(20) NULL AFTER make;
In this example:
- First, modify the data type of the
year
column fromINT
toSMALLINT
- Second, modify the
color
column by setting themaximum
length to20
, removing theNOT NULL
constraint, and changing its position to appear after themake
column.
Third, show the new column list of the vehicles
table to verify the modifications:
MySQL ALTER TABLE
– Rename a column in a table
To rename a column, you use the following statement:
Code language: SQL (Structured Query Language) (sql)
ALTER TABLE table_name CHANGE COLUMN original_name new_name column_definition [FIRST | AFTER column_name];
In this syntax:
- First, specify the name of the table to which the column belongs.
- Second, specify the column name and the new name followed by column definition after the
CHANGE COLUMN
keywords. - Third, use the
FIRST
orAFTER column_name
option to determine the new position of the column.
The following example uses the ALTER TABLE CHANGE COLUMN
statement to rename the column note
to vehicleCondition
:
Code language: SQL (Structured Query Language) (sql)
ALTER TABLE vehicles CHANGE COLUMN note vehicleCondition VARCHAR(100) NOT NULL;
Let’s review the column list of the vehicles
table:
Code language: SQL (Structured Query Language) (sql)
DESCRIBE vehicles;
MySQL ALTER TABLE
– Drop a column
To drop a column in a table, you use the ALTER TABLE DROP COLUMN
statement:
Code language: SQL (Structured Query Language) (sql)
ALTER TABLE table_name DROP COLUMN column_name;
In this syntax:
- First, specify the name of the table that you want to drop a column after the
ALTER TABLE
keywords. - Second, specify the name of the column that you want to drop after the
DROP COLUMN
keywords.
This example shows how to remove the vehicleCondition
column from the vehicles
table:
Code language: SQL (Structured Query Language) (sql)
ALTER TABLE vehicles DROP COLUMN vehicleCondition;
To rename a table, you use the ALTER TABLE RENAME TO
statement:
Code language: SQL (Structured Query Language) (sql)
ALTER TABLE table_name RENAME TO new_table_name;
In this syntax:
- First, specify the name of the table that you want to rename after the
ALTER TABLE
keywords. - Second, specify the new name for the table after the
RENAME TO
keywords.
This example renames the vehicles
table to cars
:
Code language: SQL (Structured Query Language) (sql)
ALTER TABLE vehicles RENAME TO cars;
In this tutorial, you have learned how to use the MySQL ALTER TABLE
statement to add a column, modify a column, rename a column, drop a column and rename a table.
Was this tutorial helpful?
В этом учебном пособии вы узнаете, как использовать MySQL оператор ALTER TABLE для добавления столбца, изменения столбца, удаления столбца, переименования столбца или переименования таблицы (с синтаксисом и примерами).
Описание
MySQL оператор ALTER TABLE используется для добавления, изменения или удаления столбцов в таблице. Оператор MySQL ALTER TABLE также используется для переименования таблицы.
Добавить столбец в таблицу
Синтаксис
Синтаксис добавления столбца в таблицу MySQL (с использованием оператора ALTER TABLE):
ALTER TABLE table_name
ADD new_column_name column_definition
[ FIRST | AFTER column_name ];
table_name — имя таблицы для изменения.
new_column_name — имя нового столбца для добавления в таблицу.
column_definition — тип данных и определение столбца (NULL или NOT NULL и т. д.).
FIRST | AFTER column_name — необязательный. Он сообщает MySQL, где в таблице создается столбец. Если этот параметр не указан, то новый столбец будет добавлен в конец таблицы.
Пример
Рассмотрим пример, который показывает, как добавить столбец в таблицу MySQL, используя оператор ALTER TABLE.
Например:
ALTER TABLE contacts ADD last_name varchar(40) NOT NULL AFTER contact_id; |
Этот MySQL пример ALTER TABLE добавит столбец с именем last_name в таблицу contacts. Он будет создан как столбец NOT NULL и появится в таблице после поля contact_id.
Добавить несколько столбцов в таблицу
Синтаксис
Синтаксис добавления нескольких столбцов в таблицу MySQL (с использованием оператора ALTER TABLE):
ALTER TABLE table_name
ADD new_column_name column_definition
[ FIRST | AFTER column_name ],
ADD new_column_name column_definition
[ FIRST | AFTER column_name ],
…
;
table_name — имя таблицы для изменения.
new_column_name — имя нового столбца для добавления в таблицу.
column_definition — тип данных и определение столбца (NULL или NOT NULL и т. д.).
FIRST | AFTER column_name — необязательный. Он сообщает MySQL, где в таблице создается столбец. Если этот параметр не указан, новый столбец будет добавлен в конец таблицы.
Пример
Рассмотрим пример, который показывает, как добавить несколько столбцов в таблицу MySQL, используя оператор ALTER TABLE.
Например:
ALTER TABLE contacts ADD last_name varchar(40) NOT NULL AFTER contact_id, ADD first_name varchar(35) NULL AFTER last_name; |
Этот пример ALTER TABLE добавит в таблицу contacts два столбца — last_name и first_name.
Поле last_name будет создано как столбец varchar (40) NOT NULL и появится в таблице contacts после столбца contact_id. Столбец first_name будет создан как столбец NULL varchar (35) и появится в таблице после столбца last_name.
Изменить столбец в таблице
Синтаксис
Синтаксис для изменения столбца в таблице MySQL (с использованием оператора ALTER TABLE):
ALTER TABLE table_name
MODIFY column_name column_definition
[ FIRST | AFTER column_name ];
table_name — имя таблицы для изменения.
column_name — имя столбца для изменения в таблице.
column_definition — измененный тип данных и определение столбца (NULL или NOT NULL и т. д.).
FIRST | AFTER column_name — необязательный. Он сообщает MySQL, где в таблице помещается столбец, если вы хотите изменить его позицию.
Пример
Рассмотрим пример, который показывает, как изменить столбец в таблице MySQL с помощью оператора ALTER TABLE.
Например:
ALTER TABLE contacts MODIFY last_name varchar(50) NULL; |
Этот пример ALTER TABLE изменит столбец с именем last_name как тип данных varchar (50) и установит для столбца значения NULL.
Изменить несколько столбцов в таблице
Синтаксис
Синтаксис для изменения нескольких столбцов в таблице MySQL (с использованием оператора ALTER TABLE):
ALTER TABLE table_name
MODIFY column_name column_definition
[ FIRST | AFTER column_name ],
MODIFY column_name column_definition
[ FIRST | AFTER column_name ],
…
;
table_name — имя таблицы для изменения.
column_name — имя столбца для изменения в таблице.
column_definition — измененный тип данных и определение столбца (NULL или NOT NULL и т. д.).
FIRST | AFTER column_name — необязательный. Он сообщает MySQL, где в таблице помещается столбец, если вы хотите изменить его позицию.
Пример
Рассмотрим пример, который показывает, как изменить несколько столбцов в таблице MySQL, используя оператор ALTER TABLE.
ALTER TABLE contacts MODIFY last_name varchar(55) NULL AFTER contact_type, MODIFY first_name varchar(30) NOT NULL; |
Этот пример ALTER TABLE будет изменять в таблице contacts два столбца — last_name и first_name.
Поле last_name будет изменено на столбец NULL varchar (55) и появится в таблице после столбца contact_type. Столбец first_name будет изменен на столбец varchar (30) NOT NULL (и не изменит позицию в определении таблицы contacts, так как не указано FIRST | AFTER).
Удаление столбца из таблицы
Синтаксис
Синтаксис для удаления столбца из таблицы в MySQL (с использованием оператора ALTER TABLE):
Например:
ALTER TABLE table_name
DROP COLUMN column_name;
table_name — имя таблицы для изменения.
column_name — имя столбца для удаления из таблицы.
Пример
Рассмотрим пример, который показывает, как удалить столбец из таблицы в MySQL с помощью оператора ALTER TABLE.
Например:
ALTER TABLE contacts DROP COLUMN contact_type; |
Этот пример ALTER TABLE удаляет столбец с именем contact_type из таблицы contacts.
Переименование столбца в таблице
Синтаксис
Синтаксис для переименования столбца в таблице MySQL (с использованием оператора ALTER TABLE):
ALTER TABLE table_name
CHANGE COLUMN old_name new_name
column_definition
[ FIRST | AFTER column_name ];
table_name — имя таблицы для изменения.
old_name — столбец для переименования.
new_name — новое имя столбца.
column_definition — тип данных и определение столбца (NULL или NOT NULL и т. д.). Вы должны указать определение столбца при переименовании столбца, даже если оно не изменится.
FIRST | AFTER column_name — необязательный. Он сообщает MySQL, где в таблице помещается столбец, если вы хотите изменить его позицию.
Пример
Рассмотрим пример, который показывает, как переименовать столбец в таблице MySQL с помощью оператора ALTER TABLE.
Например:
ALTER TABLE contacts CHANGE COLUMN contact_type ctype varchar(20) NOT NULL; |
Этот MySQL пример ALTER TABLE переименует столбец с именем contact_type в ctype. Столбец будет определен как столбец varchar (20) NOT NULL.
Переименовать таблицу
Синтаксис
Синтаксис для переименования таблицы в MySQL:
ALTER TABLE table_name
RENAME TO new_table_name;
table_name — таблица для переименования.
new_table_name — новое имя таблицы для использования.
Пример
Рассмотрим пример, который показывает, как переименовать таблицу в MySQL с помощью оператора ALTER TABLE.
Например:
ALTER TABLE contacts RENAME TO people; |
Этот пример ALTER TABLE переименует таблицу contacts в people.
Узнайте как использовать оператор ALTER TABLE в распространенных БД:
- ALTER TABLE Oracle PL/SQL
- ALTER TABLE SQL Server
- ALTER TABLE PostgreSQL
- ALTER TABLE MariaDB
- ALTER TABLE SQLite
SQL-запрос для изменения типа столбца в базе данных SQL Server
Мы можем использовать оператор ALTER TABLE ALTER COLUMN для изменения типа столбца в таблице. Использует следующий синтаксис:
ALTER TABLE [tbl_name] ALTER COLUMN [col_name] [DATA_TYPE]
Здесь
- tbl_name: задает имя таблицы.
- col_name: задает имя столбца, тип которого мы хотим изменить. col_name должно быть указано после ключевых слов ALTER COLUMN.
- DATA_TYPE: задает новый тип данных и длину столбца.
В целях демонстрации я создал таблицу с именем tblStudent.
CREATE TABLE [dbo].[tblstudent]
(
[id] [INT] IDENTITY(1, 1) NOT NULL,
[student_code] [VARCHAR](20) NOT NULL,
[student_firstname] [VARCHAR](250) NOT NULL,
[student_lastname] [VARCHAR](10) NOT NULL,
[address] [VARCHAR](max) NULL,
[city_code] [VARCHAR](20) NOT NULL,
[school_code] [VARCHAR](20) NULL,
[admissiondate] [DATETIME] NULL,
CONSTRAINT [PK_ID] PRIMARY KEY CLUSTERED ( [id] ASC )
)
Предположим, что вы хотите изменить тип данных [address] с varchar(max) на nvarchar(1500). Выполните следующий запрос для изменения типа столбца.
Alter table tblstudent alter column address nvarchar(1500)
Проверим изменения с помощью следующего скрипта.
use StudentDB
go
select TABLE_SCHEMA,TABLE_NAME,COLUMN_NAME,DATA_TYPE, CHARACTER_MAXIMUM_LENGTH from INFORMATION_SCHEMA.COLUMNS
where table_name='tblStudent'
Видно, что тип данных столбца изменился.
Важные замечания:
- При уменьшении размера столбца SQL Server проверит данные в таблице и, если данные превышают новую длину, вернет предупреждение и прервет выполнение оператора.
- При изменении типа данных nvarchar на varchar, если столбец содержит строку Юникод, то SQL Server возвращает ошибку и прерывает оператор.
- В отличие от MySQL изменение типа данных нескольких столбцов не допускается.
- Вы не можете добавить
а. ограничение NOT NULL, если столбец содержит NULL-значения;
б. ограничение UNIQUE, если в столбце имеются дубликаты.
Запрос SQL для изменения типа столбца в MySQL
Для изменения типа данных столбца мы можем использовать оператор ALTER TABLE MODIFY COLUMN. Синтаксис изменения типа данных столбца имеет следующий вид:
ALTER TABLE [tbl_name] MODIFY COLUMN [col_name_1] [DATA_TYPE],
MODIFY [col_name_2] [data_type],
MODIFY [col_name_3] [data_type]
Здесь
- Tbl_name: задает имя таблицы, содержащая столбец, который мы хотим изменить.
- Col_name: задает имя столбца, тип которого мы хотим изменить. Col_name должно быть указано после ключевых слов MODIFY COLUMN. Мы можем изменить тип данных нескольких столбцов. При изменении типа данных нескольких столбцов, столбцы разделяются запятой (,).
- Datatype: задает новый тип данных и длину столбца. Тип данных должен указываться после имени столбца.
В целях демонстрации я создал таблицу с именем tblactor в базе данных DemoDatabase. Вот код, который создает таблицу.
create table tblactor
(
actor_id int,
first_name varchar(500),
first_name varchar(500),
address varchar(500),
CityID int,
lastupdate datetime
)
Рассмотрим несколько примеров.
Пример 1: Запрос для изменения типа данных одного столбца
Мы хотим изменить тип столбца address с varchar(500) на тип данных TEXT. Выполните следующий запрос для изменения типа данных.
mysql> ALTER TABLE tblActor MODIFY address TEXT
Для проверки изменений выполните следующий запрос:
mysql> describe tblactor
Как можно увидеть, тип данных столбца address был изменен на TEXT.
Пример 2: SQL-запрос для изменения типа данных нескольких столбцов
Мы можем изменить тип данных нескольких столбцов в таблице. В нашем примере мы хотим изменить тип столбцов first_name и last_name. Новым типом данных столбцов становится TINYTEXT.
mysql> ALTER TABLE tblActor MODIFY first_name TINYTEXT, modify last_name TINYTEXT;
Выполните следующий запрос, чтобы проверить изменения:
mysql> describe tblActor
Как видно, тип данных столбцов first_name и last_name изменился на TINYTEXT.
Пример 3: Переименование столбца в MySQL
Чтобы переименовать столбцы, мы должны использовать оператор ALTER TABLE CHANGE COLUMN. Предположим, что вы хотите переименовать столбец CityID в CityCode; вы должны выполнить следующий запрос.
mysql> ALTER TABLE tblActor CHANGE COLUMN CityID CityCode int
Выполните команду describe, чтобы увидеть изменения структуры таблицы.
Видно, что имя столбца изменилось.
Запрос SQL для изменения типа столбца в базе данных PostgreSQL
Мы можем использовать оператор ALTER TABLE ALTER COLUMN для изменения типа данных столбца. Синтаксис изменения типа данных столбца:
ALTER TABLE [tbl_name] ALTER COLUMN [col_name_1] TYPE [data_type],
ALTER COLUMN [col_name_2] TYPE [data_type],
ALTER COLUMN [col_name_3] TYPE [data_type]
Здесь
- Tbl_name: задает имя таблицы, содержащая столбец, который вы хотите изменить.
- Col_name: задает имя столбца, тип которого мы хотим изменить. Col_name должно быть указано после ключевых слов ALTER COLUMN. Мы можем изменить тип данных нескольких столбцов.
- Data_type: задает новый тип данных и длину столбца. Тип данных должен быть указан после ключевого слова TYPE.
В целях демонстрации я создал таблицу с именем tblmovies в базе данных DemoDatabase. Вот код для создания этой таблицы:
create table tblmovies
(
movie_id int,
Movie_Title varchar(500),
Movie_director TEXT,
Movie_Producer TEXT,
duraion int,
Certificate varchar(5),
rent numeric(10,2)
)
Теперь рассмотрим несколько примеров.
Пример 1: Запрос SQL для изменения типа данных одного столбца
Мы хотим изменить тип столбца movie_id с типа данных int4 на int8. Для изменения типа данных выполните следующий запрос.
ALTER TABLE tblmovies ALTER COLUMN movie_id TYPE BIGINT
Для проверки изменений выполните следующий запрос:
SELECT
table_catalog,
table_name,
column_name,
udt_name,
character_maximum_length
FROM
information_schema.columns
WHERE
table_name = 'tblmovies';
Как видно, тип данных столбца movie_id стал int8.
Пример 2: Запрос SQL для изменения типа данных нескольких столбцов
Мы можем изменить тип данных сразу нескольких столбцов таблицы. В нашем примере мы хотим изменить тип столбцов movie_title и movie_producer. Новым типом данных для столбца movie_title становится TEXT, а для movie_producer — varchar(2000).
ALTER TABLE tblmovies ALTER COLUMN movie_title TYPE text, ALTER COLUMN movie_producer TYPE varchar(2000);
Выполните следующий запрос для проверки изменений:
SELECT
table_catalog,
table_name,
column_name,
udt_name,
character_maximum_length
FROM
information_schema.columns
WHERE
table_name = 'tblmovies';
Как видно, типом данных столбца movie_title является TEXT, а movie_producer — varchar(2000).
This MySQL tutorial explains how to use the MySQL ALTER TABLE statement to add a column, modify a column, drop a column, rename a column or rename a table (with syntax and examples).
Description
The MySQL ALTER TABLE statement is used to add, modify, or drop/delete columns in a table. The MySQL ALTER TABLE statement is also used to rename a table.
Add column in table
Syntax
The syntax to add a column in a table in MySQL (using the ALTER TABLE statement) is:
ALTER TABLE table_name ADD new_column_name column_definition [ FIRST | AFTER column_name ];
- table_name
- The name of the table to modify.
- new_column_name
- The name of the new column to add to the table.
- column_definition
- The datatype and definition of the column (NULL or NOT NULL, etc).
- FIRST | AFTER column_name
- Optional. It tells MySQL where in the table to create the column. If this parameter is not specified, the new column will be added to the end of the table.
Example
Let’s look at an example that shows how to add a column in a MySQL table using the ALTER TABLE statement.
For example:
ALTER TABLE contacts ADD last_name varchar(40) NOT NULL AFTER contact_id;
This MySQL ALTER TABLE example will add a column called last_name to the contacts table. It will be created as a NOT NULL column and will appear after the contact_id field in the table.
Add multiple columns in table
Syntax
The syntax to add multiple columns in a table in MySQL (using the ALTER TABLE statement) is:
ALTER TABLE table_name ADD new_column_name column_definition [ FIRST | AFTER column_name ], ADD new_column_name column_definition [ FIRST | AFTER column_name ], ... ;
- table_name
- The name of the table to modify.
- new_column_name
- The name of the new column to add to the table.
- column_definition
- The datatype and definition of the column (NULL or NOT NULL, etc).
- FIRST | AFTER column_name
- Optional. It tells MySQL where in the table to create the column. If this parameter is not specified, the new column will be added to the end of the table.
Example
Let’s look at an example that shows how to add multiple columns in a MySQL table using the ALTER TABLE statement.
For example:
ALTER TABLE contacts ADD last_name varchar(40) NOT NULL AFTER contact_id, ADD first_name varchar(35) NULL AFTER last_name;
This ALTER TABLE example will add two columns to the contacts table — last_name and first_name.
The last_name field will be created as a varchar(40) NOT NULL column and will appear after the contact_id column in the table. The first_name column will be created as a varchar(35) NULL column and will appear after the last_name column in the table.
Modify column in table
Syntax
The syntax to modify a column in a table in MySQL (using the ALTER TABLE statement) is:
ALTER TABLE table_name MODIFY column_name column_definition [ FIRST | AFTER column_name ];
- table_name
- The name of the table to modify.
- column_name
- The name of the column to modify in the table.
- column_definition
- The modified datatype and definition of the column (NULL or NOT NULL, etc).
- FIRST | AFTER column_name
- Optional. It tells MySQL where in the table to position the column, if you wish to change its position.
Example
Let’s look at an example that shows how to modify a column in a MySQL table using the ALTER TABLE statement.
For example:
ALTER TABLE contacts MODIFY last_name varchar(50) NULL;
This ALTER TABLE example will modify the column called last_name to be a data type of varchar(50) and force the column to allow NULL values.
Modify Multiple columns in table
Syntax
The syntax to modify multiple columns in a table in MySQL (using the ALTER TABLE statement) is:
ALTER TABLE table_name MODIFY column_name column_definition [ FIRST | AFTER column_name ], MODIFY column_name column_definition [ FIRST | AFTER column_name ], ... ;
- table_name
- The name of the table to modify.
- column_name
- The name of the column to modify in the table.
- column_definition
- The modified datatype and definition of the column (NULL or NOT NULL, etc).
- FIRST | AFTER column_name
- Optional. It tells MySQL where in the table to position the column, if you wish to change its position.
Example
Let’s look at an example that shows how to modify multiple columns in a MySQL table using the ALTER TABLE statement.
For example:
ALTER TABLE contacts MODIFY last_name varchar(55) NULL AFTER contact_type, MODIFY first_name varchar(30) NOT NULL;
This ALTER TABLE example will modify two columns to the contacts table — last_name and first_name.
The last_name field will be changed to a varchar(55) NULL column and will appear after the contact_type column in the table. The first_name column will be modified to a varchar(30) NOT NULL column (and will not change position in the contacts table definition, as there is no FIRST | AFTER specified).
Drop column in table
Syntax
The syntax to drop a column in a table in MySQL (using the ALTER TABLE statement) is:
ALTER TABLE table_name DROP COLUMN column_name;
- table_name
- The name of the table to modify.
- column_name
- The name of the column to delete from the table.
Example
Let’s look at an example that shows how to drop a column in a MySQL table using the ALTER TABLE statement.
For example:
ALTER TABLE contacts DROP COLUMN contact_type;
This ALTER TABLE example will drop the column called contact_type from the table called contacts.
Rename column in table
Syntax
The syntax to rename a column in a table in MySQL (using the ALTER TABLE statement) is:
ALTER TABLE table_name CHANGE COLUMN old_name new_name column_definition [ FIRST | AFTER column_name ]
- table_name
- The name of the table to modify.
- old_name
- The column to rename.
- new_name
- The new name for the column.
- column_definition
- The datatype and definition of the column (NULL or NOT NULL, etc). You must specify the column definition when renaming the column, even if it does not change.
- FIRST | AFTER column_name
- Optional. It tells MySQL where in the table to position the column, if you wish to change its position.
Example
Let’s look at an example that shows how to rename a column in a MySQL table using the ALTER TABLE statement.
For example:
ALTER TABLE contacts CHANGE COLUMN contact_type ctype varchar(20) NOT NULL;
This MySQL ALTER TABLE example will rename the column called contact_type to ctype. The column will be defined as a varchar(20) NOT NULL column.
Rename table
Syntax
The syntax to rename a table in MySQL is:
ALTER TABLE table_name RENAME TO new_table_name;
- table_name
- The table to rename.
- new_table_name
- The new table name to use.
Example
Let’s look at an example that shows how to rename a table in MySQL using the ALTER TABLE statement.
For example:
ALTER TABLE contacts RENAME TO people;
This ALTER TABLE example will rename the contacts table to people.