Add to Favorites

Altering a column in a mysql database schema

Sometimes in a web project the initial requirements/blueprint will need adjustment. When you already have a working database table with lots of data in it, you can just blow the table away to change the schema. In this scenario, you have a database of contacts and you were storing the date that the contact was entered in the database in a column named "created_at". Further along the road you discover that you need the time the record was created in addition to the date, but you do not want to lose the current data. ( DISCLAIMER: always back up your data before making any change like this to the database, if you make a mistake in your query you can lose your data ).

To accomplish this, we use a simple query:
alter table contacts change created_at `created_at` datetime NOT NULL;

You can also use this method to extend the length of columns, such as varchar. If you had a varchar column named "person_name" and it the limit was 20 chars. Now you want to store more data ( perhaps 40 characters maximum ) but keep the current data intact.
The query would look like:
alter table contacts change person_name `person_name` varchar(40);

Comments

Be the first to leave a comment on this post.

Leave a comment

To leave a comment, please log in / sign up