Monday 9 December 2019

How to Change a Column Name in MySQL

If you already created your MySQL database, and you decide after the fact that one of the columns is named incorrectly, you don't need to remove it and add a replacement; you can simply rename it.

Renaming a Database Column

You rename a column in MySQL using the ALTER TABLE and CHANGE commands together to change an existing column. For example, say the column is currently named Soda, but you decide that Beverage is a more appropriate title. The column is located on the table entitled Menu. Here is an example of how to change it:
ALTER TABLE menu CHANGE soda beverage varchar(10) ;
In a generic form, where you substitute your terms, this is:
ALTER TABLE tablename CHANGE oldname newname varchar(10) ;

About VARCHAR

The VARCHAR(10) in the examples can change to be appropriate for your column. VARCHAR is a character string of variable length. The maximum length—in this example it is 10—indicates the maximum number of characters you want to store in the column. VARCHAR(25) could store up to 25 characters.

Other Uses for ALTER TABLE

The ALTER TABLE command can also be used to add a new column to a table or to remove an entire column and all its data from a table. For example, to add a column use:
ALTER TABLE table_name
ADD column_name datatype
To delete a column, use:

ALTER TABLE table_name
DROP COLUMN column_name 

0 comments:

Post a Comment