How do I rename a column in a database table using SQL?

Viewed 589960

If I wish to simply rename a column (not change its type or constraints, just its name) in an SQL database using SQL, how do I do that? Or is it not possible?

This is for any database claiming to support SQL, I'm simply looking for an SQL-specific query that will work regardless of actual database implementation.

13 Answers

Specifically for SQL Server, use sp_rename

USE AdventureWorks;
GO
EXEC sp_rename 'Sales.SalesTerritory.TerritoryID', 'TerrID', 'COLUMN';
GO

On PostgreSQL (and many other RDBMS), you can do it with regular ALTER TABLE statement:

=> SELECT * FROM Test1;
 id | foo | bar 
----+-----+-----
  2 |   1 |   2

=> ALTER TABLE Test1 RENAME COLUMN foo TO baz;
ALTER TABLE

=> SELECT * FROM Test1;
 id | baz | bar 
----+-----+-----
  2 |   1 |   2

In sql server you can use

exec sp_rename '<TableName.OldColumnName>','<NewColumnName>','COLUMN'

or

sp_rename '<TableName.OldColumnName>','<NewColumnName>','COLUMN'

In Informix, you can use:

RENAME COLUMN TableName.OldName TO NewName;

This was implemented before the SQL standard addressed the issue - if it is addressed in the SQL standard. My copy of the SQL 9075:2003 standard does not show it as being standard (amongst other things, RENAME is not one of the keywords). I don't know whether it is actually in SQL 9075:2008.

ALTER TABLE is standard SQL. But it's not completely implemented in many database systems.

The standard would be ALTER TABLE, but that's not necessarily supported by every DBMS you're likely to encounter, so if you're looking for an all-encompassing syntax, you may be out of luck.

To rename you have to change the column

e.g

Suppose

*registration is Table Name

newRefereeName is a column name That I want to change to refereeName SO my SQL Query will be*

ALTER TABLE 'registration' CHANGE 'newRefereeName' 'refereeName' VARCHAR(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL;

exec sp_rename 'Tablename.OldColumnName', 'NewColumnName', 'Column';

Related