Keys are essential in the database management system. We have different types of keys in the database. The primary key is a particular type of key that can uniquely identify the table rows. Primary keys must contain unique values and cannot be NULL
. We can only have one primary key in a table.
ID int NOT NULL PRIMARY KEY
Here, ID
is an attribute and int
is the data type and we have declared the ID
as the primary key.
For example, if we have a student table with the column names—student_id
, student_name
, email
, and phone_no
—we can have one primary key in the table.
Here, we can give the student_id
as the primary key.
Student_id |
Student_name |
phone_no |
In the table above, the column marked green can be taken as the primary key.
CREATE TABLE Students ( ID int NOT NULL PRIMARY KEY, Name varchar(255) NOT NULL, email varchar(255), phone int );
Student_id | Student_name | phone_no | |
1 | John | john123@gmail.com | 9632547841 |
2 | Shyam | shyam253@gmail.com | 7896321456 |
3 | John | john654@gmail.com | 9632547841 |
In the table above, we use student_id
as the primary key because the id
attribute is unique throughout the table, whereas when we see the student_name
and the phone_no
attributes, the values get repeated. Therefore, it cannot be declared as the primary key.
RELATED TAGS
CONTRIBUTOR
View all Courses