sql
sql
SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table.
Constraints can be column level or table level. Column level constraints apply
to a column, and table level constraints apply to the whole table.
Types of SQL Constraints
1. NOT NULL
Ensures that a column cannot contain NULL values. Every row must have a
value in this column.
It is used to avoid null values:
Commonly used for mandatory fields like name, ID, etc.
Null means empty space if user doesn’t pass any data into cell, it will considered
as null value
EXAMPLE:
CREATE TABLE Employees (
EmpID INT,
FullName VARCHAR(100) NOT NULL
);
2. UNIQUE Constraint
Ensures that all values in a column (or set of columns) are different.
Key Points:
Prevents duplicate entries in the column.
Allows only one NULL value
Example:
CREATE TABLE Employees (
EmpID INT,
FullName VARCHAR(100) NOT NULL,
Email VARCHAR(100) UNIQUE
);
3. PRIMARY KEY Constraint
Example:
1. Char
It helps to store alpha numeric values along with some special
character [‘A-z’,’a-z’,0-9, !,@,#,$,&]
It Stores up to 2000 characters. Characters must be enclosed within
(‘ ‘) single quotes.
It follows fixed length memory allocation.
When the size is fixed, we can store till the size mentioned , if we try
to store more than that their may be data loss.
If we try to store less than the given size, there will be memory loss.
Syntax:
Column-name char(size)
Ex: cfsc char(10)
2. Varchar / varchar 2
It helps to store alpha numeric values along with some special
character [‘A-z’,’a-z’,0-9, !,@,#,$,&]
It Stores up to 2000 characters. Characters must be enclosed within
( ‘ ‘ )single quotes.
It follows variable length memory allocation.
When the size is fixed, we can store till the size mentioned , if we try to
store more than that there may be data loss.
If we try to store less than the given size, there will be no memory
wastage.
Syntax: Column-name varchar(mention-size)
Ex: cfsc Varchar(10)
3. Number
Used to Store numeric values
Syntax: number (p,s)
Precision: Used to determine the number of values stored as integer
value.
Scale :used to determine the number of values stored after decimal.
E.g.: number(5,10)
4 Date
Used to store date type of data
Syntax; DD-MM-YYYY
E.g.: 18-Jun-2023
5.Large objects
1.CLOB [Character Large Objects]
2. BLOB [Binary Large Objects]
1. Character large objects:
It helps to store the textual information that are too long.
It can store up to 4gb
Ex: Script, Xml etc.
2. Binary Large object
It helps to Store the images, mp3, mp4 and gif of binary
values in binary stream.
It can store up to 4gb