views:

1467

answers:

5

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.

+5  A: 

Use sp_rename

USE AdventureWorks;
GO
EXEC sp_rename 'Sales.SalesTerritory.TerritoryID', 'TerrID', 'COLUMN';
GO
Galwegian
It seems Microsoft-specific and nothing in the original query indicated a Microsoft DBMS.
bortzmeyer
Yes, the answer I was looking for is "standard" SQL, and not dependent on any particular implementation. However, it is a good answer for anyone using Microsoft's system.
MetroidFan2002
+5  A: 

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

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

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

essais=> SELECT * FROM Test1;
 id | baz | bar 
----+-----+-----
  2 |   1 |   2
bortzmeyer
Thanks, that's what I needed.
MetroidFan2002
+1  A: 

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

Paul Tomblin
I accepted bortz' answer over yours because he gave a detailed explanation. Nevertheless, I upvoted you.
MetroidFan2002
@MetroidFan2002 - I only added my answer to acknowledge that "ALTER TABLE" isn't just PostgreSQL, it's pretty common.
Paul Tomblin
+2  A: 

In Informix, you can use:

RENAME COLUMN TableName.OldName AS 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.

Jonathan Leffler
No RENAME in SQL 2008 Draft too.
Nicolas Buduroi
+1  A: 

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.

Rob