Mega Code Archive

 
Categories / MySQL / Table Index
 

Alter table to add primary key, add new column, change column, drop column

mysql> CREATE TABLE IF NOT EXISTS dishes     -> (     ->   id             INT             NOT NULL,     ->   pattern        VARCHAR(25)     NOT NULL,     ->   price          DECIMAL(6,2)     -> ); Query OK, 0 rows affected (0.00 sec) mysql> mysql> EXPLAIN dishes;          # confirm the "dishes" table format +---------+--------------+------+-----+---------+-------+ | Field   | Type         | Null | Key | Default | Extra | +---------+--------------+------+-----+---------+-------+ | id      | int(11)      | NO   |     | NULL    |       | | pattern | varchar(25)  | NO   |     | NULL    |       | | price   | decimal(6,2) | YES  |     | NULL    |       | +---------+--------------+------+-----+---------+-------+ 3 rows in set (0.00 sec) mysql> mysql> ALTER TABLE dishes     ->   ADD PRIMARY KEY(id),     ->   ADD COLUMN code INT UNIQUE NOT NULL,     ->   CHANGE pattern dish_pattern VARCHAR(25) NOT NULL,     ->   DROP COLUMN price; Query OK, 0 rows affected (0.01 sec) Records: 0  Duplicates: 0  Warnings: 0 mysql> mysql> EXPLAIN dishes;          # confirm the "dishes" table format +--------------+-------------+------+-----+---------+-------+ | Field        | Type        | Null | Key | Default | Extra | +--------------+-------------+------+-----+---------+-------+ | id           | int(11)     | NO   | PRI | NULL    |       | | dish_pattern | varchar(25) | NO   |     | NULL    |       | | code         | int(11)     | NO   | UNI | NULL    |       | +--------------+-------------+------+-----+---------+-------+ 3 rows in set (0.00 sec) mysql> DROP TABLE dishes;       # delete this sample table Query OK, 0 rows affected (0.00 sec)