Constraints
Constraints
Constraints
Constraints are used to ensure data integrity rules are followed as data is inserted into the database
table. A constraint defines the values that are allowed in the column and table. As data is entered into
the database, the constraint allows only valid data to be saved.
NULL
NOT NULL
DEFAULT
CHECK
You have used several of the above constraints already but perhaps without realizing they are
categorized as a constraint. Let's review these:
The PK constraint limits the data to be the unique column value in the table. The PK column cannot
be left blank or cannot be NULL. The PK is used to create relations between two or more tables.
A NULL constraint is considered the default for a table column unless defined otherwise. NULL
means that it can be left empty when data rows are inserted into a table. For some columns, it is
fine to be NULL; for other columns, you do not want them to be empty.
A NOT NULL constraint is defined so that, when a row is inserted, a data value must be included
for the column.
Other constraints that can be used in a column or table are the following:
A DEFAULT constraint will add a set value to a column if another value isn't specified. For example,
if the customer database is used mainly to collect customer data from the city of NY, then NY could
be defined as the default so that it will automatically be saved as the city.
A CHECK column constraint will ensure that the data values fall within a certain range. For
example, the UnitPrice in a table must be greater than 0.
A CHECK table constraint will ensure that values inserted into columns are based on other
columns in the row. For example, if you have a UnitPrice and a DiscountPrice in a table, the CHECK
constraint could be defined such that the DiscountPrice has to be less than the UnitPrice.
https://ed2go-cbl.difference-engine.com/Courses/sql-6-0821/#/student/content/698cba96534494b6982203d470ce8d4f?contentItemRoot=_root_ 1/1