You are on page 1of 59

26 February 2023 1

INF 312
DATABASE DESIGN AND
DEVELOPMENT

Semester 1, 2023
Week 4 – Lecture 4

Constraints
26 February 2023 2

Lecture 4 Objectives
After completing this chapter, you should be able to do the
following:
• Explain the purpose of constraints in a table
• Distinguish among PRIMARY KEY, FOREIGN KEY,
UNIQUE, CHECK, and NOT NULL constraints and
understand the correct use of each constraint
• Understand how to create constraints when creating a
table or modifying an existing table
• Distinguish between creating constraints at the column
level and the table level
• Create PRIMARY KEY constraints for a single column
and a composite primary key
26 February 2023 3

Lecture 4 Objectives
• Create a FOREIGN KEY constraint
• Create a UNIQUE constraint
• Create a CHECK constraint
• Create a NOT NULL constraint with the ALTER TABLE ...
MODIFY command
• Include constraints during table creation
• Add multiple constraints on a single column
• View constraint information
• Use the DISABLE and ENABLE commands with
constraints
• Use the DROP command with constraints
26 February 2023 4

READINGS
• Casteel, Chapter 4
pp. 99 - 135
• This chapter is important
for SQL skill development.
5

Constraints
• Rules used to enforce business rules, practices, and
policies
• Rules used to ensure accuracy and integrity of data

Oracle 11g: SQL


6

Constraint Types

Oracle 11g: SQL


7

Creating Constraints
• Use the optional CONSTRAINT keyword during creation
to assign a name to the constraint
• Informative constraint names can assist in debugging
• Alternatively, let the server define the name for the
constraint using the default format SYS_Cn

Oracle 11g: SQL


8

Creating Constraints (continued)


• When?
• During table creation
• After table creation, by modifying the existing table
• How?
• Column level approach
• Table level approach

Oracle 11g: SQL


9

Creating Constraints at the Column


Level
• If a constraint is being created at the column level,
the constraint applies to the column specified
• NOT NULL constraint can only be created this way.

Oracle 11g: SQL


10

Creating Constraints at the Table Level

• This approach can be used to create any


constraint type except NOT NULL
• This approach is required if constraint is
based on multiple columns, for example –
two columns as a primary key.

Oracle 11g: SQL


11

Enforcement of Constraints
• All constraints are enforced at the table level, regardless
of how you create them
• If a data value violates a constraint, the entire row is
rejected

Oracle 11g: SQL


12

Adding Constraints to Existing Tables


• Constraints are added to an existing table with
the ALTER TABLE command
• NOT NULL constraint is added using MODIFY clause
• All other constraints are added using ADD clause

Oracle 11g: SQL


13

Using the PRIMARY KEY Constraint

• Ensures that columns do not contain


duplicate or NULL values
• Only one primary key per table is allowed

Oracle 11g: SQL


14

PRIMARY KEY Constraint for Composite Key

• List column names within parentheses


separated by commas

Oracle 11g: SQL


15

Using the FOREIGN KEY Constraint


• Requires a value to exist in the referenced column of
another table
• NULL values are allowed
• Enforces referential integrity
• Maps to the PRIMARY KEY of the parent table

Oracle 11g: SQL


16

FOREIGN KEY Constraint Example

Oracle 11g: SQL


17

Deletion of Foreign Key Values


• You cannot delete a value in a parent table referenced by
a row in a child table
• Use ON DELETE CASCADE keywords when creating
FOREIGN KEY constraint – it automatically deletes a
parent row when the row in a child table is deleted

Oracle 11g: SQL


18

Using the UNIQUE Constraint


• No duplicates are allowed in the referenced column
• NULL values are permitted

Oracle 11g: SQL


19

Using the CHECK Constraint


• Updates and additions must meet specified
condition

Oracle 11g: SQL


20

Using the NOT NULL Constraint


• The NOT NULL constraint is a special CHECK constraint
with IS NOT NULL condition
• Can only be created at column level
• This constraint is displayed when you execute the
DESCRIBE (DESC) command for a table
• Can only be added to an existing table using ALTER
TABLE…MODIFY command

Oracle 11g: SQL


21

NOT NULL Constraint Example

Oracle 11g: SQL


22

Including Constraints during Table Creation


– Column Level
• Include constraints in column definition

Oracle 11g: SQL


23

Including Constraints during Table Creation


– Table Level
• Include constraints at end of column list

Oracle 11g: SQL


24

Multiple Constraints on a Single


Column
• A column may be included in multiple constraints
• The order# column is included in a primary key and
a foreign key constraint

Oracle 11g: SQL


25

Viewing Constraints –
USER_CONSTRAINTS
• Display constraint listing for a specific table

Oracle 11g: SQL


26

Enabling/ Disabling a constraint


• Use DISABLE or ENABLE clause of ALTER
TABLE command

Oracle 11g: SQL


27

Dropping Constraints
• Constraints cannot be modified; they must be dropped
and recreated if needed.
• Actual syntax depends on type of constraint
• PRIMARY KEY – just list the type of constraint, i.e. PRIMARY KEY
• UNIQUE – include the column name
• All others – include the name of the constraint

Oracle 11g: SQL


28

ALTER TABLE…DROP Syntax

Oracle 11g: SQL


29

Drop Constraint Example

Oracle 11g: SQL


30

Drop Constraint Example – Error

Oracle 11g: SQL


26 February 2023 31

Data Manipulation Language (DML)


• INSERT command
• UPDATE command
• DELETE command
• COMMIT command
• ROLLBACK command
32

INSERT Command
• Used to add a row to an existing table
• Can only add one row at a time to a table
• Identify the table in the INSERT INTO clause
• Specify data in the VALUES clause

Oracle 11g: SQL


33

INSERT Command Syntax


• Enclose nonnumeric data in single quotes
• If a column list is not provided, a value
must be assigned to each column in the
table in the same sequence

Oracle 11g: SQL


34

INSERT Command Examples


No Column List

Column List

Oracle 11g: SQL


35

Inserting NULL Value


• Omit column name from the column list of the
INSERT INTO clause
• Substitute data by two single quotation marks
• Use NULL keyword

NULL value input

Oracle 11g: SQL


36

Activating the DEFAULT option


• When including a column list in the INSERT
statement,
• if you ignore the column data, it will use the DEFAULT
option
• Or, you can use the DEFAULT keyword as the value for
the column

Oracle 11g: SQL


37

Inserting Data from an Existing Table

• Substitute subquery for VALUES clause

Subquery

Oracle 11g: SQL


38

Modifying Existing Rows


• Modify rows using UPDATE command
• Use UPDATE command to:
• Add values to an existing row (replace NULL values)
• Change existing values

Oracle 11g: SQL


39

UPDATE Command
• UPDATE clause identifies table
• SET clause identifies column(s) being changed and new
value(s)
• Optional WHERE clause specifies a condition for row(s)
to be changed – if omitted, all rows will be updated!

Oracle 11g: SQL


40

UPDATE Command Syntax

Oracle 11g: SQL


41

UPDATE Command Example

Oracle 11g: SQL


42

Substitution Variables
• Prompts user for value to make dynamic updates from
user input
• Identified by ampersand (&) preceding variable name
• Can be used to create interactive scripts

Oracle 11g: SQL


43

Substitution Variable Example

Oracle 11g: SQL


44

Deleting Rows
• DELETE command removes row(s) from a table

WHERE clause
determines which
row(s) are removed

Oracle 11g: SQL


45

DELETE Command – Omitting


WHERE Clause
• CAUTION - Omitting WHERE clause removes all
rows
• Example below removes all rows from the
acctmanager2 table

Oracle 11g: SQL


46

Transaction Control Statements


• Results of data manipulation language (DML) are not
permanently updated to a table until explicit or implicit
COMMIT occurs
• Transaction control statements can:
• Commit data through COMMIT command
• Undo data changes through ROLLBACK command

Oracle 11g: SQL


47

COMMIT Command
• Explicit COMMIT occurs by executing COMMIT;
• Implicit COMMIT occurs when a DDL command is
executed or user properly exits system
• Permanently updates table(s) and allows other users to
view changes

Oracle 11g: SQL


48

ROLLBACK Command
• Used to “undo” changes that have not been
committed
• Occurs when:
• ROLLBACK; is executed
• System restarts after a crash

• SAVEPOINT marks a specific spot within the


transaction
• Can ROLLBACK to a SAVEPOINT to undo part of
the transaction

Oracle 11g: SQL


49

Transaction Control Example

Oracle 11g: SQL


50

Transaction Control Example (continued)


Only undo DML
actions after
SAVEPOINT ONE.

Oracle 11g: SQL


51

Table Locks
• Prevent simultaneous users from changing same data or
objects
• Two types of table locks:
• Shared – prevents DML operations on a portion of table
• Exclusive – locks the entire table preventing other exclusive or
shared locks

Oracle 11g: SQL


52

LOCK TABLE Command - Shared Lock


• Locks portion of table affected by DML operation
• Implicitly occurs during UPDATE or DELETE operations
• Explicitly occurs through LOCK TABLE command with
SHARE MODE option
• Released when COMMIT (implicit or explicit) or
ROLLBACK occurs

Oracle 11g: SQL


53

LOCK TABLE Command - Exclusive Lock


• Implicitly locks table for DDL operations – CREATE or
ALTER TABLE
• Explicitly locked through LOCK TABLE command with
EXCLUSIVE MODE option
• Released after execution of DDL operation or after user
exits system

Oracle 11g: SQL


54

SELECT…FOR UPDATE Command


• Creates a shared lock on retrieved portion of table using
SELECT
• Prevents one user from changing a row while another
user is selecting rows to be changed
• Lock is released through implicit or explicit COMMIT

Oracle 11g: SQL


55

SELECT…FOR UPDATE Command


Syntax

Oracle 11g: SQL


56

SUMMARY
• A constraint is a rule applied to data being added to a
table. It represents business rules, policies, or
procedures. Data violating the constraint isn’t added to
the table.
• A constraint can be included during table creation as
part of the CREATE TABLE command or added to an
existing table with the ALTER TABLE command.
• A constraint based on composite columns (more than
one column) must be created by using the table-level
approach.
• A NOT NULL constraint can be created only with the
column-level approach.
57

SUMMARY
• A PRIMARY KEY constraint doesn’t allow duplicate or
NULL values in the designated column.
• Only one PRIMARY KEY constraint is allowed in a
table.
• A FOREIGN KEY constraint requires that the column
entry match a referenced column entry in the table or be
NULL.
• A UNIQUE constraint is similar to a PRIMARY KEY
constraint, except it allows storing NULL values in the
specified column.
• A CHECK constraint ensures that data meets a given
condition before it’s added to the table. The condition
can’t reference the SYSDATE function or values stored
58

SUMMARY
• A NOT NULL constraint is a special type of CHECK
constraint. If you’re adding to an existing column, the
ALTER TABLE ... MODIFY command must be used.
• A column can be assigned multiple constraints.
• The data dictionary views USER_CONSTRAINTS and
USER_CONS_COLUMNS enable you to verify existing
constraints.
• A constraint can be disabled or enabled with the ALTER
TABLE command and the DISABLE and ENABLE
keywords.
• A constraint can’t be modified. To change a constraint,
you must first drop it with the DROP command and then
re-create it.
26 February 2023 59

Tasks for this week…..


• Read Chapter 4 – Constraints, and write
down the main points in your notebooks.
• Do Online Quiz #4 – available on Moodle.
• Start working on the Hands-on Practical
Assignment #1

You might also like