SQL Constraints
Not Null
If we specify a field in a table to be NOT NULL, then the field will never accept a null value. You will be not allowed to insert a new row in the table without specifying a value to this field.
create table
students (
student_id int(6) not null,
name varchar(10) not null,
address varchar(20)
);
Unique
This constraint helps to uniquely identify each row in the table. i.e. for a particular column, all the rows should have unique values. We can have more than one UNIQUE column in a table.
create table
students (
student_id int(6) not null unique,
name varchar(10),
address varchar(20)
);
Primary Key
Primary Key is a field which uniquely identifies each row in the table. If a field in a table is the primary key, then the field will not be able to contain NULL values as well as all the rows should have unique values for this field. So, in other words, we can say that this is a combination of NOT NULL and UNIQUE constraints.
A table can have only one field as the primary key.
create table
students (
student_id int(6) not null unique,
name varchar(10),
address varchar(20),
primary key (id)
);
Foreign Key
Foreign Key is a field in a table which uniquely identifies each row of another table. This field points to the primary key of another table and creates a link between the tables.
create table
orders (
order_id int not null,
order_no int not null,
customer_id int,
primary key (order_id),
foreign key (customer_id) references customers (customer_id)
);
Check
Using the CHECK constraint we can specify a condition for a field, which should be satisfied at the time of entering values for this field.
create table
students (
student_id int(6) not null,
name varchar(10) not null,
age int not null check (age >= 18)
);
Default
This constraint is used to provide a default value for the fields. If at the time of entering new records in the table, the user does not specify any value for these fields then the default value will be assigned to them.
create table
students (
student_id int(6) not null,
name varchar(10) not null,
age int default 18
);
Subscribe to my newsletter
Read articles from David Ferrol directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
David Ferrol
David Ferrol
I ❤️ Oracle APEX