# ALTER TABLE
# Changing storage engine; rebuild table; change file_per_table
For example, if t1 is currently not an InnoDB table, this statement changes its storage engine to InnoDB:
If the table is already InnoDB, this will rebuild the table and its indexes and have an effect similar to OPTIMIZE TABLE . You may gain some disk space improvement.
If the value of innodb_file_per_table is currently different than the value in effect when t1 was built, this will convert to (or from) file_per_table.
# ALTER COLUMN OF TABLE
# Change auto-increment value
Changing an auto-increment value is useful when you don’t want a gap in an AUTO_INCREMENT column after a massive deletion.
For example, you got a lot of unwanted (advertisement) rows posted in your table, you deleted them, and you want to fix the gap in auto-increment values. Assume the MAX value of AUTO_INCREMENT column is 100 now. You can use the following to fix the auto-increment value.
# Renaming a MySQL table
Renaming a table can be done in a single command:
The following syntax does exactly the same:
If renaming a temporary table, the ALTER TABLE version of the syntax must be used.
Steps:
- Replace <old name> and <new name> in the line above with the relevant values. Note: If the table is being moved to a different database, the dbname . tablename syntax can be used for <old name> and/or <new name> .
- Execute it on the relevant database in the MySQL command line or a client such as MySQL Workbench. Note: The user must have ALTER and DROP privileges on the old table and CREATE and INSERT on the new one.
# ALTER table add INDEX
To improve performance one might want to add indexes to columns
altering to add composite (multiple column) indexes
# Changing the type of a primary key column
An attempt to modify the type of this column without first dropping the primary key would result in an error.
# Change column definition
The change the definition of a db column, the query below can be used for example, if we have this db schema
To change the type of age column from char to int , we use the query below:
General format is:
# Renaming a MySQL database
There is no single command to rename a MySQL database but a simple workaround can be used to achieve this by backing up and restoring:
Steps:
- Copy the lines above into a text editor.
- Replace all references to <old name> , <new name> and <password> (+ optionally root to use a different user) with the relevant values.
- Execute one by one on the command line (assuming the MySQL "bin" folder is in the path and entering "y" when prompted).
Alternative Steps:
Rename (move) each table from one db to the other. Do this for each table:
You can create those statements by doing something like
Warning. Do not attempt to do any sort of table or database by simply moving files around on the filesystem. This worked fine in the old days of just MyISAM, but in the new days of InnoDB and tablespaces, it won’t work. Especially when the "Data Dictionary" is moved from the filesystem into system InnoDB tables, probably in the next major release. Moving (as opposed to just DROPping ) a PARTITION of an InnoDB table requires using "transportable tablespaces". In the near future, there won’t even be a file to reach for.
# Swapping the names of two MySQL databases
The following commands can be used to swap the names of two MySQL databases ( <db1> and <db2> ):
SQL Rename Column Syntax
Sometimes we want to change the name of a column. To do this in SQL, we specify that we want to change the structure of the table using the ALTER TABLE command, followed by a command that tells the relational database that we want to rename the column. The exact syntax for each database is as follows:
In MySQL, the SQL syntax for ALTER TABLE Rename Column is,
In Oracle, the syntax is,
Let’s look at the example. Assuming our starting point is the Customer table created in the CREATE TABLE section:
Table Customer
| Column Name | Data Type |
| First_Name | char(50) |
| Last_Name | char(50) |
| Address | char(50) |
| City | char(50) |
| Country | char(25) |
| Birth_Date | datetime |
To rename «Address» to «Addr», we key in,
SQL Server:
It is not possible to rename a column using the ALTER TABLE statement in SQL Server. Use sp_rename instead.
The resulting table structure is:
Table Customer
| Column Name | Data Type |
| First_Name | char(50) |
| Last_Name | char(50) |
| Addr | char(50) |
| City | char(50) |
| Country | char(25) |
| Birth_Date | datetime |
To rename a column in SparkSQL or Hive SQL, we would use the ALTER TABLE Change Column command.
How To Rename Column Name In SQL?
![]()
It may often happen that, we see a requirement to change the name of the column in the database to serve their purpose. With the help of SQL or Structured Query Language, the Database Administrators store, update, manipulate, and retrieve data in relational databases. So, in this article let us understand how to rename a column name in SQL.
The following topics will be covered in this article:
- What is SQL?
- What is RENAME command in SQL?
- Rename column name in MySQL, MariaDB, Oracle, and PostgreSQL
- Rename column name in MS SQL Server
- Rename table name MySQL, MariaDB, Oracle
So let us get started then,
What is SQL?
SQL or most commonly known as SEQUEL is a Structured Query Language used for managing and accessing the databases. It is based on the English language and is designed in a way to easily retrieve, manipulate, and access the data. If you wish to know more about the basics of SQL in-depth, you can refer to the article on SQL Basics. In SQL, there are various statements/ commands used to manipulate data. One such manipulation, which is quite popular in databases is renaming the column name in SQL.
So, let us understand how to use the RENAME command in SQL.
What is RENAME command in SQL?
This command is used to change the name of a column to a new column name. It is also used to change the table to a new table name. Let us understand how to use this command in different databases. But, before that, let us consider the following table to understand all the examples:
How to Rename Column name in SQL?
Rename column name in MySQL, MariaDB, Oracle, and PostgreSQL
To rename a column name in MySQL, MariaDB, Oracle, and PostgreSQL, you can follow the below syntax:
Syntax
Example:
Write a query to rename the column name “BID” to “BooksID”.
On executing the above query, you will see the following output:
You can also use the CHANGE keyword to rename a column name as follows:
Syntax
Example:
Write a query to rename the column name “BID” to “BooksID”.
On executing this query, you will see the output the same as the above output.
Rename column name in MS SQL Server
The process of renaming column name is MS SQL Server is different when compared to the other databases. In MS SQL Server, you have to use the stored procedure called sp_rename.
Syntax
Example:
Write a query to rename the column name “BID” to “BooksID”.
The resulting output will be the same as that for the above queries. Now, that you have understood how to rename a column name in various databases, let us see how you can rename a table name.
Rename table name MySQL, MariaDB, Oracle
To rename a table name, you can use the RENAME command in SQL, in the following manner:
Syntax:
Example:
Now, if you execute the below query to see the details in the table ListOfBooks, you will see the following output:
Query:
Now with this, we come to an end of this comparison on SQL vs NoSQL. I hope you guys enjoyed this article and understood all the differences. If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to Edureka’s official site.
Do look out for other articles in this series which will explain the various other aspects of SQL.
ALTER TABLE оператор MySQL
В этом учебном пособии вы узнаете, как использовать MySQL оператор ALTER TABLE для добавления столбца, изменения столбца, удаления столбца, переименования столбца или переименования таблицы (с синтаксисом и примерами).
Описание
MySQL оператор ALTER TABLE используется для добавления, изменения или удаления столбцов в таблице. Оператор MySQL ALTER TABLE также используется для переименования таблицы.
Добавить столбец в таблицу
Синтаксис
Синтаксис добавления столбца в таблицу MySQL (с использованием оператора ALTER TABLE):
table_name — имя таблицы для изменения.
new_column_name — имя нового столбца для добавления в таблицу.
column_definition — тип данных и определение столбца (NULL или NOT NULL и т. д.).
FIRST | AFTER column_name — необязательный. Он сообщает MySQL, где в таблице создается столбец. Если этот параметр не указан, то новый столбец будет добавлен в конец таблицы.
Пример
Рассмотрим пример, который показывает, как добавить столбец в таблицу MySQL, используя оператор ALTER TABLE.
Например:
Этот MySQL пример ALTER TABLE добавит столбец с именем last_name в таблицу contacts . Он будет создан как столбец NOT NULL и появится в таблице после поля contact_id .
Добавить несколько столбцов в таблицу
Синтаксис
Синтаксис добавления нескольких столбцов в таблицу MySQL (с использованием оператора ALTER TABLE):
table_name — имя таблицы для изменения.
new_column_name — имя нового столбца для добавления в таблицу.
column_definition — тип данных и определение столбца (NULL или NOT NULL и т. д.).
FIRST | AFTER column_name — необязательный. Он сообщает MySQL, где в таблице создается столбец. Если этот параметр не указан, новый столбец будет добавлен в конец таблицы.
Пример
Рассмотрим пример, который показывает, как добавить несколько столбцов в таблицу MySQL, используя оператор ALTER TABLE.
Например:
Этот пример 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):
table_name — имя таблицы для изменения.
column_name — имя столбца для изменения в таблице.
column_definition — измененный тип данных и определение столбца (NULL или NOT NULL и т. д.).
FIRST | AFTER column_name — необязательный. Он сообщает MySQL, где в таблице помещается столбец, если вы хотите изменить его позицию.
Пример
Рассмотрим пример, который показывает, как изменить столбец в таблице MySQL с помощью оператора ALTER TABLE.
Например:
Этот пример ALTER TABLE изменит столбец с именем last_name как тип данных varchar (50) и установит для столбца значения NULL.
Изменить несколько столбцов в таблице
Синтаксис
Синтаксис для изменения нескольких столбцов в таблице MySQL (с использованием оператора ALTER TABLE):
table_name — имя таблицы для изменения.
column_name — имя столбца для изменения в таблице.
column_definition — измененный тип данных и определение столбца (NULL или NOT NULL и т. д.).
FIRST | AFTER column_name — необязательный. Он сообщает MySQL, где в таблице помещается столбец, если вы хотите изменить его позицию.
Пример
Рассмотрим пример, который показывает, как изменить несколько столбцов в таблице MySQL, используя оператор ALTER TABLE.
Этот пример 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):
Например:
table_name — имя таблицы для изменения.
column_name — имя столбца для удаления из таблицы.
Пример
Рассмотрим пример, который показывает, как удалить столбец из таблицы в MySQL с помощью оператора ALTER TABLE.
Например:
Этот пример ALTER TABLE удаляет столбец с именем contact_type из таблицы contacts .
Переименование столбца в таблице
Синтаксис
Синтаксис для переименования столбца в таблице MySQL (с использованием оператора ALTER TABLE):
table_name — имя таблицы для изменения.
old_name — столбец для переименования.
new_name — новое имя столбца.
column_definition — тип данных и определение столбца (NULL или NOT NULL и т. д.). Вы должны указать определение столбца при переименовании столбца, даже если оно не изменится.
FIRST | AFTER column_name — необязательный. Он сообщает MySQL, где в таблице помещается столбец, если вы хотите изменить его позицию.
Пример
Рассмотрим пример, который показывает, как переименовать столбец в таблице MySQL с помощью оператора ALTER TABLE.
Например: