- To add a new colmn to the existing table the ALTER command is used.
Syntax:
alter table < table name > add < column name > ;
Example:
To add a column called ldate to the main_tab table with a datatype of date, use the following SQL statement:
mysql> alter table main_tab add ldate date;
This statement will add the ldate column to the end of the table. - To insert the new column after a specific column, such as name,
use this statement:
ALTER TABLE contacts ADD email VARCHAR(60) AFTER name;
mysql> alter table main_tab add ldate date after doj;
Query OK, 11 rows affected (0.12 sec)
Records: 11 Duplicates: 0 Warnings: 0
mysql> desc main_tab;
+----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+----------------+
| acc_no | int(5) | NO | PRI | NULL | auto_increment |
| name | varchar(20) | YES | | NULL | |
| gender | varchar(6) | YES | | NULL | |
| password | varchar(10) | YES | | NULL | |
| doj | date | YES | | NULL | |
| ldate | date | YES | | NULL | |
| amount | float(10,2) | YES | | NULL | |
+----------+-------------+------+-----+---------+----------------+
7 rows in set (0.00 sec)
-
If you want the new column to be first, use this statement:
ALTER TABLE contacts ADD email VARCHAR(60) FIRST;
//To drop a particular column in mysql table
mysql> desc main_tab;
+----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+----------------+
| acc_no | int(5) | NO | PRI | NULL | auto_increment |
| name | varchar(20) | YES | | NULL | |
| gender | varchar(6) | YES | | NULL | |
| password | varchar(10) | YES | | NULL | |
| doj | date | YES | | NULL | |
| amount | float(10,2) | YES | | NULL | |
| ldate | date | YES | | NULL | |
+----------+-------------+------+-----+---------+----------------+
7 rows in set (0.00 sec)
mysql> alter table main_tab drop ldate;
Query OK, 11 rows affected (0.10 sec)
Records: 11 Duplicates: 0 Warnings: 0
mysql> desc main_tab;
+----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+----------------+
| acc_no | int(5) | NO | PRI | NULL | auto_increment |
| name | varchar(20) | YES | | NULL | |
| gender | varchar(6) | YES | | NULL | |
| password | varchar(10) | YES | | NULL | |
| doj | date | YES | | NULL | |
| amount | float(10,2) | YES | | NULL | |
+----------+-------------+------+-----+---------+----------------+
6 rows in set (0.00 sec)
how to change a column without deleting the contents in mysql table
Friday, 26 November 2010
how to add a column after a particular column in mysql table
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment