Chapter 08-2 Database Constraints Part 2
Chapter 08-2 Database Constraints Part 2
Chapter 8
CHECK Constraints
• Enforce business rules by placing restrictions on the data that
can be entered into a column
• The DBMS checks to make sure a new or changed row
doesn't violate any of its table's check constraints before an
insert or update operation is allowed
• CHECK keyword
2
Compare a column to a range of values
• Guarantees that the salary is between 15.00 and 45.00 inclusive
3
Compare Two columns
4
Compare Columns
ALTER TABLE customers
ADD CONSTRAINT cust_status_name_check
CHECK ( ( status = 'A' OR status = 'I' )
AND ( name <> ' ' ) );
5
Compare a Column to a List of Constants
6
Limit Constraint
7
NULL Constraint
8
Compare a Column to an Expressions
9
Boolean Data Type
• SQL does not support a Boolean data type
• Can be represented using a CHECK constraint
10
Boolean Data Type
11
Dropping Primary Key Constraint
• Specify the PRIMARY KEY keywords
12
Drop other Constraints
• To drop a unique, foreign key, or check constraint, specify the
constraint name
13
Adding a Constraint to an Existing Table Containing
Data
• Adding a constraint to an existing table requires that all existing
data comply with the constraint being added
• The data in an existing table might have to be cleaned up prior
to adding a constraint
• If a constraint is added to a table that already contains data that
violates the constraint, the constraint is added in a disabled
state and will not work
14
ALTER TABLE
Adding a New Column to an Existing Table
• When you add a new column to an existing table, you have three options:
– Make it NOT NULL, in which case you must supply a value to insert into the
column for every row using the WITH DEFAULT clause.
– Make the column NULL capable, in which case the DBMS will insert NULL
values into the columns
– Make it NULL capable and give it a default value
15
Constraint Unit Testing
16
17