COMP101:
Foundations
of
Information
Systems
Lecture (II)
6: SQL Constraints
Grant
Dick
Department
of
Information
Science
Topics for today
• Quick recap
• CREATE, DROP TABLE (DDL statements)
• INSERT, SELECT (DML statements)
• Integrity
• Constraints:
• Keys
• Checks
1
Quick revision questions (5 min)
• What would be an appropriate (SQL) data type for
each of the following, and why?
• Student ID
• Phone number
• Product price
• Latitude
• Measurement value
• Credit card number
2
Recap: Simple DDL Statements
-- Create a table called Student
CREATE TABLE Student (
Student_ID
VARCHAR(10),
First_Name
VARCHAR(50),
Last_Name
VARCHAR(50)
);
-- Insert a row into the table
INSERT INTO Student (Student_ID, First_Name, Last_Name)
VALUES (‘1121978', ‘Grant', ‘Dick');
-- Retrieve and display the data stored in the Student table
SELECT *
FROM Student;
-- Remove the table entirely
DROP TABLE Student;
3
Structured Query Language (SQL)
• Really a family of related languages for
database creation and manipulation:
• Data Definition Language (DDL)
• Data Manipulation Language (DML)
• Data Control Language (DCL) — not in COMP 101
• “Standard” language for database interaction:
• interactively (as in COMP 101)
• programmatically in application development (as in
INFO
201, INFO 202, COSC 344) — see Lecture 9
4
Key DDL statements
CREATE TABLE|VIEW <name>
( … ); ALTER TABLE|VIEW
<name> …; DROP TABLE|VIEW
<name>;
• Note: the order of these statements
is not arbitrary (use your ERD as a
guide)!
• Cannot CREATE a table until referenced tables exist
• Cannot DROP a table while referencing tables exist
• More details today (DDL for constraints)
5
Key DML statements
• Remember CRUD:
• (C)reate, (R)etrieve, (U)pdate, (D)elete
• Basic operations (as used in COMP
101): Create: INSERT INTO <table> (…)
VALUES (…); Retrieve: SELECT … FROM
… WHERE …;
Update: UPDATE <table> SET … WHERE …;
Delete: DELETE FROM <table> WHERE …;
• See Lectures 15 & 16 for more detail on SELECT
6
Data Integrity
Refers to accuracy and consistency of data
i.e., preventing erroneous data (garbage!) getting to the database
7
Integrity: Why?
“[…] tried to sell
610,000 shares at 1
yen [when it had]
intended to sell 1
share at 610,000 yen
[and the] order was
41 times the number
of J-Com’s
outstanding shares,
but the Tokyo Stock
Exchange processed
the order anyway.”
Source: Factwide
8
Integrity in the database: Why?
• Cannot rely on users to do the right thing:
• They type too fast to notice errors
• They might be inexperienced and not know rules
• They may try to bend the rules “just this once”
• They may experience fatigue
• Laborious to implement in programs that
access the database:
• Might be used by multiple programs (redundancy)
• May be difficult to implement in some languages
• May introduce inconsistency if done per-program
9
Solution: SQL constraints
• As close to “at rest” as possible:
• Serve as last line of defence
• Provide consistent definition of business
rules
• Simplify application development
• BUT: nothing can prevent all errors!
10
Our case study for today
Business rules:
• A student’s mark in an enrolment cannot be less than zero
or
greater than 100 (but it can be missing)
• Semester can only be: SS (Summer School), S1, S2, FY (full
year)
• Absent can only be (Y)es or (N)o and by default is set to (N)o
11
SQL Demonstration
Structurally complete database without constraints
12
Adding constraints
• Two kinds:
• Key constraints (primary or foreign)
• CHECK constraints (supplied value matches specified
criteria)
• General syntax:
• CONSTRAINT <name> <details of constraint>
• <name> (optional) unique name for the constraint
• <details…> defines the constraint (see following slides)
• Defined in either CREATE TABLE or ALTER
TABLE
13
Advice: Wherever
possible, add
constraints to an
empty database with
no data
(the only time this is not possible is when the database is
“live”)
14
Primary and foreign keys
• Primary keys ensure that each
row is retrievable and uniquely
identified
• Columns making up the primary key can never
contain nulls, i.e., must have a value
• Foreign keys provide referential
integrity, i.e., links between rows are
valid and reference existing data
• Columns making up a foreign key may contain
nulls,
15
unless overridden by other constraints
16
Example: adding a primary key
-- Specify primary key of Student table
CREATE TABLE Student (
...
CONSTRAINT PK_Student PRIMARY KEY (Student_ID)
);
-- Specify primary key of Enrolment table
CREATE TABLE Enrolment (
...
CONSTRAINT PK_Enrolment
PRIMARY KEY (Paper_Code, Student_ID, Year,
Semester)
);
17
Example: adding a foreign key
ALTER TABLE Enrolment
ADD CONSTRAINT
FK_Enrolment_Student FOREIGN KEY
(Student_ID)
REFERENCES Student (Student_ID);
Note: line breaks and indentation are not
significant — included here for clarity (and tidiness!
)
18
SQL Demonstration
Adding keys
19
Integrity and business rules
• Basic column integrity:
• Not nullable (i.e., value may not be missing)
• Default value
• Unique value
• Examples:
Absent CHAR(1) DEFAULT 'N'
Student_User_Code UNIQUE NOT
NULL
• More generic integrity:
• Add CHECK constraints to table
20
Check constraints
• Used to check validity of supplied
values Examples:
•A value must be within a specified set of options
•A value must be unique within the table
•A numeric value must be within a given range
•A date value must be within a given time period
21
Examples
-- Mark must be between 0 and 100 (inclusive)
CONSTRAINT Valid_Mark
CHECK (Mark BETWEEN 0 AND 100)
-- Absent must have a value
Absent NOT NULL
-- Semester must be one of SS, S1, S2, FY
CONSTRAINT Valid_Semester
CHECK (Semester IN ('SS', 'S1', 'S2', 'FY'))
22
SQL Demonstration
Adding integrity
23
Constraints and CREATE TABLE
• Better to integrate constraints into table creation
process rather than adding after (clean, concise,
easy to understand)
• Typical when constructing/designing database
• Usually follows an “iterative” process:
1. Define basic table structure (columns and types)
2. Execute and test
3. Drop table
4. Edit table definition with constraints
5. Go to step 2
24
Example: CREATE TABLE
constraints
CREATE TABLE Enrolment
( Paper_Code CHAR(7), CONSTRAINT
Student_ID FK_Enrolment_Student
VARCHAR2(7), Year FOREIGN KEY (Student_ID)
NUMERIC(4), REFERENCES Student
Semester CHAR(2) (Student_ID)
CONSTRAINT Valid_Semester
CHECK (Semester IN ('SS', 'S1', 'S2', 'FY')),
Mark NUMERIC(3)
CONSTRAINT Valid_Mark CHECK (Mark BETWEEN 0
AND 100), Absent CHAR(1) DEFAULT 'N' NOT NULL
CONSTRAINT Valid_Absent CHECK (Absent IN ('Y',
'N')),
CONSTRAINT PK_Enrolment
PRIMARY KEY (Paper_Code, Student_ID, Year,
Semester),
CONSTRAINT FK_Enrolment_Paper
FOREIGN KEY (Paper_Code) REFERENCES Paper
(Paper_Code),
25
• DEFAULT & NOT NULL always inline
out-of-line constraints
inline constraints • preferred for keys
• preferred for CHECK & UNIQUE where possible • CHECK & UNIQUE involving more
than one column always out-of-line
);
26
General CHECK clauses
(these work for text, number, and date columns)
• Relational comparison:
CHECK (A > 0), CHECK (A < 0), CHECK (A >=
42), …
• Only one value supplied across two columns:
(must be out-of-line)
CHECK ((A IS NOT NULL AND B IS
NULL) OR (A IS NULL AND B IS
NOT NULL))
• Value within (inclusive) range:
CHECK (A BETWEEN -10 AND 10)
• Value appears in a specified set:
27
CHECK (A IN ('Larry', 'Moe', 'Curly'))
28
Summary
• SQL is a family of languages for defining
database structure and integrity (DDL) and
data access and manipulation (DML)
• Database integrity checks
• Ensure that data meet minimum quality standards
across all applications and simplify application
design
• However, they cannot prevent all errors from entering the
database (only those that can be logically described)
• SQL is a great language to learn from
examples — use the examples in this lecture as
a template to learn how to define business
rules, keys, etc.
29
Revision exercise/questions
• Write an integrity constraint that ensures that the
points value of a paper is restricted to either 9,
18, or 36 points
• Write an integrity constraint that ensures that
a value entered is within the range –100 to
100
• Describe using an example when you would use the
following constraints:
• UNIQUE
• NOT NULL
• CHECK
• DEFAULT
• PRIMARY KEY
30
• FOREIGN KEY
31
Thanks!
Questions?