Mega Code Archive

 
Categories / MySQL / Key
 

Two ways to declare primary key when creating the table

mysql> mysql> CREATE TABLE IF NOT EXISTS cups     -> (     ->   id     INT     AUTO_INCREMENT PRIMARY KEY,     ->   cup_pattern    VARCHAR(25)     -> ); Query OK, 0 rows affected (0.01 sec) mysql> mysql> # create a table called "saucers" with 2 columns mysql> CREATE TABLE IF NOT EXISTS saucers     -> (     ->   id     INT     AUTO_INCREMENT,     ->   scr_pattern    VARCHAR(25),     ->   PRIMARY KEY(id)     -> ); Query OK, 0 rows affected (0.00 sec) mysql> mysql> # confirm the "cups" and "saucers" table format mysql> EXPLAIN cups; +-------------+-------------+------+-----+---------+----------------+ | Field       | Type        | Null | Key | Default | Extra          | +-------------+-------------+------+-----+---------+----------------+ | id          | int(11)     | NO   | PRI | NULL    | auto_increment | | cup_pattern | varchar(25) | YES  |     | NULL    |                | +-------------+-------------+------+-----+---------+----------------+ 2 rows in set (0.00 sec) mysql> EXPLAIN saucers; +-------------+-------------+------+-----+---------+----------------+ | Field       | Type        | Null | Key | Default | Extra          | +-------------+-------------+------+-----+---------+----------------+ | id          | int(11)     | NO   | PRI | NULL    | auto_increment | | scr_pattern | varchar(25) | YES  |     | NULL    |                | +-------------+-------------+------+-----+---------+----------------+ 2 rows in set (0.00 sec) mysql> mysql> # delete these sample tables mysql> DROP TABLE cups, saucers; Query OK, 0 rows affected (0.00 sec)