Sei sulla pagina 1di 26

License

c 2002-2015 T. Uyar, Ş. Öğüdücü


You are free to:


Database Systems
I Share – copy and redistribute the material in any medium or format
Relational Model I Adapt – remix, transform, and build upon the material

Under the following terms:


H. Turgut Uyar Şule Öğüdücü I Attribution – You must give appropriate credit, provide a link to the license,
and indicate if changes were made.
I NonCommercial – You may not use the material for commercial purposes.
I ShareAlike – If you remix, transform, or build upon the material, you must
2002-2015 distribute your contributions under the same license as the original.
For more information:
https://creativecommons.org/licenses/by-nc-sa/4.0/
Read the full license:
https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode

1 / 104 2 / 104

Topics Relational Model

Relational Model
I by Dr. E. F. Codd, 1970
Introduction
I data is modelled as relations:
Keys
Referential Integrity α ⊆ A × B × C × ...
TutorialD I relations are assigned to relation variables (relvar)
I each element of a relation is a tuple
SQL I each piece of data of an element is an attribute
Data Types
Data Definition I relations can be represented using tables
Data Manipulation I relation → table, tuple → row, attribute → column
Referential Integrity

3 / 104 4 / 104
Relation Example Relation Structure

MOVIE
TITLE YEAR DIRECTOR SCORE VOTES
The Usual Suspects 1995 Bryan Singer 8.7 3502 I relation header: set of attributes of the relation
Suspiria 1977 Dario Argento 7.1 1004 I affected by data definition language statements
Being John Malkovich 1999 Spike Jonze 8.3 13809
... ... ... ... ... I relation body: set of tuples in the relation
I affected by data manipulation language statements
I relation variable: MOVIE
I tuple: (Suspiria, 1977, Dario Argento, 7.1, 1004)
I attribute: YEAR

5 / 104 6 / 104

Relation Predicate Tuple Values

I relation predicate: “meaning” of the relation I each tuple is either True or False according to the predicate

example example: MOVIE relation


I “The movie titled TITLE was released in YEAR. I (Suspiria, 1977, Dario Argento, 1004, 7.1) is True
It was directed by DIRECTOR. I (Suspiria, 1978, Dario Argento, 1004, 7.1) is False
The average of VOTES votes is SCORE.”

7 / 104 8 / 104
Tuple Order Attribute Order

I tuple order is insignificant I attribute order is insignificant

example example
I these relations are equivalent: I these relations are equivalent:

TITLE ... TITLE ...


TITLE YEAR ... YEAR TITLE ...
The Usual Suspects ... Suspiria ...
The Usual Suspects 1995 ... 1995 The Usual Suspects ...
Suspiria ... Being John Malkovich ...
Suspiria 1977 ... 1977 Suspiria ...
Being John Malkovich ... The Usual Suspects ...

9 / 104 10 / 104

Duplicate Tuples Domains

I there can not be duplicate tuples in a relation


I each tuple must be uniquely identifiable
I all values for the same attribute should be selected
example from the same domain
I comparison only makes sense between values
TITLE YEAR DIRECTOR SCORE VOTES
chosen from the same domain
The Usual Suspects 1995 Bryan Singer 8.7 3502
- Suspiria 1977 Dario Argento 7.1 1004 I in practice, data types are used instead
Being John Malkovich 1999 Spike Jonze 8.3 13809
... ... ... ... ...
- Suspiria 1977 Dario Argento 7.1 1004
... ... ... ... ...

11 / 104 12 / 104
Domain Example Attribute Values

I TITLE from the titles domain, YEAR from the years domain, I attribute values must be scalar
DIRECTOR from the directors domain, . . . I no arrays, lists, records, . . .
I if data types are used:
TITLE string, YEAR integer, DIRECTOR string, . . . example: multiple directors

I assigning “Suspiria” to DIRECTOR is valid TITLE ... DIRECTORS ...


in terms of data types but it doesn’t make sense ... ... ... ...
The Matrix ... Andy Wachowski, Lana Wachowski ...
I YEAR and VOTES are integers
... ... ... ...
but it doesn’t make sense to compare them

13 / 104 14 / 104

Null Value Default Value

I a default value can be used instead of null


I value of attribute I tuple does not have I it may not be one of the valid values for the attribute
not known for tuple a value for attribute

example example example

I I I if SCORE values are between 1.0 and 10.0,


director of movie nobody voted for movie,
not known therefore no SCORE the default value can be chosen as 0.0

15 / 104 16 / 104
Keys Candidate Key Examples

I let B be the set of all attributes of the relation,


and let A ⊆ B
I {TITLE} ?
I to be a candidate key, A has to be:
I {TITLE, YEAR} ?
I unique: no two tuples have the same values
I {TITLE, DIRECTOR} ?
for all attributes in A
I {TITLE, YEAR, DIRECTOR} ?
I irreducible: no subset of A is unique

I every relation has at least one candidate key

17 / 104 18 / 104

Surrogate Keys Surrogate Key Example

MOVIE# TITLE YEAR DIRECTOR SCORE VOTES


I if a natural key can not be found
... ... ... ... ... ...
a surrogate key can be defined 6 The Usual Suspects 1995 Bryan Singer ... ...
1512 Suspiria 1977 Dario Argento ... ...
I identity attribute 70 Being John Malkovich 1999 Spike Jonze ... ...
I its value doesn’t matter ... ... ... ... ... ...
I it can be generated by the system
I {MOVIE#} is a candidate key
I {MOVIE#, TITLE} is not a candidate key

19 / 104 20 / 104
Primary Key Primary Key Example

I if more than one candidate key, one is selected as the primary key
I others are alternate keys MOVIE# TITLE YEAR DIRECTOR SCORE VOTES
I names of attributes in the primary key are underlined ... ... ... ... ... ...
6 The Usual Suspects 1995 Bryan Singer ... ...
I any attribute that is part of the primary key 1512 Suspiria 1977 Dario Argento ... ...
can not be empty in any tuple 70 Being John Malkovich 1999 Spike Jonze ... ...
... ... ... ... ... ...
I every relation must have a primary key

21 / 104 22 / 104

Scalarity Example Scalarity Example

I for scalarity, tuples have to be repeated


I how to store actor data?
MOVIE
MOVIE
MOVIE# TITLE ... ACTORS MOVIE# TITLE ... ACTOR
6 The Usual Suspects ... Gabriel Byrne 6 The Usual Suspects ... Gabriel Byrne
... ... ... ... ... ... ... ...
70 Being John Malkovich ... Cameron Diaz, John Malkovich 70 Being John Malkovich ... Cameron Diaz
... ... ... ... 70 Being John Malkovich ... John Malkovich
... ... ... ...

23 / 104 24 / 104
Scalarity Example Scalarity Example
MOVIE
MOVIE MOVIE# TITLE ... DIRECTOR#
MOVIE# TITLE ... 6 The Usual Suspects ... 639
1512 Suspiria ... 2259
6 The Usual Suspects ...
70 Being John Malkovich ... 1485
1512 Suspiria ...
... ... ... ...
70 Being John Malkovich ...
... ... ... PERSON CASTING
PERSON# NAME MOVIE# ACTOR# ORD
ACTOR CASTING 308 Gabriel Byrne 6 308 2
ACTOR# NAME MOVIE# ACTOR# ORD 1485 Spike Jonze 70 282 2
639 Bryan Singer 70 503 14
308 Gabriel Byrne 6 308 2
282 Cameron Diaz ... ... ...
282 Cameron Diaz 70 282 2
2259 Dario Argento
503 John Malkovich 70 503 14
503 John Malkovich
... ... ... ... ...
... ...

25 / 104 26 / 104

Foreign Keys Foreign Key Example

  - 
MOVIE PERSON
DIRECTOR#    NAME
639 
I foreign key: an attribute of a relation MOVIE# TITLE ... PERSON#

2259 
6 The Usual Suspects ... 308 Gabriel Byrne
that is a candidate key of another relation 1512 Suspiria ... PP 1485 Spike Jonze

q 
70 Being John Malkovich ... 1485 PP 639 Bryan Singer

 
... ... ... ... P P 282 Cameron Diaz
2259 Dario Argento
503 John Malkovich
... ...

27 / 104 28 / 104
Foreign Key Examples Referential Integrity

I referential integrity:
MOVIE#  TITLE ... DIRECTOR#    NAME
MOVIE PERSON
  The Usual Suspects ...   -  Gabriel Byrne
PERSON# all values of a foreign key attribute must be present
among the values of the referenced candidate key attribute
1512 Z}Suspiria
6 639 308
Z ... 2259 7
 1485 Spike Jonze
... ...
Z ... ...  ... ...
Z  I if a request would break referential integrity:
Z 
Z
  
Z CASTING  I don’t allow
MOVIE#   ORD
Z 
ACTOR# I reflect the change to affected tuples
6 308 2
70 282 2 I assign null value
... ... ...
I assign default value

29 / 104 30 / 104

Referential Integrity Examples Tutorial D Data Types

MOVIE PERSON
MOVIE# TITLE ... DIRECTOR# PERSON# NAME I INTEGER
... ... ... ... ... ... I RATIONAL
1512 Suspiria ... 2259 2259 Dario Argento I BOOL
... ... ... ... ... ...
I CHAR

I delete (2259, Dario Argento)


I update (2259, Dario Argento) as (2871, Dario Argento)

31 / 104 32 / 104
Type Definition Type Definition Examples

TYPE PERSON# POSSREP


{ VALUE INTEGER };
I defining a new type:
TYPE type_name POSSREP TYPE MOVIE# POSSREP
{ field_name field_type { VALUE INTEGER };
[, ...]
[ CONSTRAINT condition ] }; TYPE YEAR POSSREP
{ VALUE INTEGER };
I deleting a type:
DROP TYPE type_name; TYPE SCORE POSSREP
{ VALUE RATIONAL
CONSTRAINT (VALUE >= 1.0)
AND (VALUE <= 10.0) };

33 / 104 34 / 104

Type Operations Type Operations

I generating a value for a type: I getting the value of a field: THE_ operators
type_name(base_value [, ...]) THE_field_name(variable_name)

example example
I generating a SCORE value: I getting the VALUE field of a SCORE variable:
SCORE(8.7) THE_VALUE(SCORE)

35 / 104 36 / 104
Type Operations Relation Definition

I type casting: CAST_AS_ operators


I defining a new relation:
CAST_AS_target_type(value)
RELATION
{ attribute_name attribute_type
example
[, ...] }
I casting an integer VOTES value to a RATIONAL: KEY { attribute_name [, ...] }

CAST_AS_RATIONAL(VOTES)

37 / 104 38 / 104

Relation Definition Example Relation Variables

RELATION I defining a new relation variable


{ MOVIE# MOVIE#,
VAR relvar_name BASE RELATION
TITLE CHAR,
{ ... }
YEAR YEAR,
KEY { ... };
DIRECTOR# PERSON#,
SCORE SCORE, I deleting a relation variable:
VOTES INTEGER }
DROP VAR relvar_name;
KEY { MOVIE# }

39 / 104 40 / 104
Relation Variable Examples Relation Variable Examples

VAR PERSON BASE RELATION


VAR MOVIE BASE RELATION { PERSON# PERSON#,
{ MOVIE# MOVIE#, NAME CHAR }
TITLE CHAR, KEY { PERSON# };
YEAR YEAR,
DIRECTOR# PERSON#, VAR CASTING BASE RELATION
SCORE SCORE, { MOVIE# MOVIE#,
VOTES INTEGER } ACTOR# PERSON#,
KEY { MOVIE# }; ORD INTEGER }
KEY { MOVIE#, ACTOR# };

41 / 104 42 / 104

Tuple Generation Tuple Generation Examples

TUPLE
{ MOVIE# MOVIE#(6),
I
TITLE "The Usual Suspects",
generating a tuple:
YEAR YEAR(1995),
TUPLE DIRECTOR# PERSON#(639),
{ attribute_name attribute_value SCORE SCORE(8.7),
[, ...] } VOTES 35027 }

TUPLE
{ PERSON# PERSON#(639),
NAME "Bryan Singer" }

43 / 104 44 / 104
Relation Generation Relation Assignment Example

I generating a relation: MOVIE := RELATION


{ TUPLE
RELATION
{ MOVIE# MOVIE#(6), TITLE "The Usual Suspects",
{ TUPLE
YEAR YEAR(1995), DIRECTOR# PERSON#(639),
{ ... }
SCORE SCORE(8.7), VOTES 35027 },
[, ...] }
TUPLE
I assigning a relation to a relation variable: { MOVIE# MOVIE#(70), TITLE "Being John Malkovich",
YEAR YEAR(1999), DIRECTOR# PERSON#(1485),
relvar_name := RELATION { ... };
SCORE SCORE(8.3), VOTES 13809 } };

45 / 104 46 / 104

Tuple Insertion Tuple Insertion Example

INSERT MOVIE RELATION


I inserting tuples: { TUPLE
{ MOVIE# MOVIE#(1),
INSERT relvar_name RELATION TITLE "Star Wars",
{ TUPLE { ... } YEAR YEAR(1977),
[, ...] }; DIRECTOR# PERSON#(360),
SCORE SCORE(8.8),
VOTES 53567 } };

47 / 104 48 / 104
Tuple Deletion Tuple Deletion Example

I deleting tuples: I delete movies with scores less than 3.0 and votes more than 4
DELETE relvar_name DELETE MOVIE
[ WHERE condition ]; WHERE ((SCORE < SCORE(3.0))
AND (VOTES > 4));
I if no condition is specified, all tuples will be deleted

49 / 104 50 / 104

Tuple Update Tuple Update Example

I register a new vote (9) for the movie ”Suspiria”


UPDATE MOVIE
I updating tuples:
WHERE (TITLE = "Suspiria") (
UPDATE relvar_name SCORE := SCORE(
[ WHERE condition ] (THE_VALUE(SCORE)
( attribute_name := attribute_value * CAST_AS_RATIONAL(VOTES)
[, ...] ); + CAST_AS_RATIONAL(9))
/ CAST_AS_RATIONAL(VOTES + 1)
I if no condition is specified, all tuples will be updated ),
VOTES := VOTES + 1
);

51 / 104 52 / 104
Attribute Renaming Foreign Key Definition

I renaming an attribute: I defining a foreign key:


RENAME { attribute_name AS new_name }
CONSTRAINT constraint_name
referencing_relvar_name
{ attribute_name }
example
<= referenced_relvar_name
I renaming the DIRECTOR# attribute: { attribute_name };

RENAME { DIRECTOR# AS PERSON# } I attribute names have to match (rename if necessary)

53 / 104 54 / 104

Foreign Key Examples Foreign Key Examples

CONSTRAINT CASTING_FKEY_MOVIE
CONSTRAINT MOVIE_FKEY_DIRECTOR CASTING { MOVIE# } <= MOVIE { MOVIE# };
MOVIE { DIRECTOR# }
RENAME { DIRECTOR# AS PERSON# } CONSTRAINT CASTING_FKEY_ACTOR
<= PERSON { PERSON# }; CASTING { ACTOR# }
RENAME { ACTOR# AS PERSON# }
<= PERSON { PERSON# };

55 / 104 56 / 104
Data Types String Data Types

I INTEGER
I CHARACTER [ VARYING ] (n)
I NUMERIC (precision, scale)
I precision: total number of digits
I CHARACTER (n): if the string is shorter than n characters
I scale: number of digits after the decimal point it will be padded with spaces
I same as: DECIMAL (precision, scale)
I CHAR (n) instead of CHARACTER (n)
I FLOAT I VARCHAR (n) instead of CHARACTER VARYING (n)

I BOOLEAN

57 / 104 58 / 104

Date / Time Data Types Large Object Data Types

I DATE
I value example: 2005-09-26
I arbitrary length objects

I I binary: BINARY LARGE OBJECT (n)


TIME
I value example: 11:59:22.078717 I BLOB

I TIMESTAMP I text: CHARACTER LARGE OBJECT (n)


I value example: 2005-09-26 11:59:22.078717 I CLOB

I INTERVAL I can not be used in queries


I value example: 3 days

59 / 104 60 / 104
Domain Creation Domain Example

I creating a domain:
CREATE DOMAIN domain_name [ AS ] base_type I a domain for valid SCORE values:
[ DEFAULT default_value ]
CREATE DOMAIN SCORES AS FLOAT
[ { CHECK ( condition ) } [, ...] ]
CHECK ((VALUE >= 1.0) AND (VALUE <= 10.0))
I deleting domains:
DROP DOMAIN domain_name [, ...]

61 / 104 62 / 104

Table Creation Table Creation Example

I using a domain:
I creating a table:
CREATE TABLE table_name ( CREATE TABLE MOVIE ( CREATE TABLE MOVIE (
{ column_name data_type } ID INTEGER, ID INTEGER,
[, ... ] TITLE VARCHAR(80), TITLE VARCHAR(80),
) YR NUMERIC(4), YR NUMERIC(4),
DIRECTORID INTEGER, DIRECTORID INTEGER,
I deleting tables: SCORE FLOAT, SCORE SCORES,
DROP TABLE table_name [, ... ] VOTES INTEGER VOTES INTEGER
) )

63 / 104 64 / 104
Null and Default Values Table Creation Example

I defining nullable columns and default values:


CREATE TABLE MOVIE (
CREATE TABLE table_name (
ID INTEGER,
{ column_name data_type
TITLE VARCHAR(80) NOT NULL,
[ NULL | NOT NULL ]
YR NUMERIC(4),
[ DEFAULT default_value ] }
DIRECTORID INTEGER,
[, ... ]
SCORE FLOAT,
)
VOTES INTEGER DEFAULT 0
I NULL: the column is allowed to be empty (default) )
I NOT NULL: the column is not allowed to be empty

65 / 104 66 / 104

Value Constraints Value Constraint Example

I defining constraints on values: I SCORE values must be between 1.0 and 10.0

CREATE TABLE table_name ( CREATE TABLE MOVIE (


{ column_name data_type ID INTEGER,
[ NULL | NOT NULL ] ...,
[ DEFAULT default_value ] } SCORE FLOAT,
[ { CHECK ( condition ) } VOTES INTEGER DEFAULT 0,
[, ...] ] CHECK ((SCORE >= 1.0) AND (SCORE <= 10.0))
) )

67 / 104 68 / 104
Primary Keys Primary Key Example

I defining primary keys: CREATE TABLE MOVIE (


ID INTEGER,
CREATE TABLE table_name (
TITLE VARCHAR(80) NOT NULL,
{ column_name data_type
YR NUMERIC(4),
[ NULL | NOT NULL ]
DIRECTORID INTEGER,
[ DEFAULT default_value ] }
SCORE FLOAT,
[, ... ]
VOTES INTEGER DEFAULT 0,
[ PRIMARY KEY ( column_name [, ...] ) ]
PRIMARY KEY (ID)
)
)

69 / 104 70 / 104

Primary Keys Automatically Incremented Values

I if the primary key consists of a single column,


it can be specified in column definition: I no standard on defining automatically incremented values
column_name data_type PRIMARY KEY
I PostgreSQL: SERIAL data type
ID SERIAL PRIMARY KEY
example
I MySQL: AUTO_INCREMENT property
CREATE TABLE MOVIE ( ID INTEGER PRIMARY KEY AUTO_INCREMENT
ID INTEGER PRIMARY KEY,
I SQLite: AUTOINCREMENT property
...
VOTES INTEGER DEFAULT 0 ID INTEGER PRIMARY KEY AUTOINCREMENT
)

71 / 104 72 / 104
Uniqueness Uniqueness Example

I titles and (director, year) pairs are unique:


I defining unique columns: CREATE TABLE MOVIE (
CREATE TABLE table_name ( ID SERIAL PRIMARY KEY,
... TITLE VARCHAR(80) NOT NULL,
[ { UNIQUE ( column_name [, ...] ) } YR NUMERIC(4),
[, ...] ] DIRECTORID INTEGER,
... SCORE FLOAT,
) VOTES INTEGER DEFAULT 0,
UNIQUE (TITLE),
I null values are ignored UNIQUE (DIRECTORID, YR)
)

73 / 104 74 / 104

Uniqueness Indexes

I if the uniqueness constraint consists of a single column, I creating an index


it can be specified in the column definition:
CREATE [ UNIQUE ] INDEX index_name
column_name data_type UNIQUE ON table_name (column_name [, ...])

I speeds up queries
example: person names are unique
I slows down inserts and updates
CREATE TABLE PERSON (
ID SERIAL PRIMARY KEY, example: create a year index on movies
NAME VARCHAR(40) UNIQUE NOT NULL
) CREATE INDEX MOVIE_YEAR ON MOVIE (YR)

75 / 104 76 / 104
Renaming Tables Adding Columns

I adding columns to an existing table:


I renaming a table:
ALTER TABLE table_name
ALTER TABLE table_name ADD [ COLUMN ] column_name data_type
RENAME TO new_name [ NULL | NOT NULL ]
[ DEFAULT default_value ]

example
ALTER TABLE MOVIE
example
RENAME TO FILM ALTER TABLE MOVIE
ADD COLUMN RUNTIME INTEGER

77 / 104 78 / 104

Deleting Columns Renaming Columns

I deleting columns from a table: I renaming a column:


ALTER TABLE table_name ALTER TABLE table_name
DROP [ COLUMN ] column_name RENAME [ COLUMN ] column_name TO new_name

example example
ALTER TABLE MOVIE ALTER TABLE MOVIE
DROP COLUMN RUNTIME RENAME COLUMN TITLE TO NAME

79 / 104 80 / 104
Column Defaults Adding Constraints

I setting a default value for a column: I adding a new constraint to a table:


ALTER TABLE table_name ALTER TABLE table_name
ALTER [ COLUMN ] column_name ADD [ CONSTRAINT constraint_name ]
SET DEFAULT default_value constraint_definition

I removing the default value from a column: I removing a constraint from a table:
ALTER TABLE table_name ALTER TABLE table_name
ALTER [ COLUMN ] column_name DROP [ CONSTRAINT ] constraint_name
DROP DEFAULT
I when adding constraints, what happens with existing tuples?

81 / 104 82 / 104

Constraint Addition Example Row Insertion

I YR values can not be less than 1887 I inserting a row to a table:


ALTER TABLE MOVIE INSERT INTO table_name
ADD CONSTRAINT MINIMUM_YEAR [ ( column_name [, ...] ) ]
CHECK (YR >= 1887) VALUES ( column_value [, ...] )

I order of values must match order of columns


I drop the minimum year constraint
I if column names are omitted, values must be in order of definition
ALTER TABLE MOVIE I omitted columns will take their default values
DROP CONSTRAINT MINIMUM_YEAR
I automatically generated columns are usually omitted

83 / 104 84 / 104
Row Insertion Example Row Insertion Example

INSERT INTO MOVIE VALUES (


6, INSERT INTO MOVIE (YR, TITLE) VALUES (
’The Usual Suspects’, 1995,
1995, ’The Usual Suspects’
639, )
8.7,
I value for ID will be automatically generated
35027
)

85 / 104 86 / 104

Row Deletion Row Deletion Example

I deleting rows: I delete movies with scores less than 3.0 and votes more than 4:
DELETE FROM table_name
DELETE FROM MOVIE
[ WHERE condition ]
WHERE ((SCORE < 3.0) AND (VOTES > 4))
I if no condition is specified, all rows will be deleted

87 / 104 88 / 104
Row Update Row Update Example

I updating rows: I register a new vote (9) for the movie ”Suspiria”
UPDATE table_name UPDATE MOVIE
SET { column_name = column_value } [, ...] SET SCORE = (SCORE * VOTES + 9)
[ WHERE condition ] / (VOTES + 1),
VOTES = VOTES + 1
I if no condition is specified, all rows will be updated
WHERE (TITLE = ’Suspiria’)
I order of column assignments is insignificant

89 / 104 90 / 104

Foreign Keys Foreign Key Example

I defining foreign keys: CREATE TABLE MOVIE (


CREATE TABLE table_name ( ID SERIAL PRIMARY KEY,
... TITLE VARCHAR(80) NOT NULL,
[ { FOREIGN KEY ( column_name [, ...] ) YR NUMERIC(4),
REFERENCES table_name DIRECTORID INTEGER,
[ ( column_name [, ...] ) ] } SCORE FLOAT,
[, ...] ] VOTES INTEGER DEFAULT 0,
... FOREIGN KEY DIRECTORID REFERENCES PERSON (ID)
) )

91 / 104 92 / 104
Foreign Keys Foreign Keys

I if the foreign key consists of only one column,


it can be specified in the column definition: I if the foreign key refers to the primary key,
column_name data_type the referred column can be omitted
REFERENCES table_name [ ( column_name ) ]
example
example CREATE TABLE MOVIE (
ID SERIAL PRIMARY KEY,
CREATE TABLE MOVIE ( ...
ID SERIAL PRIMARY KEY, DIRECTORID INTEGER REFERENCES PERSON,
... ...
DIRECTORID INTEGER REFERENCES PERSON (ID), )
...
)

93 / 104 94 / 104

Integrity Violation Options Foreign Keys

I integrity violation options:

I
CREATE TABLE table_name (
what to do if referential integrity will be broken?
...
I don’t allow if used: RESTRICT, NO_ACTION [ { FOREIGN KEY ( column_name [, ...] )
I reflect the change to affected tuples: CASCADE REFERENCES table_name
[ ( column_name [, ...] ) ]
I assign null value: SET NULL
[ ON DELETE option ]
I assign default value: SET DEFAULT [ ON UPDATE option ] } [, ...] ]
...
)

95 / 104 96 / 104
Foreign Key Example Referential Integrity Example

CREATE TABLE MOVIE (


ID SERIAL PRIMARY KEY, MOVIE PERSON
ID TITLE ... DIRECTORID
... ID NAME
6 The Usual Suspects ... 639
DIRECTORID INTEGER, 70 Being John Malkovich ... 1485
308
1485
Gabriel Byrne
Spike Jonze
107 Batman & Robin ... 105
...,
FOREIGN KEY DIRECTORID
I MOVIE.DIRECTORID: ON DELETE RESTRICT
REFERENCES PERSON (ID)
ON DELETE RESTRICT I delete Spike Jonze from PERSON: not allowed
ON UPDATE CASCADE I delete Gabriel Byrne from PERSON: allowed
)

97 / 104 98 / 104

Referential Integrity Example Referential Integrity Example

MOVIE PERSON CASTING MOVIE PERSON CASTING


ID TITLE DIRECTORID ID NAME ID TITLE DIRECTORID ID NAME
MOVIEID ACTORID ORD MOVIEID ACTORID ORD
6 The Usual Suspects 639 308 Gabriel Byrne 6 The Usual Suspects 639 308 Gabriel Byrne
6 308 2 6 308 2
70 Being John Malkovich 1485 1485 Spike Jonze 70 Being John Malkovich 1485 1485 Spike Jonze
70 282 2 70 282 2
107 Batman & Robin 105 107 Batman & Robin 105
112 1485 4 112 1485 4
112 Three Kings 1070 112 Three Kings 1070

I MOVIE.DIRECTORID: ON DELETE CASCADE I MOVIE.DIRECTORID: ON DELETE RESTRICT


I CASTING.MOVIEID: ON DELETE CASCADE I CASTING.MOVIEID: ON DELETE CASCADE
I CASTING.ACTORID: ON DELETE CASCADE I CASTING.ACTORID: ON DELETE CASCADE
I delete Spike Jonze from PERSON: which rows get deleted? I delete Spike Jonze from PERSON: which rows get deleted?

99 / 104 100 / 104


Example Database Example Database

CREATE TABLE MOVIE (


ID SERIAL PRIMARY KEY,
CREATE TABLE PERSON (
TITLE VARCHAR(80) NOT NULL,
ID SERIAL PRIMARY KEY,
YR NUMERIC(4),
NAME VARCHAR(40) UNIQUE NOT NULL
DIRECTORID INTEGER REFERENCES PERSON (ID)
)
SCORE FLOAT,
VOTES INTEGER DEFAULT 0
)

101 / 104 102 / 104

Example Database References

Required Reading: Date


CREATE TABLE CASTING ( I Chapter 3: An Introduction to Relational Databases
MOVIEID INTEGER REFERENCES MOVIE (ID), I 3.2. An Informal Look at the Relational Model
ACTORID INTEGER REFERENCES PERSON (ID), I 3.3. Relations and Relvars
ORD INTEGER,
I Chapter 6: Relations
PRIMARY KEY (MOVIEID, ACTORID)
I Chapter 9: Integrity
)
I 9.10. Keys
I 9.12. SQL Facilities

103 / 104 104 / 104

Potrebbero piacerti anche