Saturday, January 22, 2011

How to change column datatype in mysql


Mysql Alter Column Datatype is used to modify the table and change the datatype of field.
Understand with Example
The Tutorial illustrate an example from 'Mysql Alter Column  Datatype'. To understand this example we create a table 'employees' with empid as Primary Key.
Query to create table:
CREATE TABLE `employees` (               
            ->Empid int(10),  
            ->Empname varchar(60),    
             ->date date
            ->PRIMARY KEY(empid)  
           ->);
Query to insert data into Table named employees:
The Query insert into add the records or rows into the table 'employees'.
mysql>insert into employees values(01,'Girish','2008-12-22');
Query OK, 1 row affected (0.02 sec)
mysql>insert into employee1 values(02,'Komal','2008-12-23');
Query OK, 1 row affected (0.02 sec)
Query to view data of  Table named employees:
To view the detail of table 'employee1' we use select query that return the detail of records.
mysql> select * from employee;
Output:-
+-------+---------+------------+
| Empid | Empname | date       |
+-------+---------+------------+
|     1 | Girish  | 2008-12-22 |
|     2 | Komal   | 2008-12-23 |
+-------+---------+------------+
2 rows in set (0.00 sec)

Data type of Table named employees before altering column data type:
The describe employee describe the field name ,data type ,null ,key etc in table employees
+---------+-------------+------+-----+---------+----------------+
| Field   | Type        | Null | Key | Default | Extra          |
+---------+-------------+------+-----+---------+----------------+
| empid   | int(11)     | NO   | PRI | NULL    | auto_increment |
| Empname | varchar(60) | NO   |     |         |                |
| date    | date        | YES  |     | NULL    |                |
+---------+-------------+------+-----+---------+----------------+
3 rows in set (0.02 sec)
Query to alter column data type of the Table named employees:
The Alter Query redefine the table 'employee' and change the data type of column  'empid'.
mysql> alter table employees
    -> change empid empid varchar(100);
Query OK, 2 rows affected (0.13 sec)
Records: 2  Duplicates: 0  Warnings: 0
Data type of Table named employees after altering column data type:
The describe employee describe the field name ,data type ,null ,key etc in table employees.
mysql> describe employees;
+---------+--------------+------+-----+---------+-------+
| Field   | Type         | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+-------+
| empid   | varchar(100) | NO   | PRI |         |       |
| empname | varchar(130) | YES  |     | NULL    |       |
| date    | date         | YES  |     | NULL    |       |
+---------+--------------+------+-----+---------+-------+
3 rows in set (0.01 sec)

No comments:

Post a Comment