0% found this document useful (0 votes)
5 views

CS4416 Lecture 08 - SQL Constraints

The document outlines SQL constraints and triggers, emphasizing their role in ensuring data integrity within databases. It details various types of constraints such as keys, foreign keys, value-based, and tuple-based constraints, along with examples of their implementation. Additionally, it discusses the timing of checks and the use of assertions, highlighting the importance of defining foreign keys before data insertion to avoid violations.

Uploaded by

miriamoamohammed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

CS4416 Lecture 08 - SQL Constraints

The document outlines SQL constraints and triggers, emphasizing their role in ensuring data integrity within databases. It details various types of constraints such as keys, foreign keys, value-based, and tuple-based constraints, along with examples of their implementation. Additionally, it discusses the timing of checks and the use of assertions, highlighting the importance of defining foreign keys before data insertion to avoid violations.

Uploaded by

miriamoamohammed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Slides based on http://infolab.stanford.edu/~ullman/fcdb/aut07/index.

html#lecture

Please note that this lecture is being recorded for academic purposes and will be available on Sulis. Any questions/comments you make during the lecture may be
heard/seen on the recording. The recordings will be retained on Sulis for a period of 13 months. If you have any questions or concerns about this, please contact
[email protected].

Please be advised that you should not copy, modify or distribute recordings of a lecture to which you have access, without first seeking permission to do so.

SQL CONSTRAINTS
CS4416 Lecture 08
Constraints and Triggers
2

 Two methods for ensuring data integrity in a


database (within the database):
 Constraints:a constraint is a relationship among data
elements that the DBMS is required to enforce.
◼ Example: key constraints.
 Triggers: a trigger is a piece of code, only executed
when a specified condition occurs, e.g., insertion of a
tuple. (triggers will be covered in next lecture)
◼ Easier to implement than complex constraints.
Kinds of Constraints
3

 Keys
 Foreign-key, or referential-integrity
 Value-based constraints
 Constrain values of a particular attribute
 Tuple-based constraints
 Relationship among attributes
 Assertions: any SQL Boolean expression
Revision: Declaring Single-Attribute Keys
4

 Place PRIMARY KEY or UNIQUE after the type in


the declaration of the attribute.
 Example:

CREATE TABLE Products (


maker CHAR(1),
model CHAR(4) PRIMARY KEY,
type VARCHAR(8)
);
Revision: Declaring Single-Attribute Keys (2)
5

 Example of two alternative keys:

CREATE TABLE Customers (


customer_id CHAR(10) PRIMARY KEY,
firstname VARCHAR(32),
lastname VARCHAR(32),
city VARCHAR(32),
address VARCHAR(128),
email VARCHAR(128) UNIQUE
);
Revision: Multiattribute Key
6

 We assume that for each model X purchased by customer Y


there is one entry per day in table Sales. Thus:

CREATE TABLE Sales (


customer_id CHAR(10),
model CHAR(4),
quantity INTEGER,
day DATE,
paid REAL,
type_of_payment VARCHAR(32),
PRIMARY KEY(customer_id, model, day)
);
Foreign Keys
7

 Values appearing in attributes of one relation


must appear together in certain attributes of
another relation.
 Example: in

Sales(customer_id, model, quantity, day, paid, type_of_payment),

we might expect that a customer_id value also appears in relation


Customers and a model value also appears in relation Products.
Expressing Foreign Keys
8

 Use keyword REFERENCES, either:


1. After an attribute (for one-attribute keys), or
2. As an element of the schema:
FOREIGN KEY (<list of attributes>)
REFERENCES <relation> (<attributes>)
 Referenced attributes must be declared PRIMARY
KEY or UNIQUE.
Important Note
9

 Define foreign keys BEFORE inserting data in your


tables!
 If you define them after the database has been
populated with data that contradicts them then
the DBMS won’t allow you define the foreign
keys!
Example: With Attribute
10

CREATE TABLE Products (...


model CHAR(4) PRIMARY KEY,
...);
CREATE TABLE Customers (
customer_id CHAR(10) PRIMARY KEY,
...);

CREATE TABLE Sales (


customer_id CHAR(10) REFERENCES Customers(customer_id),
model CHAR(4) REFERENCES Products(model),
quantity INTEGER, ...
PRIMARY KEY(customer_id, model, day)
)
Example: As Schema Element
11

CREATE TABLE Products (...


model CHAR(4) PRIMARY KEY,
...);
CREATE TABLE Customers (
customer_id CHAR(10) PRIMARY KEY,
...);
CREATE TABLE Sales (
customer_id CHAR(10),
model CHAR(4), ...
FOREIGN KEY(customer_id) REFERENCES Customers(customer_id),
FOREIGN KEY(model) REFERENCES Products(model),
PRIMARY KEY(customer_id, model, day)
);
Enforcing Foreign-Key Constraints
12

x y
R S

 If there is a foreign-key constraint from relation S


to relation R, two violations are possible:
1. An insert or update to S introduces values not
found in R.
2. A deletion or update to R causes some tuples of S to
“dangle.”
Actions Taken (1)
13

R model S
model
(Products) (Sales)

 Example: suppose S = Sales, R = Products.


 An insert or update to Sales that introduces a
nonexistent model must be rejected.
 A deletion or update to Products that removes a
model value found in some tuples of Sales can be
handled in three ways (next slide).
Actions Taken (2)
14

R model S
model
(Products) (Sales)

Problem: A deletion or update to Products that


removes a model value found in some tuples of
Sales
 Default : Reject the modification.
 Cascade : Make the same changes in Sales, i.e. either
delete or update tuples referencing that model.
 Set NULL : Change that model to NULL in Sales.
Choosing a Policy
15

 When we declare a foreign key, we may choose


policies SET NULL or CASCADE independently for
deletions and updates.
 Follow the foreign-key declaration by:

ON [UPDATE, DELETE][SET NULL CASCADE]


 Two such clauses may be used.

 Otherwise, the default (reject) is used.

 MySQL Policies:
http://dev.mysql.com/doc/refman/5.7/en/innodb-foreign-key-constraints.html
Example: Setting Policy
16

CREATE TABLE Sales (


customer_id CHAR(10), model CHAR(4),
quantity INTEGER, day DATE,
paid REAL,
type_of_payment VARCHAR(32),
FOREIGN KEY(customer_id)
REFERENCES Customers(customer_id)
ON DELETE CASCADE
ON UPDATE CASCADE,
FOREIGN KEY(model)
REFERENCES Products(model)
ON UPDATE CASCADE,
PRIMARY KEY(customer_id, model, day));
Attribute-Based Checks
17

 Constraints on the value of a particular attribute.


 Add CHECK(<condition>) to the declaration for the
attribute.
 The condition may use the name of the attribute,
but any other relation or attribute name must be
in a subquery.
Example: Attribute-Based Check
18

CREATE TABLE Sales (


customer_id CHAR(10)
CHECK (customer_id IN (SELECT customer_id
FROM Customers)),
model CHAR(4)
CHECK (model IN (SELECT model
FROM Products)),
quantity INTEGER CHECK (quantity > 0),
day DATE CHECK (day > ‘2017-12-31'),
paid REAL,
type_of_payment VARCHAR(32),
PRIMARY KEY(customer_id, model, day)
);
Timing of Checks
19

 Attribute-based checks are performed only when a


value for that attribute is inserted or updated.
 Example: CHECK (day > '2017-12-31')
checks every new day and rejects the modification (for
that tuple) if day is less than or equal to '2017-12-31'.
 Example: CHECK (model IN (select
model from Products)) not checked if a
model is deleted from Products (unlike foreign-keys).
Tuple-Based Checks
20

 CHECK (<condition>) may be added as a


relation-schema element.
 The condition may refer to any attribute of the
relation.
 But other attributes or relations require a subquery.
 Checked on insert or update only.
Example: Tuple-Based Check
21

 Model 1001 can be sold only on or after the 1st of March 2018:

CREATE TABLE Sales (


customer_id CHAR(10)
CHECK (customer_id IN (SELECT customer_id
FROM Customers)),
model CHAR(4)
CHECK (model IN (SELECT model FROM Products)),
quantity INTEGER, day DATE,
paid REAL, type_of_payment VARCHAR(32),
CHECK (model <> '1001' OR day >= ‘2018-03-01'),
PRIMARY KEY(customer_id, model, day)
);
Assertions
22

 These are database-schema elements, like


relations or views.
 Defined by:
CREATE ASSERTION <name>
CHECK (<condition>);
 Condition may refer to any relation or attribute in
the database schema.

 Not supported by MySQL!


Example: Assertion
23

 In Sales, cannot sell more than 100 PCs of a particular


model.

CREATE ASSERTION PCSales100 CHECK (


NOT EXISTS (
SELECT model
FROM Sales
WHERE model IN (SELECT model FROM PCs)
GROUP BY model
HAVING SUM(quantity) > 100)
);
Timing of Assertion Checks
24

 In principle, we must check every assertion after


every modification to any relation of the database.
 A clever system can observe that only certain
changes could cause a given assertion to be
violated.

You might also like