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

前端 未结 11 1673
时光说笑
时光说笑 2020-12-12 18:25

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

相关标签:
11条回答
  • 2020-12-12 19:18

    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
    
    0 讨论(0)
  • 2020-12-12 19:18

    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.

    0 讨论(0)
  • 2020-12-12 19:19

    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.

    0 讨论(0)
  • 2020-12-12 19:24

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

    0 讨论(0)
  • 2020-12-12 19:25

    In MySQL, the syntax is ALTER TABLE ... CHANGE:

    ALTER TABLE <table_name> CHANGE <column_name> <new_column_name> <data_type> ...
    

    Note that you can't just rename and leave the type and constraints as is; you must retype the data type and constraints after the new name of the column.

    0 讨论(0)
提交回复
热议问题