Below are the differences between Primary Key and Unique Key
CREATE TABLE customer (
`idcustomer` int(11) NOT NULL,
`firstname` varchar(50) NULL,
`lastname` varchar(30) NULL,
`age` int(11) NOT NULL ,
`phonenumber` char(11) NULL,
`dob` date DEFAULT NULL,
`gender` char(1) NOT NULL
,Constraint pk_idcustomer Primary key(idcustomer),
Constraint uq_firstname Unique Key(firstname),
Constraint uq_lastname Unique Key(lastname)
);
- Primary Key does not accept Null values but Unique Key column can accept Null values.
- There is only One Primary Key per table but You can have multiple Unique Keys per Table
- By default it added cluster index when you create Primary key, for Unique Key it creates Non-cluster index.
In below example, you can see that we created Primary key on idcustomer column and Unique Constraint on firstname and lastname.
CREATE TABLE customer (
`idcustomer` int(11) NOT NULL,
`firstname` varchar(50) NULL,
`lastname` varchar(30) NULL,
`age` int(11) NOT NULL ,
`phonenumber` char(11) NULL,
`dob` date DEFAULT NULL,
`gender` char(1) NOT NULL
,Constraint pk_idcustomer Primary key(idcustomer),
Constraint uq_firstname Unique Key(firstname),
Constraint uq_lastname Unique Key(lastname)
);
Check out detail demo for Difference between Primary Key and Unique Key in MySQL
No comments:
Post a Comment