This article provides a quick example of renaming a table in SQL.
Most of the major RDBMSs allow you to rename a column with the ALTER TABLE
statement. SQL Server is an exception.
Example (Most RDBMSs)
Most of the major RDBMSs allow you to rename a column as follows.
Syntax:
ALTER TABLE table_name
RENAME COLUMN old_column_name TO new_column_name;
Example:
ALTER TABLE Products
RENAME COLUMN ProdDesc TO ProductDescription;
Here, we renamed a column in the Products
table from ProdDesc
to ProductDescription
.
That should work in RDBMSs including PostgreSQL, Oracle, SQLite, MySQL (starting with 8.0), and MariaDB (starting with 10.5.2+).
Earlier Versions of MySQL & MariaDB
MySQL and MariaDB didn’t always support the RENAME COLUMN
syntax.
In MySQL prior to version 8.0, and MariaDB prior to 10.5.2+, you’ll need to use the CHANGE COLUMN
syntax instead.
Syntax:
ALTER TABLE table_name
CHANGE COLUMN old_column_name new_column_name datatype;
Example:
ALTER TABLE Products
CHANGE COLUMN ProdDesc ProductDescription varchar(500);
Note that this syntax requires that you respecify the column definition even if you’re only renaming it.
This syntax is still supported in later versions of MySQL and MariaDB, although they now also have the previous RENAME COLUMN
syntax that makes it easier.
SQL Server
In SQL Server, you’ll need to use the sp_rename
stored procedure to rename a column.
Syntax:
sp_rename 'schema_name.table_name.old_column_name', 'new_column_name', 'COLUMN';
You also have the option of providing the parameter names:
sp_rename
[ @objname = ] 'object_name' ,
[ @newname = ] 'new_name'
[ , [ @objtype = ] 'object_type' ]
Example:
EXEC sp_rename 'dbo.Products.ProdDesc', 'ProductDescription', 'COLUMN';
Or:
EXEC sp_rename
@objname = 'dbo.Products.ProdDesc',
@newname = 'ProductDescription',
@objtype = 'COLUMN';