Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 284
MetroidFan2002 Avatar asked Oct 03 '22 11:10

MetroidFan2002


People also ask

How do I RENAME a column in a table in SQL?

ALTER TABLE table_name RENAME TO new_table_name; Columns can be also be given new name with the use of ALTER TABLE. QUERY: Change the name of column NAME to FIRST_NAME in table Student.


2 Answers

Specifically for SQL Server, use sp_rename

USE AdventureWorks;
GO
EXEC sp_rename 'Sales.SalesTerritory.TerritoryID', 'TerrID', 'COLUMN';
GO
like image 136
Galwegian Avatar answered Oct 11 '22 00:10

Galwegian


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
like image 107
bortzmeyer Avatar answered Oct 11 '22 00:10

bortzmeyer