Overview
In this article discuss about the Constraints in SQL. Why it is required for any developer before create the table or fully database for our projects or application. Why it's very import phase for any type of database define or design for a our application.
Constraints
It's define some condition when we perform any DML Operation(Data Manipulation Language Syntax like Insert new Record,Update New Record and also perform the Delete operation) in the database.
Suppose we have a master data table and we want to delete some rows of master table if any row or rows inserted childeren table behalf of this master table records if deletion is perform so childeren table data is waste or ambiguous data it's contains memory.
So how to prevent the this type of activity inside the database through Constraint.
below some constraint so one by one discuss.
SQL Constraints
- NOT NULL
- Unique
- Primary Key
- Foreign Key
- Check
- Default
Not Null Constraint
If we create a table with NOT NULL Constraints. So that mean in this particular column value we can not empty inserted because that's show error so please see in below picture.
First We create a table with Not Null Constraints
Picture for create table with NOT NULL Constraints
Now Try to insert with null value
Showing Error when we try to insert data with null values
Unique Constraint
If we create or apply with any column unique constraint that's mean this column all row values is unique. Below images show the output.
Now create table with Unique constraints
Create table with Unique constraints Now try to some data insert with unique constraints
Insert data with unique constraints
Show the OUTPUT below Picture
Explaination
Here first two insertion query is different value with Email column but last two insertion query with same first two insertion query. so that's why below two row insertion failed.
Primary Key Constraint
Primary Key Constraint is define or contains some rules.
- Not Null and Unique Constraint it's says about this column value is not null and each record is unique without duplication.
- Single or Composite it's mean a primary key can be define on single column and multiple column (Composite Key Constraint)
- Indexing Primary Key always define the a index that's called Culster Index. Indexing basically used Data Structure a most popular term that Tree and Hashing(Balance Tree and HashMap) based on different-different database system.
Below some code Snippet for your better understanding.
and other Other Query for different Purpose.
- On Multiple Columns Set Primary Key
CREATE TABLE Orders (
OrderID INT,
ProductID INT,
Quantity INT,
CONSTRAINT PK_Order PRIMARY KEY (OrderID, ProductID)
); - Create on Existing table
ALTER TABLE table_name
ADD CONSTRAINT pk_name PRIMARY KEY (column_name);
0 Comments
thanks for your suggestion and improving quality of the content