Download - 05 ICT118 SQL Constraints Sem 2 2010
8/2/2019 05 ICT118 SQL Constraints Sem 2 2010
http://slidepdf.com/reader/full/05-ict118-sql-constraints-sem-2-2010 1/12
1
Database and InformationDatabase and InformationDatabase and InformationDatabase and Information
RetrievalRetrievalRetrievalRetrieval
ICT118
Lecture 5 Implementing business rules throughdatabase constraints
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.2
Oracle 11g: SQL
Chapter 4
ConstraintsSlides from the Cengage website for Casteel, “Oracle 11g: SQL”
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.3
ObjectivesObjectivesObjectivesObjectives
Explain the purpose of constraints in a tableExplain the purpose of constraints in a tableExplain the purpose of constraints in a tableExplain the purpose of constraints in a table
Distinguish among PRIMARY KEY, FOREIGN KEY,Distinguish among PRIMARY KEY, FOREIGN KEY,Distinguish among PRIMARY KEY, FOREIGN KEY,Distinguish among PRIMARY KEY, FOREIGN KEY,UNIQUE, CHECK, and NOT NULL constraintsUNIQUE, CHECK, and NOT NULL constraintsUNIQUE, CHECK, and NOT NULL constraintsUNIQUE, CHECK, and NOT NULL constraintsand the appropriate use for each constraint and the appropriate use for each constraint and the appropriate use for each constraint and the appropriate use for each constraint
Understand how constraints can be created whenUnderstand how constraints can be created whenUnderstand how constraints can be created whenUnderstand how constraints can be created whencreating a table or modifying an existing tablecreating a table or modifying an existing tablecreating a table or modifying an existing tablecreating a table or modifying an existing table
Distinguish between creating constraints at theDistinguish between creating constraints at theDistinguish between creating constraints at theDistinguish between creating constraints at thecolumn level and table levelcolumn level and table levelcolumn level and table levelcolumn level and table level
8/2/2019 05 ICT118 SQL Constraints Sem 2 2010
http://slidepdf.com/reader/full/05-ict118-sql-constraints-sem-2-2010 2/12
2
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.4
Objectives (continued)Objectives (continued)Objectives (continued)Objectives (continued)
Create PRIMARY KEY constraints for a singleCreate PRIMARY KEY constraints for a singleCreate PRIMARY KEY constraints for a singleCreate PRIMARY KEY constraints for a single
column and a composite primary keycolumn and a composite primary keycolumn and a composite primary keycolumn and a composite primary key
Create a FOREIGN KEY constraint Create a FOREIGN KEY constraint Create a FOREIGN KEY constraint Create a FOREIGN KEY constraint
Create a UNIQUE constraint Create a UNIQUE constraint Create a UNIQUE constraint Create a UNIQUE constraint
Create a CHECK constraint Create a CHECK constraint Create a CHECK constraint Create a CHECK constraint
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.5
Objectives (continued)Objectives (continued)Objectives (continued)Objectives (continued)
Create a NOT NULL constraint using theCreate a NOT NULL constraint using theCreate a NOT NULL constraint using theCreate a NOT NULL constraint using the
ALTER TABLE…MODIFY commandALTER TABLE…MODIFY commandALTER TABLE…MODIFY commandALTER TABLE…MODIFY command
Include constraints during table creationInclude constraints during table creationInclude constraints during table creationInclude constraints during table creation
Use DISABLE and ENABLE commandsUse DISABLE and ENABLE commandsUse DISABLE and ENABLE commandsUse DISABLE and ENABLE commands
Use the DROP commandUse the DROP commandUse the DROP commandUse the DROP command
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.6
ConstraintsConstraintsConstraintsConstraints
Rules used to enforce business rules,Rules used to enforce business rules,Rules used to enforce business rules,Rules used to enforce business rules,
practices, and policiespractices, and policiespractices, and policiespractices, and policies
Rules used to ensure accuracy and integrity of Rules used to ensure accuracy and integrity of Rules used to ensure accuracy and integrity of Rules used to ensure accuracy and integrity of
datadatadatadata
8/2/2019 05 ICT118 SQL Constraints Sem 2 2010
http://slidepdf.com/reader/full/05-ict118-sql-constraints-sem-2-2010 3/12
3
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.7
Constraint TypesConstraint TypesConstraint TypesConstraint Types
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.8
Creating ConstraintsCreating ConstraintsCreating ConstraintsCreating Constraints
Use the optional CONSTRAINT keyword duringUse the optional CONSTRAINT keyword duringUse the optional CONSTRAINT keyword duringUse the optional CONSTRAINT keyword during
creation to assign a namecreation to assign a namecreation to assign a namecreation to assign a name
Let the server name the constraint using theLet the server name the constraint using theLet the server name the constraint using theLet the server name the constraint using the
default format SYS_Cdefault format SYS_Cdefault format SYS_Cdefault format SYS_Cn nn n
Informative names can assist in debuggingInformative names can assist in debuggingInformative names can assist in debuggingInformative names can assist in debugging
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.9
Creating ConstraintsCreating ConstraintsCreating ConstraintsCreating Constraints(continued)(continued)(continued)(continued)WhenWhenWhenWhen
During table creation
After table creation, by modifying the existing table
HowHowHowHow
Column level approach
Table level approach
8/2/2019 05 ICT118 SQL Constraints Sem 2 2010
http://slidepdf.com/reader/full/05-ict118-sql-constraints-sem-2-2010 4/12
4
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.10
Creating Constraints at theCreating Constraints at theCreating Constraints at theCreating Constraints at the
Column LevelColumn LevelColumn LevelColumn Level
If a constraint is being created at the columnIf a constraint is being created at the columnIf a constraint is being created at the columnIf a constraint is being created at the column
level, the constraint applies to the columnlevel, the constraint applies to the columnlevel, the constraint applies to the columnlevel, the constraint applies to the column
specifiedspecifiedspecifiedspecified
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.11
Creating Constraints at the TableCreating Constraints at the TableCreating Constraints at the TableCreating Constraints at the Table
LevelLevelLevelLevel
Approach can be used to create anyApproach can be used to create anyApproach can be used to create anyApproach can be used to create anyconstraint type except NOT NULLconstraint type except NOT NULLconstraint type except NOT NULLconstraint type except NOT NULL
Required if constraint is based on multipleRequired if constraint is based on multipleRequired if constraint is based on multipleRequired if constraint is based on multiplecolumnscolumnscolumnscolumns
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.12
Enforcement of ConstraintsEnforcement of ConstraintsEnforcement of ConstraintsEnforcement of Constraints
All constraints are enforced at the table levelAll constraints are enforced at the table levelAll constraints are enforced at the table levelAll constraints are enforced at the table level
If a data value violates a constraint, the entireIf a data value violates a constraint, the entireIf a data value violates a constraint, the entireIf a data value violates a constraint, the entire
row is rejectedrow is rejectedrow is rejectedrow is rejected
8/2/2019 05 ICT118 SQL Constraints Sem 2 2010
http://slidepdf.com/reader/full/05-ict118-sql-constraints-sem-2-2010 5/12
5
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.13
Adding Constraints to ExistingAdding Constraints to ExistingAdding Constraints to ExistingAdding Constraints to Existing
TablesTablesTablesTablesConstraints are added to an existing table withConstraints are added to an existing table withConstraints are added to an existing table withConstraints are added to an existing table with
the ALTER TABLE commandthe ALTER TABLE commandthe ALTER TABLE commandthe ALTER TABLE command
Add a NOT NULL constraint using MODIFYAdd a NOT NULL constraint using MODIFYAdd a NOT NULL constraint using MODIFYAdd a NOT NULL constraint using MODIFY
clauseclauseclauseclause
All other constraints are added using ADDAll other constraints are added using ADDAll other constraints are added using ADDAll other constraints are added using ADD
clauseclauseclauseclause
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.14
Using the PRIMARY KEYUsing the PRIMARY KEYUsing the PRIMARY KEYUsing the PRIMARY KEY
Constraint Constraint Constraint Constraint
Ensures that columns do not containEnsures that columns do not containEnsures that columns do not containEnsures that columns do not contain
duplicate or NULL valuesduplicate or NULL valuesduplicate or NULL valuesduplicate or NULL values
Only one per table is allowedOnly one per table is allowedOnly one per table is allowedOnly one per table is allowed
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.15
Constraint Checked withConstraint Checked withConstraint Checked withConstraint Checked withData Input Data Input Data Input Data Input
8/2/2019 05 ICT118 SQL Constraints Sem 2 2010
http://slidepdf.com/reader/full/05-ict118-sql-constraints-sem-2-2010 6/12
6
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.16
PRIMARY KEY Constraint forPRIMARY KEY Constraint forPRIMARY KEY Constraint forPRIMARY KEY Constraint for
Composite KeyComposite KeyComposite KeyComposite KeyList column names within parenthesesList column names within parenthesesList column names within parenthesesList column names within parentheses
separated by commasseparated by commasseparated by commasseparated by commas
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.17
Using the FOREIGN KEYUsing the FOREIGN KEYUsing the FOREIGN KEYUsing the FOREIGN KEY
Constraint Constraint Constraint Constraint
Requires a value to exist in the referencedRequires a value to exist in the referencedRequires a value to exist in the referencedRequires a value to exist in the referenced
column of another tablecolumn of another tablecolumn of another tablecolumn of another table
NULL values are allowedNULL values are allowedNULL values are allowedNULL values are allowed
Enforces referential integrityEnforces referential integrityEnforces referential integrityEnforces referential integrity
Maps to the PRIMARY KEY in parent tableMaps to the PRIMARY KEY in parent tableMaps to the PRIMARY KEY in parent tableMaps to the PRIMARY KEY in parent table
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.18
FOREIGN KEY Constraint FOREIGN KEY Constraint FOREIGN KEY Constraint FOREIGN KEY Constraint ExampleExampleExampleExample
8/2/2019 05 ICT118 SQL Constraints Sem 2 2010
http://slidepdf.com/reader/full/05-ict118-sql-constraints-sem-2-2010 7/12
7
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.19
Deletion of Foreign Key ValuesDeletion of Foreign Key ValuesDeletion of Foreign Key ValuesDeletion of Foreign Key Values
YouYouYouYou cannot cannot cannot cannot delete a value in a parent tabledelete a value in a parent tabledelete a value in a parent tabledelete a value in a parent table
referenced by a row in a child tablereferenced by a row in a child tablereferenced by a row in a child tablereferenced by a row in a child table
Use ON DELETE CASCADE keywords whenUse ON DELETE CASCADE keywords whenUse ON DELETE CASCADE keywords whenUse ON DELETE CASCADE keywords when
creating FOREIGN KEY constraint creating FOREIGN KEY constraint creating FOREIGN KEY constraint creating FOREIGN KEY constraint – –– – thisthisthisthis
clause automatically deletes a parent rowclause automatically deletes a parent rowclause automatically deletes a parent rowclause automatically deletes a parent row
when the row in a child table is deletedwhen the row in a child table is deletedwhen the row in a child table is deletedwhen the row in a child table is deleted
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.20
Using the UNIQUE Constraint Using the UNIQUE Constraint Using the UNIQUE Constraint Using the UNIQUE Constraint
No duplicates are allowed in the referencedNo duplicates are allowed in the referencedNo duplicates are allowed in the referencedNo duplicates are allowed in the referenced
columncolumncolumncolumn
NULL values are permittedNULL values are permittedNULL values are permittedNULL values are permitted
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.21
Using the CHECK Constraint Using the CHECK Constraint Using the CHECK Constraint Using the CHECK Constraint
Updates and additions must meet Updates and additions must meet Updates and additions must meet Updates and additions must meet
specified conditionspecified conditionspecified conditionspecified condition
8/2/2019 05 ICT118 SQL Constraints Sem 2 2010
http://slidepdf.com/reader/full/05-ict118-sql-constraints-sem-2-2010 8/12
8
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.22
Using the NOT NULL Constraint Using the NOT NULL Constraint Using the NOT NULL Constraint Using the NOT NULL Constraint
The NOT NULL constraint is a special CHECKThe NOT NULL constraint is a special CHECKThe NOT NULL constraint is a special CHECKThe NOT NULL constraint is a special CHECK
constraint with IS NOT NULL conditionconstraint with IS NOT NULL conditionconstraint with IS NOT NULL conditionconstraint with IS NOT NULL condition
Can only be created at column levelCan only be created at column levelCan only be created at column levelCan only be created at column level
Included in output of DESCRIBE commandIncluded in output of DESCRIBE commandIncluded in output of DESCRIBE commandIncluded in output of DESCRIBE command
Can only be added to an existing table usingCan only be added to an existing table usingCan only be added to an existing table usingCan only be added to an existing table using
ALTER TABLE…MODIFY commandALTER TABLE…MODIFY commandALTER TABLE…MODIFY commandALTER TABLE…MODIFY command
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.23
NOT NULL Constraint ExampleNOT NULL Constraint ExampleNOT NULL Constraint ExampleNOT NULL Constraint Example
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.24
Including Constraints duringIncluding Constraints duringIncluding Constraints duringIncluding Constraints during
Table CreationTable CreationTable CreationTable Creation – –– – Column LevelColumn LevelColumn LevelColumn Level
Include in column definitionInclude in column definitionInclude in column definitionInclude in column definition
8/2/2019 05 ICT118 SQL Constraints Sem 2 2010
http://slidepdf.com/reader/full/05-ict118-sql-constraints-sem-2-2010 9/12
9
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.25
Including Constraints duringIncluding Constraints duringIncluding Constraints duringIncluding Constraints during
Table CreationTable CreationTable CreationTable Creation – –– – Table LevelTable LevelTable LevelTable LevelInclude at end of column list Include at end of column list Include at end of column list Include at end of column list
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.26
Multiple Constraints on aMultiple Constraints on aMultiple Constraints on aMultiple Constraints on a
Single ColumnSingle ColumnSingle ColumnSingle ColumnA column may be included in multipleA column may be included in multipleA column may be included in multipleA column may be included in multiple
constraintsconstraintsconstraintsconstraints
The order# column is included in a primary keyThe order# column is included in a primary keyThe order# column is included in a primary keyThe order# column is included in a primary key
and a foreign key constraint and a foreign key constraint and a foreign key constraint and a foreign key constraint
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.27
Viewing ConstraintsViewing ConstraintsViewing ConstraintsViewing Constraints – –– – USER_CONSTRAINTSUSER_CONSTRAINTSUSER_CONSTRAINTSUSER_CONSTRAINTS
Display constraint listing for a specificDisplay constraint listing for a specificDisplay constraint listing for a specificDisplay constraint listing for a specific
tabletabletabletable
8/2/2019 05 ICT118 SQL Constraints Sem 2 2010
http://slidepdf.com/reader/full/05-ict118-sql-constraints-sem-2-2010 10/12
10
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.28
Viewing ConstraintsViewing ConstraintsViewing ConstraintsViewing Constraints – –– –
USER_CONS_COLUMNSUSER_CONS_COLUMNSUSER_CONS_COLUMNSUSER_CONS_COLUMNS
Display constraint listing by columnDisplay constraint listing by columnDisplay constraint listing by columnDisplay constraint listing by column
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.29
Using DISABLE/ENABLEUsing DISABLE/ENABLEUsing DISABLE/ENABLEUsing DISABLE/ENABLE
Use DISABLE or ENABLE clause of ALTERUse DISABLE or ENABLE clause of ALTERUse DISABLE or ENABLE clause of ALTERUse DISABLE or ENABLE clause of ALTER
TABLE commandTABLE commandTABLE commandTABLE command
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.30
Dropping ConstraintsDropping ConstraintsDropping ConstraintsDropping Constraints
Constraints cannot be modified; they must beConstraints cannot be modified; they must beConstraints cannot be modified; they must beConstraints cannot be modified; they must be
dropped and redropped and redropped and redropped and re----createdcreatedcreatedcreated
Actual syntax depends on the type of Actual syntax depends on the type of Actual syntax depends on the type of Actual syntax depends on the type of
constraint constraint constraint constraint
PRIMARY KEY – just list type of constraint
UNIQUE – include column name
All others – reference the constraint name
8/2/2019 05 ICT118 SQL Constraints Sem 2 2010
http://slidepdf.com/reader/full/05-ict118-sql-constraints-sem-2-2010 11/12
11
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.31
ALTER TABLE…DROP SyntaxALTER TABLE…DROP SyntaxALTER TABLE…DROP SyntaxALTER TABLE…DROP Syntax
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.32
Drop Constraint ExampleDrop Constraint ExampleDrop Constraint ExampleDrop Constraint Example
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.33
Drop Constraint ExampleDrop Constraint ExampleDrop Constraint ExampleDrop Constraint Example – –– – ErrorErrorErrorError
8/2/2019 05 ICT118 SQL Constraints Sem 2 2010
http://slidepdf.com/reader/full/05-ict118-sql-constraints-sem-2-2010 12/12
12
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.34
SummarySummarySummarySummary
A constraint is a rule that is applied to dataA constraint is a rule that is applied to dataA constraint is a rule that is applied to dataA constraint is a rule that is applied to data
being added to a tablebeing added to a tablebeing added to a tablebeing added to a tableThe constraint represents business rules, policies,
and/or procedures
Data violating the constraint is not added to the
table
A constraint can be included during tableA constraint can be included during tableA constraint can be included during tableA constraint can be included during table
creation as part of the CREATE TABLEcreation as part of the CREATE TABLEcreation as part of the CREATE TABLEcreation as part of the CREATE TABLEcommand or added to an existing tablecommand or added to an existing tablecommand or added to an existing tablecommand or added to an existing table
using the ALTER TABLE commandusing the ALTER TABLE commandusing the ALTER TABLE commandusing the ALTER TABLE command
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.35
Summary (continued)Summary (continued)Summary (continued)Summary (continued)
A PRIMARY KEY constraint does not allow duplicate orA PRIMARY KEY constraint does not allow duplicate orA PRIMARY KEY constraint does not allow duplicate orA PRIMARY KEY constraint does not allow duplicate or
NULL values in the designated columnNULL values in the designated columnNULL values in the designated columnNULL values in the designated column
Only one PRIMARY KEY constraint is allowed in a tableOnly one PRIMARY KEY constraint is allowed in a tableOnly one PRIMARY KEY constraint is allowed in a tableOnly one PRIMARY KEY constraint is allowed in a table
A FOREIGN KEY constraint requires that the column entryA FOREIGN KEY constraint requires that the column entryA FOREIGN KEY constraint requires that the column entryA FOREIGN KEY constraint requires that the column entry
match a referenced column entry in the referenced tablematch a referenced column entry in the referenced tablematch a referenced column entry in the referenced tablematch a referenced column entry in the referenced table
or be NULLor be NULLor be NULLor be NULL
A UNIQUE constraint is similar to a PRIMARY KEYA UNIQUE constraint is similar to a PRIMARY KEYA UNIQUE constraint is similar to a PRIMARY KEYA UNIQUE constraint is similar to a PRIMARY KEYconstraint except it allows NULL values to be stored inconstraint except it allows NULL values to be stored inconstraint except it allows NULL values to be stored inconstraint except it allows NULL values to be stored inthe specified columnthe specified columnthe specified columnthe specified column
A CHECK constraint ensures a value meets a specifiedA CHECK constraint ensures a value meets a specifiedA CHECK constraint ensures a value meets a specifiedA CHECK constraint ensures a value meets a specifiedconditionconditionconditioncondition
22 July, 2010 ICT118 Database and Information Retrieval, Sem 2, 2010 5.36
Summary (continued)Summary (continued)Summary (continued)Summary (continued)
A NOT NULL constraint ensures a value isA NOT NULL constraint ensures a value isA NOT NULL constraint ensures a value isA NOT NULL constraint ensures a value isalways provided for a columnalways provided for a columnalways provided for a columnalways provided for a column
A constraint can be disabled or enabled usingA constraint can be disabled or enabled usingA constraint can be disabled or enabled usingA constraint can be disabled or enabled usingthe ALTER TABLE command and the DISABLEthe ALTER TABLE command and the DISABLEthe ALTER TABLE command and the DISABLEthe ALTER TABLE command and the DISABLEand ENABLE keywordsand ENABLE keywordsand ENABLE keywordsand ENABLE keywords
A constraint cannot be modifiedA constraint cannot be modifiedA constraint cannot be modifiedA constraint cannot be modifiedTo change a constraint, the constraint must first bedropped with the DROP command and then re-created
USER_CONSTRAINTS andUSER_CONSTRAINTS andUSER_CONSTRAINTS andUSER_CONSTRAINTS andUSER_CONS_COLUMNS data dictionary viewsUSER_CONS_COLUMNS data dictionary viewsUSER_CONS_COLUMNS data dictionary viewsUSER_CONS_COLUMNS data dictionary viewsprovide information regarding constraintsprovide information regarding constraintsprovide information regarding constraintsprovide information regarding constraints