What is the difference between primary key and unique constraints in SQL - DeveloperIndian

5/7/2022
All Articles

#difference_between_primary_key_and_unique_constraints #sql_constraints #oracle mysql #what is constraint in sql

What is the difference between primary key and unique constraints in SQL - DeveloperIndian

What is the difference between primary key and unique constraints?

Primary key cannot have NULL value, the unique constraints can have NULL values.
There is only one primary key in a table, but there can be multiple unique constrains.

UNIQUE: This constraint when specified with a column, tells that all the values in the column must be unique. That is, the values in any row of a column must not be duplicate.
PRIMARY KEY: A primary key is a field which can uniquely identify each row in a table. And primary key constraint is used to specify a field in a table as primary key which is always contain unique data.
 

Below is the syntax to create constraints  at the time of creating the table. 
CREATE TABLE demo_table
(
column1 data_type(size) constraint_name,
column2 data_type(size) constraint_name,
column3 data_type(size) constraint_name,
....
);

demo_table: Name of the table to be created.
data_type: Type of data that can be stored in the field  .
constraint_name: Name of the constraint which is used by us. for example- NOT NULL, UNIQUE, PRIMARY KEY etc. 
 

 

Article