Data Types
Data Types
A data type is an attribute that specifies the type of data that these objects can store. It
can be an integer, character string, monetary, date and time, and so on.
Exact numeric data types
Data Type Lower limit Upper limit Memory
bigint −2^63 (−9,223,372, 2^63−1 (−9,223,372, 8 bytes
036,854,775,808) 036,854,775,807)
Constraints in SQL Server are predefined rules and restrictions that are enforced in a single column or
multiple columns, regarding the values allowed in the columns, to maintain the integrity, accuracy, and
reliability of that column’s data.
There are six main constraints that are commonly used in SQL Server that we will describe deeply with
examples within this article and the next one. These constraints are:
UNIQUE Constraints
‘The UNIQUE constraint in SQL is used to ensure that no duplicate values will be inserted into a specific
column or combination of columns that are participating in the UNIQUE constraint and not part of the
PRIMARY KEY. In other words, the index that is automatically created when you define a UNIQUE
constraint will guarantee that no two rows in that table can have the same value for the columns
participating in that index, with the ability to insert only one unique NULL value to these columns, if the
column allows NULL.
CREATE TABLE ConstraintDemo2
(
ID INT UNIQUE,
Name VARCHAR(50) NULL
)
A Foreign Key is a database key that is used to link two tables together. The FOREIGN KEY constraint
identifies the relationships between the database tables by referencing a column, or set of columns, in
the Child table that contains the foreign key, to the PRIMARY KEY column or set of columns, in
the Parent table.
The relationship between the child and the parent tables is maintained by checking the existence of the
child table FOREIGN KEY values in the referenced parent table’s PRIMARY KEY before inserting these
values into the child table.
CREATE TABLE ConstraintDemoParent
(
ID INT PRIMARY KEY,
Name VARCHAR(50) NULL
)
GO
CREATE TABLE ConstraintDemoChild
(
CID INT PRIMARY KEY,
ID INT FOREIGN KEY REFERENCES ConstraintDemoParent(ID)
)
CHECK Constraint
A CHECK constraint is defined on a column or set of columns to limit the range of values, that can be
inserted into these columns, using a predefined condition. The CHECK constraint comes into action to
evaluate the inserted or modified values, where the value that satisfies the condition will be inserted
into the table, otherwise, the insert operation will be discarded.