What do you mean by PRIMARY KEY and how can we use it in MySQL table?

MySQLMySQLi Database

PRIMARY KEY uniquely identifies each row in a database. A PRIMARY KEY must contain unique value and must not contain NULL values. There can be only one PRIMARY KEY in a MySQL table. We can create a PRIMARY KEY column by defining a PRIMARY KEY constraint. For defining PRIMARY KEY constraint we must have to use PRIMARY KEY keyword while creating the table and it can be demonstrated in the following example −

Example

The following query we have created a table named ‘student’ by defining the column ‘RollNo’ as PRIMARY KEY −

mysql> Create Table Student(RollNo INT PRIMARY KEY, Name Varchar(20),
   Address Varchar(20), DOB DATE);
Query OK, 0 rows affected (0.16 sec)

Now by describing the table as follows, we can see ‘RollNo’ is having a PRIMARY KEY constraint −

mysql> Describe Student;

+---------+-------------+------+-----+---------+-------+
| Field   | Type        | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| RollNo  | int(11)     | NO   | PRI | NULL    |       |
| Name    | varchar(20) | YES  |     | NULL    |       |
| Address | varchar(20) | YES  |     | NULL    |       |
| DOB     | date        | YES  |     | NULL    |       |
+---------+-------------+------+-----+---------+-------+

4 rows in set (0.03 sec)

Now, the ‘RollNo’ column of the ‘Student’ table must have unique values and it cannot have null values.

raja
Published on 16-Feb-2018 18:52:18
Advertisements