How to rename the column name SQL Table

Asked

Viewed 46,833 times

9

I want to rename the column name via SQL. I am trying as follows:

ALTER TABLE nomes_clientes 
RENAME COLUMN primeiro_nome TO nome, 
RENAME COLUMN segundo_nome TO sobrenome;

But that way it’s not working.

  • In which database? Each one is different

  • The database is Mysql

3 answers

9


You need to reset every column like this:

ALTER TABLE nomes_clientes 
    CHANGE primeiro_nome nome VARCHAR(255) NOT NULL;
    CHANGE segundo_nome sobrenome VARCHAR(255) NOT NULL;

I put in the Github for future reference.

8

Just as @Maniero commented will depend on the database you are using, but for these three (Oracle, Postgresql and Mysql) it is as follows:

Oracle

ALTER TABLE T_CLASSE_SOCIAL
RENAME COLUMN TESTE TO  TESTE_NOVO;

Postgresql

ALTER TABLE distribuidores RENAME COLUMN endereco TO cidade;

Mysql

ALTER TABLE tabela_exemplo CHANGE id_exemplo novo_id_exemplo integer(5) unsigned;

References: Mysql | Postgresql | Oracle

  • 2

    In this case of Mysql, this code would not be changing the table name instead of the column name?

  • @Christian, my mistake, I set the answer to the correct commands

  • It worked! Thank you all!

0

Complementing the answer:

Sqlserver

sp_RENAME '[Tabela.NomeColuna]', '[NovoNomeColuna]' , 'COLUMN'

In this database, a ready-made sp is used. Remembering that it is necessary to use the exec to run the precedent. The third parameter 'COLUMN' is required for the case in question, which is to rename a column. Example:

exec sp_RENAME 
          'Pessoa.codPessoa',
          'codPessoaAlterada',
          'COLUMN'

For more details of SP use:

References: Sqlserver

Browser other questions tagged

You are not signed in. Login or sign up in order to post.