Monday 19 December 2011

How to Create a MySQL Table with a Primary Key

This is one way to create a table with a primary key. In this example, the primary key consists of one column. In a future post, I will show how to set up a primary key with more than one column: 

mysql> create table andrews_table
    -> (col1 varchar(10), primary key(col1));
Query OK, 0 rows affected (0.02 sec)
 
mysql> insert into andrews_table values ('Fred');
Query OK, 1 row affected (0.00 sec)

mysql>
  
The purpose of a primary key is to ensure that the values in the primary key column remain unique. So, if you try to insert Fred into the primary key column again, you would expect the insert to fail:
 
mysql> insert into andrews_table values ('Fred');
ERROR 1062 (23000): Duplicate entry 'Fred' for key 1
mysql> select * from andrews_table;
+------+
| col1 |
+------+
| Fred |
+------+
1 row in set (0.00 sec)
 
mysql>

No comments: