![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh4ZoJpFw51Z3RSW3L06UlY-E8nO0QMXupLuQC6JCIqra2ZOwaaEE3bsum-fwA4sj_BEMZl2RKhFOBeFgETNbyerjIO1-hePwoOpdceh-exyDulMiSGgXB8LxBci-PlDG-eBg8hKOM-s-TI/s400/Difference+Between+Primary+Key+And+Unique+Key+And+Foreign+Key+And+Composite+Key.png)
Primary Key
- Primary Key can identify a row as uniquely
- A table can have only one primary key
- It can't be Null
- Indexing added automatically to Primary key
Foreign Key
- A FOREIGN KEY in one table reference to a Primary Key in another table
- A table can have one OR more foreign key.
- It can be Null
- Indexing not added automatically to Foreign key
Unique Key
- Unique Key can identify a row as uniquely.
- A table can have one OR more unique key.
- It can be Null
- Indexing not added automatically to Unique Key
Composite Key
- A composite key contains at least one compound key and one more attribute. Composite keys may also include simple keys and non-key attributes.
- A table can have one OR more composite Key
- It can also be null.
See Example:
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`email` varchar(100) NOT NULL,
`phone` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `user_profile` (
`user_id` int(11) NOT NULL,
`address1` varchar(100) NOT NULL,
`address2` varchar(100) NOT NULL,
KEY `user_id` (`user_id`),
FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Primary Key: users.id
Foreign Key: user_profile.user_id
Unique Key: users.email
Foreign Key: user_profile.user_id
Unique Key: users.email
Post a Comment