You are on page 1of 66

OBJECT-ORIENTED & OBJECT-

RELATIONAL DATABASES
CS561-SPRING 2012
W P I , M O H A M E D E L TA B A K H 1
Object Oriented Databases

History of Databases
HISTORY OF DATABASES
! Back to the Beginning
file
! store data after process created it has ceased to
systems
exist
(1950s)
hierarchical/ ! concurrency
! recovery
network
! fast access
(1960s) ! complex structures
! more reliability
relational ! less redundancy
(1970-80s) ! more flexibility
! multiple views
! better simulation
! more (and complex) data types
! more relationships (e.g. aggregation,
ODBMS specialisation)
! single language for database AND
(1990s) programming
! better versioning
! no 'reconstruction' of objects
! other OO advantages (reuse, inheritance etc.) 2
STONEBRAKER’S
Stonebraker’sAPPLICATION MATRIX
Application Matrix

No Query Query

Complex Data OODBMS ORDBMS

Simple Data File System RDBMS

Thesis: Most applications will move to


the upper right.
3
Introduction to Database Systems 2
MOTIVATION
•  Relational model (70’s):
•  Clean and simple.
•  Great for administrative and transactional data.
•  Not as good for other kinds of complex data (e.g.,
multimedia, networks, CAD).

•  Object-Oriented models (80’s):


•  Complicated, but some influential ideas from Object
Oriented
•  Complex data types.

•  Idea: Build DBMS based on OO model.


Programming languages have evolved from Procedural to
Object Oriented. So why not DBMSs ???
4
RELATIONAL MODEL

•  Relations are the key concept, everything else is around


relations

•  Primitive data types, e.g., strings, integer, date, etc.

•  Great normalization, query optimization, and theory

•  What is missing??
•  Handling of complex objects
•  Handling of complex data types
•  Code is not coupled with data
•  No inherence, encapsulation, etc.

5
! Back to the Beginning

Object Oriented Databases (ODBMS) store data together with the appropriate methods for
RELATIONAL MODEL OF A ‘CAT’
accessing it i.e. encapsulation.

Relational databases " hammer the world flat" by normalisation.

Relational database of a cat:

At query time, try to put


things together as you
want !!!!

Object-oriented database of a cat:

6
OBJECT ORIENTED MODEL OF A ‘CAT’
Applications
! Back to the Beginning
Object-oriented database of a cat:
Object Oriented Databases The first areas where ODBMS were widely used were:
! CASE : Computer aided software engineering

! CAD : Computer aided design

! CAM : Computer aided manufacture

Increasingly now used in:


! telecommunications

! healthcare

! finance

! multimedia

!(2 oftext/document/quality management


This enables:
http://www.dis.port.ac.uk/~chandler/OOLectures/database/database.htm 14) [10/13/2002 11:48:18 AM]

! complex data types to be stored (e.g. CAD These are the 'next-generation applications" where traditional IT
applications)
example, it has been estimated that up to 90% of the data held in
large amount of data is not 'record oriented'.
7
TWO APPROACHES

•  Object-Oriented Model (OODBMS)


•  Pure OO concepts

•  Object-Relational Model (ORDBMS)


•  Extended relational model with OO concepts

8
DATABASE DESIGN PROCESS
Application Domain
or Universe of Discourse

using ER model or UML

Data Modelling

Conceptual Model

using Data Model of the


target DBMS

Logical Database Design

Logical Model
DBMS specific
resource-based
optimization

Physical Database Design

Physical Model 9
LOGICAL & PHYSICAL LAYERS

Relational Normalization & SQL


ER diagram RDBMS
database design Physical design table definitions
Mapping onto
Relations
(no operations)

UML class Mapping onto Object-Relational Extended-SQL


Normalization &
Relations and Object
Physical design ORDBMS
diagram types database design table definitions

Mapping directly
onto ODL classes

Object-Oriented
database schema Optimization OODBMS
in ODL

10
EXAMPLE OF UML CLASSES

Person Class Name

name: {firstName: string,


middleName: string, Attributes
lastName: string}
address: string
birthDate: date

age(): Integer
Operations
changeAddress(newAdd: string)

p:Person A Person object

name: {Norman, William, Preston}


address: Stockport
birthDate: 11-JUN-70

11
FIRST APPROACH: OBJECT-ORIENTED
MODEL
•  Relations are not the central concept, classes and objects are
the main concept

•  Object-Oriented DBMS(OODBMS) are DBMS based on an Object-


Oriented Data Model inspired by OO programming languages

•  Main Features:
•  Powerful type system
•  Classes
•  Object Identity
•  Inheritance

•  OODBMS are capable of storing complex objects, I.e., objects


that are composed of other objects, and/or multi-valued
attributes.
12
FEATURE 1: POWERFUL TYPE SYSTEM

•  Primitive types
•  Integer, string, date, Boolean, float, etc.

•  Structure type
•  Attribute can be a record with a schema
Struct {integer x, string y}
•  Collection type
•  Attribute can be a Set, Bag, List, Array of other types

•  Reference type
•  Attribute can be a Pointer to another object

13
FEATURE 2: CLASSES

•  A ‘class’ is in replacement of ‘relation’

•  Same concept as in OO programming languages


•  All objects belonging to a same class share the same
properties and behavior

•  An ‘object’ can be thought of as ‘tuple’ (but richer


content)

•  Classes encapsulate data + methods + relationships


•  Unlike relations that contain data only

•  In OODBMSs objects are persistency (unlike OO


programming languages)

14
FEATURE 3: OBJECT IDENTITY

•  OID is a unique identity of each object regardless of


its content
•  Even if all attributes are the same, still objects have different
OIDs

•  Easier for references

•  An object is made of two things:


•  State: attributes (name, address, birthDate of a person)
•  Behaviour: operations (age of a person is computed from
birthDate and current date)

15
FEATURE 4: INHERITANCE

•  A class can be defined in terms of Person

another one. name: {firstName: string,


middleName: string,
lastName: string}
address: string
birthDate: date
•  Person is super-class and Student age(): Integer

is sub-class.
changeAddress(newAdd: string)

•  Student class inherits attributes


Student
and operations of Person.
regNum: string {PK}
major: string

register(C: Course): boolean

16
STANDARDS FOR OBJECT-ORIENTED
MODEL
•  ODMG: Object Data Management Group (1991)
•  provide a standard where previously there was none
•  support portability between products
•  standardize model, querying and programming issues

•  Language of specifying the structure of object


database
•  ODL: Object Definition Language
•  OQL: Object Query Language

•  ODL is somehow similar to DDL (Data Definition


Language) in SQL

17
Overview of ODL & OQL

18
Figure 4.2: An ODL declaration of the class Movie

The first attribute, on line (2), is named t i t l e . Its type is string-a


2. INTRODUCTION TO ODL 137

nd length4.2: declared
ODL: CLASSES & ATTRIBUTES
haracter string of unknown length. U'e expect the value of the t i t l e attribute
any Movie object to be the name of the movie. The next two attributes, year
xample In Fig. on 4.2
linesis (3)
an and
ODL(4), declaration
have integerof the
typeclass
andofrepresent
movies. the
It
not
ar ina which
complete the declaration;
movie was made we shall
and add more toin itminutes,
its length later. Line (1) declarw
respectively. On
ovie
ne (5)tois be a class.
another Following
attribute line (1)which
f ilmType, are the
tellsdeclarations
whether theofmovie
four attributes
was filmed
at all Movie objects will have.
color or black-and-white. Its type is an enumeration, and the name of the
numeration is Film. Values of enumeration attributes Keyword
are chosenattribute
from a list
le'terals,
1) color
c l a s s and
Movie blackAndWhite
{ in this example.
An2)object in a t t r i b u t e s t r i n g t i t l ehave
the class Movie as we ; defined it so far can be thought of
a record
3) or atuple
t t r i bwith
u t e four g e r year; one for each of the four attributes.
i n t ecomponents,
4) a t t r i b u t e i n t e g e r length;
5) a t t("Gone
r i b u t e With
enum tFilm Ccolor,blackAndMite)
h e Wind", 1939, 231, color) filmType;
a Movie object. 0

xample 4.3Figure 4.2: An 4.2,


: In Example
Two
ODLalldeclaration classes
the attributes with
of thehave their
classatomic attributes
Movie types. Here is
example with a nonatomic type. We can define the class S t a r by
The first attribute, on line (2), is named t i t l e . Its type is string-a
1) string
aracter t a r C length. U'e expect the value of the t i t l e attribute
c l a s sof Sunknown
any2)Movie object
a t t r i to
b ubet ethe
s t rname of the movie. The next two attributes, year
i n g name;
d length
3) declared
a t t r i b on S t r (3)
u t elines u c tand
Addr (4), have integer type and represent the
ar in which the movie { s t r iwas
n g smade
t r e e and
t , sits
t r ilength
n g c i tin
y )minutes,
address; Attribute
respectively. On as a structure
e (5) is another attribute f ilmType, which tells whether the movie was filmed
color or black-and-white. Its type is an enumeration, and the name of the
umeration
ne is Film.
(2) specifies Values of name
an attribute enumeration
(of the attributes
star) that are is achosen
string.from a list
Line (3)
ecifies another
le'terals, color attribute address. This
and blackAndWhite in this attribute
example. has a type that is a record
An object
ucture. Thein name
the class Movie
of this as we have
structure defined
is Addr, andit the
so far canconsists
type be thought of
of two 19
a record or tuple with four components, one for each of the four attributes.
D
; 2.
o r , b l a c k ~ n d W h i t efilmType; ~
Note, t
tars ODL:
r : : s t a r r e d I n ; CHAPTER 4. OTHER DATA MODELS
RELATIONSHIPS 4.2. INTRODUCTION t o incl
TO
instanc 3.OD
dBy
n g1) cc il ats syMovie
) address; 1. If we have a value
many-manyo r
C class C the type of the rela
dio::owns; 4. b
starredIn
2) attribute s t r i n g t i t l e ; could
3) attribute integer year;
to be e
ng city) address;
ovie::stars;
4) a t t r i b u t e integer length;
5)
6)
attribute enum F i l m {color,black~ndWhite~
relationship Set<Star> s t a r s
filmType;
2. If the relationship is many
Keyword relationship
tionship in C is just D,wh
Note,
3. If the relationship is many
Exam
are reversed in t(2)
oabove.
inc
inverse Star::starredIn;
Keyword set
starredIn
7)

n g c 1;
relationship Studio ownedBy

i t y ) address;
inverse Studio::owns; and
instan
4. If the relationship St
is one-o
D, and in D it value
4.2 an
is just C.
starredIn Set: set of unsorted unique could
Since
E/R modele
vie::stars;
8) c l a s s Star C Note, that as in the
s;
vie::stars;
9) a t t r i b u t e s t r i n g name;
objects to be
to include the case where for so
owns10) a t t r i b u t e Struct Addr instance, a many-one many
relationshr
( s t r i n g s t r e e t , s t r i n g c i t y ) address; value of the relationship in som
ovie::ownedBy;
11) relationship Set<Movie> starredIn Bag: set of unsorted objects
could be associated E xany
with Stu
asem
to be empty for someand D objectsS
with possible duplication and (1
inverse Movie::stars;
3;
Example 4.6 : In Fig. 4.24.3 wean
ha
and Studio. The first
structu
two of th
12) c l a s s Studio i
; 13) List: set of sorted list Since
attribute s t r i n g name; 4.2 and 4.3. ?Ve also There
discussed
many
Since each of their types uses
sowns
14)
and
15)
their
r
attribute s t r i n g address;
e l a t i o
relationships
n s h i p Set<Movie> owns list typesStar
many relationship between
Array: set of sorted Sti
vie::ownedBy; Studio objects have attribute
1;
inverse Movie::ownedBy;
referenced byand index(14). Notice that and Intyp(l
the
structure as was used struct
20for the
type of
There is nothing wrong with us
ODL: RELATIONSHIPS & INVERSE
RELATIONSHIPS
CHAPTER 4. OTHER DATA MODELS 4.2. INTRODUCTION TO OD

1. If we have a many-many r
1) c l a s s Movie C class C the type of the rela
2) attribute s t r i n g t i t l e ;
3) attribute integer year;
4) a t t r i b u t e integer length; 2. If the relationship is many
5) attribute enum F i l m {color,black~ndWhite~ filmType; tionship in C is just D,wh
6) relationship Set<Star> s t a r s
3. If the relationship is many
inverse Star::starredIn;
7) relationship Studio ownedBy
Keyword inverse
are reversed in (2) above.
inverse Studio::owns; 4. If the relationship is one-o
1; D, and in D it is just C.
8) c l a s s Star C Note, that as in the E/R model
9) a t t r i b u t e s t r i n g name; to include the case where for so
10) a t t r i b u t e Struct Addr instance, a many-one relationsh
( s t r i n g s t r e e t , s t r i n g c i t y ) address; value of the relationship in som
11) relationship Set<Movie> starredIn could be associated with any se
inverse Movie::stars; to be empty for some D objects
3;
Example 4.6 : In Fig. 4.3 we ha
and Studio. The first two of th
12) c l a s s Studio i Inverse of4.3. ?Ve also discussed
4.2 and
13) attribute s t r i n g name;
14) attribute s t r i n g address; each other
Since each of their types uses
15) r e l a t i o n s h i p Set<Movie> owns many relationship between Star
inverse Movie::ownedBy; Studio objects have attribute
1; and (14). Notice that the typ
structure as was used21for the
There is nothing wrong with us
ODL: MULTIPLICITY OF RELATIONSHIPS
CHAPTER 4. OTHER DATA MODELS 4.2. INTRODUCTION TO OD

1. If we have a many-many r
1) c l a s s Movie C class C the type of the rela
2) attribute s t r i n g t i t l e ;
3) attribute integer year; Based on the use of collection
4) a t t r i b u t e integer length; types (set, bag,
2. If theetc.)
relationship is many
5) attribute enum F i l m {color,black~ndWhite~ filmType; tionship in C is just D,wh
6) relationship Set<Star> s t a r s
3. If the relationship is many
inverse Star::starredIn;
are reversed in (2) above.
7) relationship Studio ownedBy
inverse Studio::owns; Many-to-Many relationship
4. If the relationship is one-o
1; D, and in D it is just C.
8) c l a s s Star C Note, that as in the E/R model
9) a t t r i b u t e s t r i n g name; to include the case where for so
10) a t t r i b u t e Struct Addr One-to-Many
instance,relationship
a many-one relationsh
( s t r i n g s t r e e t , s t r i n g c i t y ) address; value of the relationship in som
11) relationship Set<Movie> starredIn could be associated with any se
inverse Movie::stars; to be empty for some D objects
3; What about multiway
Example 4.6 : In Fig. 4.3 we ha
12) c l a s s Studio i relationships???
and Studio. The first two of th
13) attribute s t r i n g name; 4.2 and 4.3. ?Ve also discussed
14) attribute s t r i n g address; --Not supportedSince each of their types uses
many relationship between Star
15) r e l a t i o n s h i p Set<Movie> owns --Need to convertStudio
a multiway toattribute
objects have
inverse Movie::ownedBy;
multiple binary and
relationships
(14). Notice that the typ
1;
22for the
structure as was used
There is nothing wrong with us
is the equivalent in hours. Note that this method takes no parameters.
Movie object to which the method is applied is the "hidden" argument,
it is from this object that a possible implementation of 1engthInHours
ould obtain the length of the movie in minute^.^

ODL: METHODS
thod 1engthInHours may raise an exception called noLengthFound, Pre-
ly this exception would be raised if the length attribute of the object

ue that could not represent a valid length (e.g., a negative number).

1) c l a s s Movie {
2) attribute string t i t l e ;
3) a t t r i b u t e integer year;
4) a t t r i b u t e i n t e g e r length;
5) a t t r i b u t e enumeration(color,blackAndWhite) filmType;
6) r e l a t i o n s h i p Set<Star> stars Three methods declarations
inverse S t a r : : s t a r r e d I n ;
7) r e l a t i o n s h i p Studio ownedBy
inverse Studio::oms;
8) f l o a t lengthInHours() raises(noLengthF0und);
9) void starNames(out Set<String>);
LO) void otherMovies(in S t a r , out Set<Movie>) Parameters are either
raises(noSuchStar); IN, OUT, or INOUT

Figure 4.4: Adding method signatures to the Movie class

In line (9) we see another method signature, for a Definition


method called (implementation)
starNames. is
This method has no return value but has an output not partwhose
parameter of the
typeclass
is a
set of strings. We presume that the value of the output paramet,er is computed
by starNames to be the set of strings that are the values of the attribute name
for the stars of the movie to which the method is applied. However, as always 23
there is no guarantee that t,he method definition behaves in this particular way.
There
is that is
seta issimilar
objects
the belong capability
to one
essentially and
a triple ODL
in consisting
only to
onedeclare
that one
ofclass. Thus,
movie, aC
classto to and
be aasubclass
represent
star, movies
studio, ome possible ap
of usanother class D. We follow the name C in its declaration with the keyword
are the
thatextends salary
bothand that and
cartoons
the name
is paid to the star by the studio for acting in that movie.
D.murder mysteries, we need a fourth class for these
movies.
ODL: INHERITANCE . Disallow m
Example
The 4.10: Recall Example 2.10,
classSubclasses
CartoonMurderMystery mustwhereinheritweproperties
declared cartoons
from both to Car-
be a
3.2
toonsubclass of movies, with as
and MurderMystery, in ODL
thesuggested
additionalby
property
Fig. 4.7. of aThat
relationship from a cartoon
is, a ~artoonMurder-
:tLeta us
setrecall
of stars that are its "voices." Iinr ethe
canE/R
create a subclass Cartoon for
garded as t
the discussion of subclasses model from Section 2.1.11.
Mystery
hlovie object
There with
has
the ODLall the properties
declaration: of a Movie object, plus the relationship
in ODL to declare one class C to be a subclass
voices and
is a similar
the
capability
attribute weapon.
of another class D. We follow the name C in its declaration with the keyword
. Indicate wh
c l a s s Cartoon extends Movie i subclass. F
extends and the name D.
•  Same Idea as in OO
r e l a t i o n s h i p Set<Star> Movieprogramming (C++ or Java)
voices; romance we
•  Subclass inherits all attributes, relationships, and methods
Example 4.10: Recall Example 2.10, where we declared cartoons to be a ending than
subclass of movies, with the additional property of a relationship from a cartoon
ITe
:t ahave
set of
technically
•  we
not Plus
indicated
stars adding
that
must doare
nameadditional
the its of the inverse offields
relationship voices, although
so. "voices." I r e can create a subclass Cartoon for
would spec
hlovie with the ODL declaration: Keyword extends from superc
A subclass inherits Cartoon
all the propertiesMurderMystery
of its superclass. Thus, each cartoon
objectc lhas
a s sattributes
Cartoon textends i t l e , year, length,
Movie i and f ilmType inherited from ~ o v i e
(recall Fig. a t i o nand
r e l4.3), s h iitp inherits
Set<Star> relationships
voices; s t a r s and ownedBy from Cartoon
Movie, movie is a movie
3. Give a new
in addition to its own relationship voices. with voices of characters ties in the s
Also in that esample. we defined a class of murder mysteries with additional
CartoonMurderMyster~ ance inheri
ITe have
attribute not indicated
weapon. the name of the inverse of relationship voices, although
technically we must do so. specify that
Ac lsubclass
a s s Figure
MurderMystery
inherits
4.7: all theextends
Diagram Movie
properties
showing of multiple
its superclass. Thus, each
inheritance Murder
cartoon movie is a movie verdict, w
object hasa t tattributes
r i b u t e sttirtilneg, year, length, and f ilmType inherited from ~ o v i e
weapon; Courtroom.
(recall Fig. 4.3), and it inherits relationships s t a r s and ownedBy from with the weapons used
Movie,
in ODL, wetomay
In addition its ownfollow the keyword
relationship extends by several classes, separated
voices.
is a suitable declaration of this subclass. Again, allby:
t,he properties of additional
movies are
Also in that esample. we
by colons.3 Thus, we may declare the fourth
inherited
defined a class ofclass
murder mysteries with 4.3.4 Exten
attribute by MurderMystery.
weapon.
class
c l a s sCartoonMurderMystery
MurderMystery extends Movie Inherits from two other When an ODL cla
extends
a t t r i b u t MurderMystery
e s t r i n g weapon;: Cartoon; classes the class definitio
given time. The
isWhen a class
a suitable C inherits
declaration fromsubclass.
of this several classes, there
Again, all is t,he potential
t,he properties for are
of movies con- and a relation in
24
fiietsinherited
amongby names. Two or more of the superclasses of C may have a
MurderMystery.
property
a(extent
t t r i b u t eMovies
s t r i n gkey ( t i t l e , year))
name;
...
a t t r i b u t e string t i t l e ;
...
Itcould have used
is possible ODL: INSTANCES & KEYS
thatkeys
severalin place
sets ofof attributes
key, even arethough
keys.only onethen
If so, key following
is declared.
the Similarly,
word key(s) we may
if name is a place
key forseveral keys separated
class Star, by commas.
then we could begin itsAsdeclaration:
usual, a
key that consists of more than one attribute must have parentheses around the
list of class Star so we can disambiguate a key of several attributes from
its attributes,
several Instance
•  keys of one attribute
(extent of akey
Stars class
each.name)are all objects currently exist of that class
Example • 4.14
DDITIONAL In :ODL anthat
AsODL. example is called
CONCEPTS extent
of a situation where(and is given toa have
it is appropriate name)
153
more• than Keysa t t r i are
one b u t e not
key, s t r i nas
consider a important for referencing objects
class
g name;Employee, whose complete set of attributes
andtributes forming
relationships we
... keys.
shall If there
not describe here. than
is more one attribute
However, in atwo
suppose that key,ofthe
its
of • 
attributes Because
must be each
surrounded object
by already
parentheses. The
attributes are empID, the employee ID, and ssNo, the Social Security number. has
key a unique
declaration OID
itself
ears, along with the extent declaration, inside parentheses that may follow
Then • weDefining
can declare each keys in ODL
of these attributes is optional
name of the class itself in the first line of its declaration.
to be a key by itself with
ODL
• class
mple 4.13 : allows
To declare defining
Employee that the set of multiple
two attributeskeys (Comma
t i t l e and year form separated)
yItfor
is class
possible
(extent that
Movie, weseveral
Employees sets
key of
could begin itsattributes
empID, ssNo)are keys. If so, then following
declaration:
the word
c l a s skey(s)
Movie. . .we may place several keys separated by commas. As usual, Keywords
a extent & key
key that consists
(extent ofMovies
more than key one t i attribute
(around
t l e , the must have parentheses around the
year))
Because there are no parentheses list of attributes, ODL interprets
list
the of its attributes,
above as saying that we can
so each of thedisambiguate
two attributesa keyis aofkey
several attributes
by itself. If we putfromThe key is the pair of (title, year)
several
parentheseskeysaround
a t t of.one
r i b u t attribute
e
. . the
s t r i n g each. ssNo) , then ODL would interpret the two
t
list (empID,
i t l e ;

attributes together
Example : As asan
forming
example one key.a situation
That is, the implication of writingto have
could have 4.14 used keys in place ofofkey, where
even though it isoneappropriate
only key is declared.
more than
classone
Similarly, key, isconsider
ifEmployee
name a key for a class
class Star,
Employee, whose
then we couldcomplete
begin itsset of attributes
declaration:
and relationships S t a r we
c l a s s(extent shall not key
Employees describe(empID,here.ssNo))
However, suppose that two of its
are .empID,
attributes(extent . . S t athe employee
r s key name)ID, and ssNo, the Social Security number. The key is the pair of (empID, SSN)
Then we can declare each of these attributes to be a key by itself with
a t t r i b u t e s t r i n g name;
...
class Employee Two keys empID and SSN
(extent Employees key empID, ssNo)
...
It is possible that several sets of attributes are keys. If so, then following
the word key(s) we may place several keys separated by commas. As usual, a 25
Because
key there are
that consists no parentheses
of more around the
than one attribute listhave
must parenthesesODL
of attributes, interprets
around the
WHAT’S NEXT

•  First Approach: Object-Oriented Model


•  Concepts from OO programming languages
•  ODL: Object Definition Language
•  What about querying OO databases???
•  OQL: Object Oriented Query Language

26
OQL: OBJECT-ORIENTED QUERY
LANGUAGE
•  OQL is a query language designed to operate on
databases described in ODL.

•  Tries to bring some concepts from the relational model to


the ODBMs
•  E.g., the SELECT statement, joins, aggregation, etc.

•  Reference of class properties (attributes, relationships,


and methods) using:
•  Dot notation (p.a), or
•  Arrow notation (p->a)

•  In OQL both notations are equivalent

27
If it makes sense, we can form expressions with several dots. For example,
if myMovie denotes a movie object, then myMovie. ownedBy denotes the Studio
object that owns the movie, and mynovie. ownedBy .name denotes the string
that is the name of that studio.
INTRODUCTION TO OQL OQL: EXAMPLE QUERIES
Select-From-Where I OQL
Expressions in 9.1.3
OQL permits us to write expressions using a select-from-where syntas similar
. to SQL's familiar query form. Here is an example asking for the year of the
N IN QUERY
c l a s s MovieLANGUAGES movieINTRODUCTION
9.1. Gone IVzth the Wind. T O Reference
OQL the extent (instance of class)
( e x t e n t Movies key ( t i t l e , y e a r ) )
C SELECT m. yearWHERE and a boolean-valued expression. This expression,
attribute string t i t l e ; 3. The keyword
ts a t t r i b u t e integer year; FR OM Movies
the expression m following the SELECT, may only use as operands const
a t t r i b u t e integer length; WHERE
and those i t l e = "Gone
m . t variables declaredWith in t h the
e Wind"FROM clause. The comparison opera
he dot. This
a t t r i b uconvention
t e enum Film is (color,blackAndWhite> filmType; are like SQL's, except that ! =, rather than <>, is used for "not equal
arrow both
r e l a tobtain
i o n s h i p Scompo-
et<Star> s t a r s XoticeSelect the year
that,logical
The escept for the of movie
operators are‘Gone
double-quotes Owith
AND, around R, and the
theNO wind’
string
T, likeconstant,
SQL's.this query
ow and dot operators i n v ehave
rse Star::starredIn;
r e l a t i o n s h i p S t u d i o ownedBy
could be SQL rather than OQL.
the same. 111 C, expression The querythe
In general, produces a bag of objects.
OQL select-from-where We compute
expression consists of: this bag by conside
i n v e r s e Studio::owns;
pects p to be a pointer to a
f l o a t lengthInHours() r a i s e s ( n o ~ e n g t h F 0 u n d ) ; all possible values of the variables in the FROM clause, in nested loops. If
N INthat
f of QUERY structure. LANGUAGES 9.1. INTRODUCTION
combination of values TO OQL
void starNames(out S e t < S t r i n g > ) ; 1. The keylvord SELECTfor these
follolved variables
by satisfies the condition of the WH
a list of expressions.
void otherMovies(in S t a r , o u t Set<Movie>) clause, then the object described by the SELECT clause is added to the bag
For each movie a m,
list sof isone
theorset of variable
stars in declarations.
-

raises(noSuchStar); 2. The
3.
is the The
resultkeyrvord
keyword
of the FRO WM H Efollowed
RE and
select-from-where abyboolean-valued
statement. more
expression. This expression,
ts I ; dthe expression
variable that
is declared movie
following (follow
by giving a relationship)
the SELECT, may only use as operands const
Example and those9.2 :variables
Here is adeclared more complex in the FR OQL query:The comparison opera
OM clause.
he dot. This convention is 430 CH..IPTER 9.(a)
are OBJECT-ORIENTATION
.A
liken expression
SQL's, whose
except value
that I,V! QUERY
has
=, a
rather LANGUAGES
collection
than <>, is
type, e.g.used
a setfor
or "not
bag. equal
th c l a s sdots.
several S t a r For example,
arrow both obtain compo-
( e x t e n t S t a r s key name)
SELECT s.name
The logical operators are AND, OR, and NOT, like SQL's.
. ownedBy
ow and< dot denotes
operators the Studio have (b)
FROM The optionalm,
Movies keyn-ord
m . s t aAS, r s and
s
edBy .name denotes
the same. a t1t1r1i bC, the
u t eexpression string W HER E m . t i t of
l ethe "Casablanca"
=avariable.
s t r i n g name; The (c) The
query name
produces bag of objects. We compute this bag by conside
pects p toa be t t r i baupointer
t e S t r u c t to Addr a Alternative Form of FROM Lists
all possible values of the variables in the FROM clause, in nested loops. If
f of that structure. { s t r i n g s t r e e t , s t r i n g c i t y ) a d d r e s s ; ThisSelect
query star
Typically. asks names
the for thefrom
expression names movie
of (a) is‘Casablanca’
ofvariables
the thestars of of
extent Casablanca.
some class, Notice
such as ofthe sequ
thethe
r e l a t i o n s h i p Set<Movie> s t a r r e d I n In addition combination
to the
of termsSQL-style
in
ofelements
the
values
FR O M offor
clause.FROthese
M clauses,
First wewhere
define
satisfies
the collection
m to be
the
an
condition
arbitrary object
WH
in
ons in OQL inverse Movie::stars; clause, extent
then Movies
the objectfor class
describedMovie in
by the
the example
SELECT above.
clause An
is extent
added is
to the
the bag
is follo~vedclass
by a name
Movie, forby a typical
saying element,
m is in OQLextent
the allo~vsof a completely
that class, which is Movies. T
is theanalog
result ofofathe select-from-where
relation in an SQL FRO Mstatement.
clause.
1;
ect-from-where syntas similar equivalent, for
moreeach
logical,
valueyet of less mSQL-is11
we let Another
form.
s be We a Scan
t notation
a give
r the However,
object typical
in the
it is possible to
set m.stars of star
ple asking for the year of the element name, usethe
then in keyword
a variable I N declaration
, and any collection-producing expression, such as
movie
Example m. That
another 9.2 :is,Here n-e
select-from-where is afinally
consider more the
in name
two
complex
expression.
of the
nested OQL collection.
loops
query: all pairs (m, s ) such that
c l a s s Studio For instance,
a movie and s a star of that movie. The evaluation can be sketched as:
th several(dots. e x t e n t SFor t u d i example,
o s key name) SELECT s.name
. ownedBy
C denotes the Studio FR
ROR
O
OMeach
M m i m,
I N Movies,
mMovies n Movies
m r DO
s . IsNt am.stars
s s
edBy .namea tdenotes t r i b u t e s t the r i n g string
name;
W HE R EFORm .each
t i t l e s= i n m.stars DO
"Casablanca"
a t t r i b u t e s t r i n g address;
r e l a t i o n s h i p Set<Movie> owns
is an equivalent FROM clause for IFthe mquery
. t i t l in
e Example
= "Casablanca" 9.2. THEN
i n v e r s e Movie::ownedBy; This query asks for add
the s.name
names of t
theo t h e
stars output
of Casablanca.
bag Notice 28the sequ
he string constant, this query of terms in the FR O M clause. First we define m to be an arbitrary object in
ons in OQL
I ;
class The WHERE
Movie, byclause
saying restricts
m is in our the consideration
extent of thatto thosewhich
class, pairs isthat have mTe
Movies.
a star appeared in several Disney movies.
allow a variable representing a typical element of that collectio
SELECT DISTINCT s.name each member of the collection.
FROM Movies m , m.stars s Example 9.6 : Let us redo the query of Example 9.3, which ask
To make
WHERthe result
E m. a list, add
ownedBy. namean =
ORDER BY ofclause
"Disney" at the end of the query,
the movies made by Disney. First, the set of Disney movies co
again as in SQL. by the query, as was used in Example 9.4.

OQL: EXAMPLE QUERIES II


The strategy of this query is similar to that of Example 9.2. We again
INTRODUCTION TO OQL The followingall
consider pairs ofwill
examples a movie and
illustrate thea correct
star ofsyntax.
that movie
SELECT m in two nested loops as in
Example 9.2. But now; the condition on thatFROM pairMovies m is that "Disney" is the
(m, s)
name of the studio whose S t u d i o object is m. ownedBy.movies. =The
Example 9.3: Let us ask for the names of the WHERE
stars of m.ownedBy.name
Disney "Disney"
following query does the job, eliminating duplicateWenames inuse
can now thethis
situation
query as where
a subquery to define the set over w
The ORDER BY clause in OQL is quite similar to the same clause in SQL.
a star appeared in several Disney movies. d. representing the Disney movies; can range.
c l a s s Movie Keywords ORDER BY are followed by a list of expressions. The first of these
( e x t e n t Movies key ( t i t l e , y e a r ) ) expressions is evaluated for each object in the SELECT DISTINCT
result of thes.namequery, and objects
SELECT DISTINCT s.name FROM (SELECT m
C areFRordered by this
OM Movies m, m.stars s value. Ties, if any, are broken by the value of the second
FROM Movies m
attribute string t i t l e ; expression. then the third, and so on. By default, the order is ascending. but
a t t r i b u t e integer year; WHERE m. ownedBy. name = "Disney" WHERE m.ownedBy.name = "Disney") d,
a choice of ascending or descending order can be d. indicated
stars s
by the keyword ASC
a t t r i b u t e integer length; or DESC, respectively. following an attribute. as in SQL.
NTATION aI,V t t r QUERY
i b u t e enum LANGUAGES
Film (color,blackAndWhite> filmType;
9.1. IAiTRODUCTION TO OQL
The strategy of this query is similar to thatThis Exampleof9.2.
of expression We again 43 1
consider Select
all pairs distinct
of :a Let
movie star names in movies owned by
the query ‘Disney’
"Find the stars of Disney movi
relationship Set<Star> s t a r s Example 9.4 us and
finda thestarset
of that movie
of Disney
succinctinmovies,
two nested
than thatbut loops
let the
of Example as9.3.
in and be
result a listless so. Ho
perhaps
inverse Star::starredIn; Example
Inofthe 9.2. But
first
movies. three now;
ordered the
lines,
by wecondition
consider
length. Ifonthere
that pair
each are
Movie(m, s)
ties, isa new
object
illustrate let thatm.
the "Disney"
If
movies
form theofis
of building the
name
equal oflength
queries the be
available in OQL. In th
m of FROMr e lLists a t i o n s h i p S t u d i o ownedBy
i n v e r s e Studio::owns;
ordered
name
studioof the
thatalphabetically.
studio
oxnswhosethis movie
S t u The
d i is
o queryisis:
object
"Disney," m. the the
then
ownedBy. clause has two
FROM complete object subquery
nestedmloops. In the first, the variabl
becomes
f l o a t lengthInHours() r a i s e s ( n o ~ e n g t h F 0 u n d ) ; a member of the output bag. The fourth allline Disney movies, the result of the subquery in the FROM clause
specifies that the object,s m
The SELECT m
clause in OQL is quite similarloop,
to nested
the withinclause
same the first,
in the variable s ranges over all star
of FROM clauses, where the collection
void starNames(out S e t < S t r i n g > ) ; produced ORDER
FR O
by
M
BY
the select-from-where
Movies m
query are to
lnovie d. ordered
'
be Sotice thatfirst by SQL.
no WHERE the value
clause of in the outer qu
is needed
element, OQL allo~vs a completely
void otherMovies(in S t a r , o u t Set<Movie>) Keywords ORDER BY are followed
t h (i.e., m.ownedBy.name
m. l e n gWHERE the length of the movie)by a list of expressions. The first of
and then, if there are ties, by the value these
= "Disney"
-is11 form. We can giver the a i s e stypical
(noSuchStar); expressions
of m. t i O lisD evaluated
(i.e., for each object in the result of the query, and objects
tR eE R BY m.length, m . t i t l e The value produced by this query is
the title of the movie).
nd finally
I ; the name of the collection. are
thusordered
a listbyof this
Movie value. Ties, if any, are broken by the value of the second
objects.
expression. then the
order third, and
movies so on.by
owned By‘Disney’
default, thebased
order ison
ascending.
lengthbutand title
class Star a 9.1.5
choice of ascending or descending
Complex Output Types order can be indicated by the keyword ASC
, s I N m . s(teaxrt se n t S t a r s key name) or DESC, respectively. following an attribute. as in SQL.
<
uery in Example
The elements in the SELECT clause need not be simple variables. They can
a t t r i b9.2.
u t e s t r i n g name; Example 9.4 : Let us find
be any expression, the setexpressions
including of Disney movies,
built but let the
using result
type be a list
constructors. For
a t t r i b u t e S t r u c t Addr weReport
{string s t r e e t , s t r i n g c i t y ) address;
ofexample,
movies. ordered
canbyapplyset
length.theof structures
If Sthere
t r u care ties,constructor
t type let the movies
toofseveral
equal length be
expressions and
r e l a t i o n s h i p Set<Movie> s t a r r e d I n
ordered alphabetically. The query
get a select-from-where query that
is: produces a set or bag of structures.
RDER BY clause at the end iof n vthe
e r s equery,
Movie::stars;
1; Example m
SELECT 9.5: Suppose we want the set of pairs of stars living at the same
FROM \ire
address. can mget this set with the query:
Movies Join two classes
e correct syntax. WHERE m.ownedBy.name = "Disney"
c l a s s Studio SELECT
ORDER DISTINCT m
BY m.length, S t. rt iutcl et ( s t a r l : s l , s t a r 2 : s 2 )
s of the stars
( e xoft e nDisney
t S t u d imovies. The
o s key name) FROM S t a r s s l , S t a r s s 2
C names in the situation where
duplicate WHERE s l . a d d r e s s = s 2 . a d d r e s s AND s1.name < s2.name
a t t r i b u t e s t r i n g name;
.
a t t r i b u t e s t r i n g address;
r e l a t i o n s h i p Set<Movie> owns Report
That is, pairs of
1%-econsider all stats who
pairs of have
stars, the s2.
s l and sameTheaddress
WHERE clause checks
i n v e r s e Movie::ownedBy; that they have the same address. It also checks that the name of the first star 29
I; p~ecedesthe name of the second in alphabetic order, so ~3-edon't produce pairs
y"
In addition to the SQL-style elements of FROM clauses, where the collection produced
example, we by the
can select-from-where
apply the S t r u c tque
typ
is follo~vedby a name for a typical element, OQL allo~vsa completely getl eanselect-from-where
m. g t h (i.e., the lengthquery
of thethat pro
movie
equivalent,
To make themore logical,
result a list,yet
add anSQL-is11
less ORDER BY form. Weatcan
clause the give thethe
end of typical
query, of m. t i t l e (i.e., the title of the movi
element name, then
again as in SQL. the keyword I N , and finally the name of the collection. E x a m p l e 9.5: Suppose we want the
TER 9. OBJECT-ORIENTATION I,V QUERY LANGUAGES thus a list of Movie objects.
9.1. IAiTRODUCTION TO OQL
For instance, address. \ire can get this set with the

OQL OUTPUT
The following examples will illustrate the correct syntax.
In the first three lines, we consider each
9.1.5 Movie object
Complex
SELECT DISTINCT m. IfS tthe
Output r u cnames t ao
t (Typ
Example 9.3:
Alternative usFR
Let of
Form OM for
ask
FROM Ithe
N Movies,
mLists I N stars
names ofs the m.stars
of Disney movies. The
studio that oxns this movie is "Disney,"FROthen
M Sthe
t a rcomplete t a r s sm2 bec
s s l , Sobject
following query does the job, eliminating duplicate names in the situation where a member of the output bag. The The fourthelements
WHERE lines in
lspecifies
. athe e sthat
s = the
d d r SELECT 2 . aobjec
sclause d d rn
o the SQL-style
a star anelements
is appeared
equivalent FR
FR OO clause
MMclauses,
inofseveral Disney for
where the
thequery
movies. in Example 9.2.
collection produced by the select-from-where query are to be ordered
be any expression, including expressi first by the val
y a name for a typical element, OQL allo~vsa completely m . l e n g t h (i.e., the length of the movie) That is, consider all pairs of star
more logical, SELECT DISTINCT
yet less SQL-is11 form.s.name
We can give the typical example, we can apply the S t r u c t typv
and then,
1%-e if there are ties, by the
of m. t i t l e (i.e., the title of the that movie). The value theproduced by this It que
FROM Movies
e, then the keyword I N , and m , m.stars
finally the names of the collection. thus a list of Movie objects.
get a they have
select-from-where samequery address.
that pro a
p~ecedesthe name of the second in alp
•  Unlike SQL which produces relations, OQL produces
WTo
again
E m. ownedBy.
HERmake
as
the resultname
in SQL.
a list,=add "Disney"
an ORDER BY clause at the end of the query,
9.1.5 Complex Output address.
consisting of the same star t~viceand
Example 9.5: Suppose we want the
in two different orders.
Types
The m Istrategy of sthis m . s t a r sis similar to that of Example 9.2. We again
I N query
collection (set, bag, list) of objects
FROM N Movies, \ire can get this set with the
For every pair that passes the t ~
consider all pairs of a movie and a star of that movie in two nested loops as in
The following examples will illustrate the correct syntax. The elements in the SELECT clause typeneed of thisnot structure
be simpleisvariables.a record with They
M clause 9.2.
ent FROExample for the But now;inthe
query condition
Example 9.2. on that pair (m, s) is that "Disney" is the be any expression, including expressions SELECTbuilt DISTINCT
using type Sconstructors.
truct(star
name of the 9.3: studioLet whose object is m. type of each field is the class S t a r . s
•  The object can be of any type
Example us askS t ufor d i othe names of ownedBy.
the stars of Disney movies. The
9.1. IAiTRODUCTION TO OQL 43 1
example, we can apply the S t r u cand t type s 2FR OM Sprovide
constructor
that t a r s tos lvalues
, S t afor
several r s the
s 2 two
expressions
following
The ORD query
ER BYdoes the job,
clause in OQL eliminating
is quiteduplicate
similar to names in the clause
the same situationin where
get a select-from-where query that
SQL. W
produces H E R Ea s
setl . a
or d d
bagr e s
ofs s2.addre
structures.
=
structure is
he result a astar
Keywordslist,appeared
addORan DER ORinDER
BY several
BY clause
are Disney
followed at the movies.
by end of the
a list of query,
expressions. The first of these
n SQL. In the first three
expressions lines, wefor
is evaluated consider
each object each Moviein theobject
resultm. If the
of the nameand
query, the Example 9.5: Suppose we want
of objects Thatthe is, set of
u cpairs
S t r1%-e ( s t aof
tconsider r 1stars
: all living
S tpairs at
a r , sof the
t a star
r2:
studio
are ordered SELECT
that oxns by thisDISTINCT
thisvalue.
movie is s.name
Ties,"Disney,"
if any,thenare thebrokencomplete
by theobjectvaluemofbecomes
the second address. \ire can get this set with the query:
xamples will illustrate theoutput
correct syntax. that they have the same address. It a
aexpression.
member FROM Movies
ofthenthe m , bag.
the third, m.stars
andThe so son.fourth
By line specifies
default, that Set
the order the of strings
object,s
is ascending. m but The typethe
p~ecedes of thename result
of of second
the the query in is
alp
SELECT DISTINCT S t r u c t ( s t a r l : s l , s t a r 2 : s 2 )
Let usproduced
a choice
ask for W H
ofby
the m.select-from-where
Eascending
REthe
names ownedBy.
ofor nameof=query
thedescending
stars "Disney"
order
Disney are to be
can
movies. ordered
beThe indicated firstbybythe
thekeyword
value of ASC FROM S t a r s s l , S t a r s s 2consisting of the same star t~viceand
m.or ljob, (i.e., theduplicate
e n geliminating
DESC, t hrespectively. length ofnames
followingthe movie)an and
attribute. then, ifinthere
aswhere SQL.are ties, by the value Set<Struct{starl: S t a r , sta
does the in the situation WHERE s l . a d d r e s s = s 2 . ain d dtwor e s sdifferent
AND s1.name orders.< s2.name
The
of m.Disney
in several strategy of this query is similar to that
(i.e., the title of the movie). The value produced by this query is
t i t l e movies. of Example 9.2. We again
Example
consider 9.4pairs: Letofusa find theand set aofstarDisney movies,
moviebut in let
twothe result be aaslist For every pair that passes the t ~ t
thus a list all of Movie movie
objects. of that nested loops in is, 1%-econsider all pairs of stars,
That s l and s2. The WHERE clause ch
ISTINCT ofExample
movies.
s.name ordered
9.2. Butby now;length. If there are
the condition on ties,
that let
pairthe (m,movies
s) is thatof equal length
"Disney" be
is the type of this structure is a record with
that they have the same address. It also checks that the name of the first
vies mordered
, name
m.stars alphabetically.
s The query is: type of each field is
of the studio whose S t u d i o object is m. ownedBy. p~ecedesthe name of the second in alphabetic order, so the
~3-edon't Star. s
class produce
ownedBy. 9.1.5name =Complex "Disney" Output Types 9.1.6
and 2 that Subqueries
SELECT m consisting of the same star t~vice and swe don'tprovide
producevalues the same for the
pairtwo of
The The
elements
FROM O R D E R
in BY
the clause
SELECT in OQL
clause is
need
m that of Example 9.2. We again quite
not similar
be simpleto the same
variables. clause
They in
canSQL.
in two different orders. structure is
y of this query is Movies
similar to Ure can use a select-from-whereexpres
s of a be Keywords
anyWHERE
movie and aO RDER BY
m.ownedBy.name
expression,
star are
including
of that moviefollowed
expressions
in=two by
"Disney" a built
nested list
loopsof expressions.
using
as Set
Theoffirst
in type constructors. objects
of ofFor
Forthese typeevery Movie
pair that passes the\Ye t ~ shall
tests,
o we giveproduce a record structure.
one example: in the
ut now; expressions
example, O R D
the condition E R is
BY evaluated
we canonapply m.length, for
the S(m,
that pair m each
. t i t
u cist type
t r s) object
l e in the
constructor
that "Disney" result
is the of the query,
to several expressions andand objects
type of this structure is a record subquery use appear sintSaSection
with S
two t r u c
fields,t ( s t a
named r 1 : tralrand
, s tsa9.2.
t ra2r 2: .
dio whose areaSordered
get by this
t u d i o object
select-from-where is m.value.
query Ties,
ownedBy. if any, are
that produces broken
a set or bag byofthe value of the second
structures. type of each field is the class S t a r . since that is the type of the variable
expression. then the third, and so on. By default, the order is ascending. but and s 2 that provide values for the The twotypefields. of That
the result of the the
is. formally, querytypeiso
BY clause in
Example OQL is quite similar
Suppose to the same clause in SQL. structure is
a choice of9.5: ascending orwe want the order
descending set of can
pairsbeofindicated
stars living at the
by the same ASC
keyword
R BY are followed by a list of expressions. The first of these Set<Struct{starl: S t a r , sta
address. \ire can get this set with the query:
valuatedorfor DESC, object in the following
each respectively. result of the an query,
attribute. as in SQL.
and objects S t r u c t ( s t a r 1 : S t a r , s t a r 2 : star)
his value. Ties, if any, are broken t r ubythe
c tthe t value of the second
Example
SELECT 9.4 : Let us Sfind
DISTINCT ( sseta rof
l :Disney
s l , s tmovies,
a r 2 : s 2but
) let the result be a list
2 there are ties, let the movies of equal length be Set of structures
the third, and so on. By default, the order is ascending. but The type of the result of the query is a set of these structures, that is:
of FROM S
movies. t a r s s by
ordered S t a r s s If
l , length.
nding or descending order can be indicated by the keyword ASC
WHEalphabetically.
ordered RE s l . a d d r e s s = s 2query s s AND s1.name < s2.name
. a d d r eis:
vely. following an attribute. as inThe SQL. Set<Struct{starl: S t a r , star2: Star)>
9.1.6 Subqueries 30
Let usThat is,SELECT
find the 1%-e consider
set of m
Disney all pairsbut
movies, of stars, l andbes2.
let the sresult a listThe WHERE clause checks
that they
ed by length. have are
If there the ties,
sameletaddress. It also
the movies checks
of equal thatbethe name of the first star
length
HAVING <condition>

i t i o n p) serves t o eliminate some of t h e groups created by the GROUP BY. The condition
applies t o the value of the p a r t i t i o n field of each structure in the intermedi-
e first realize that variable p rangcs
a t e collection. If true, then this structure is processed as in Section 9.2.3, t o
of the structure in the GROUP BY
form a structure of the output collection. If false, then this structure does not

OQL: AGGREGATION
e of the form S t r u c t (m: o ) , t+-hereo
contribute t o the output collection.
efore refers to this object
INTRODUCTION o. Thus.
TO OQL
of this Movie object E x a m p l e 9.11 : Let us repeat Example 9.10, but ask for t h e sum of the lengths
ces the bag of lengths of the movies of movies for only those studios and years such that the studio produced a t lewt
has t h e value "Disney" and y r has one movie of over 120 minutes. The query of Fig. 9.7 does the job. Notice t h a t
from is the bag of t h e lengths of the in t h e HAVING clause we used t h e same query as in the SELECT clause to obtain
apply thec l a sSsUM operator t o this bag
Movie the bag of le~lgtlisof movies for a given studio and year. In the HAVING clause,
s in the group. nThus,
( e x t e t Movies
onekey ( t i t l e , year))
member tve take the maximum of those lengths Aggregate
and compareover
it tthe partition
o 120.
C
attribute string t i t l e ;
a t t r i b u t e integer year;
a t t r i b u t e integer length; SELECT s t d o , y r , sumlength: SUM(SELECT p.m.length
Disney movies a t t r i bof enum Film (color,blackAndWhite> filmType;
u t e1990. FROM p a r t i t i o n p)
relationship Set<Star> s t a r s
FROM Movies m
inverse Star::starredIn;
M u l t i p l e rCe loaltlieocntsihoi n
p sS t u d i o ownedBy GROUP BY s t d o : m.ownedBy.name, y r : m.year
i n v e r s eaStudio::owns; HAVING MAX(SELECT p.m.length FROM p a r t i t i o n p) > 120
variable in the FROM clause. f e ~
f l o a t lengthInHours() r a i s e s ( n o ~ e n g t h F 0 u n d ) ;
y are necessary, but the principles
void starNames(out S e t < S t r i n g > ) ;
e above. Suppose that the variables
void otherMovies(in S t a r , o u t Set<Movie>) Figure 9.7: Restricting the groups considered
:xk. Then:
raises(noSuchStar);
I;

class Star Intermediate result


( e x t e n t S t a r s key name)
< Grouping fields
Struct{
a t t r i b u t e s t r i n g name;
a t t r i b u t e S t r u c t Addr
{string s t r e e t , s t r i n g c i t y ) address; stdo: …,
r e l a t i o n s h i p Set<Movie> s t a r r e d I n
inverse Movie::stars; yr: …,
1; partition: bag(struct {m: …})
};
c l a s s Studio
( e x t e n t S t u d i o s key name)
C
a t t r i b u t e s t r i n g name;
a t t r i b u t e s t r i n g address;
r e l a t i o n s h i p Set<Movie> owns
Bag of structures with members
i n v e r s e Movie::ownedBy; follow what’s in the FROM clause 31
I;
Raise the exception n o s i s t e r s if the ship FOR ALL x IN S : C(x)

The result of this expression is TRUE if every x in S satisfies C(x) and is FALSE
eter, and applying the method to a ship s, otherwise. Similarly, the expression

OQL: COLLECTION OPERATORS


le b, provided s participated in that battle.
articipate if ship s did
INTRODUCTION TO not
OQLfight in battle EXISTS x I N S : C(x)

has value TRUE if there is at least one x in S such that C(X) is TRUE and it has
ched as parameters, add a ship of this name value FALSE otherwise.
h the method is applied.
c l a s s Movie
Example 9.7 : Another way to express the query "find all the stars of Disney
of Exercise
C
( e x t e n t Movies key ( t i t l e , y e a r ) )
9.1.2 using at least one subquery Likeis in
• movies" SQL,
shown we
in Fig. 9.4. have
Here, ANY,
we focus on ALL,
a star s and ask if they are

allEXISTS
attribute string t i t l e ; the star of some movie rn that is a Disney movie. Line (3) tells us to consider
a t t r i b u t e integer year; movies m in the set of movies s. starredIn, which is the set of movies in
a t t r i b u t e integer length;
chema of Exercise which star s appeared. Line (1)then asks whether movie m is a Disney movie.
a t t r i b u t e 9.1.3
enum and Film Fig. 9.3, xvritc
(color,blackAndWhite> filmType;
relationship Set<Star> s t a r s If we find even one such movie m , the value of the EXISTS expression in lines
inverse Star::starredIn;
r e l a t i o n s h i p S t u d i o ownedBy
•  OQL has similar operators
(3) and (4) is TRUE; otherwise it is FALSE.
of ships with at least nine i n v e rguns.
s e Studio::owns;
f l o a t lengthInHours() r a i s e s ( n o ~ e n g t h F 0 u n d ) ;
hip names)void withstarNames(out
at least nineS eguns. t<String>); 1) SELECT s
void otherMovies(in S t a r , o u t Set<Movie>)
r a i 30,000
s e s ( n o Stons.
u c h S t aNake
r);
2) FROM S t a r s s
ith a displacement under 3) WHERE EXISTS m IN s . s t a r r e d I n :
I;
rliest launch year first, and if there are ties. 4) m. ownedBy .name = "Disney"

class Star
( e x t (i.e.,
e n t Sships
t a r s key name)
Select stars who participated in a
are sister ships of the same class). Figure 9.4: Using an existential subquery
< movie made by ‘Disney’
ves are wanted, not the names of the ships.
a t t r i b u t e s t r i n g name; 438 CHAPTER 9. OBJECT-ORIENTATlOiV IN QUERY LANGUAG
a t t r i b u t e S t r u c t Addr
es in which ships { s t r of
i n gats t rleast
e e t , two
s t r i ndifferent
g c i t y ) address; Example 9.8 : Let us use the for-all operator to write a query asking for the
r e l a t i o n s h i p Set<Movie> s t a r r e d I n stars that have appeared only in Disney movies. Technically, that set includes
inverse Movie::stars; SELECT
.'stars" who appears in no movies at all (as far as we can tell from our database).
1; no ship was listed as damaged.
sin which It is possible to aadd
FROM S t r s sanother condition to our query, requiring that the star
appear inWHERE FOR one
at least ALLrnovie.
m I N but
s . s tTW
a r rlealr
e d I nthat
: improvement as ail exercise.
c l a s s Studio m. ownedBy
Figure 9.5 shows the query. .name = "Disney"
s of QQL
( e x t e Expressions
n t S t u d i o s key name)
C
a t t r i b u t e s t r i n g name; Select stars who participated only
of the othera toperators, besides select-from- Figure 9.5: Using
9.2.2 in Aggregation a subquery with universal quantification
t r i b u t e s t r i n g address; movies made by ‘Disney’
Expressions
us build expressions. These
r e l a t i o n s h i p Set<Movie> operators
owns in-
and there-exists - aggregation operators,
i n v e r s e Movie::ownedBy; OQL uses the same five aggregation operators that SQL does: AVG, COUNT.
32 SUM.
ators - I ;union, intersection, and difference. applying to a designated column of a table, the same operators
MIN. and MAX. However, while these operators in SQL may be thought in OQL
of asap
SELECT DISTINCT m
Movie. We can use the title and (to break9.3. ties)OBJECT
the year ofASSIGAr1IENT
the movie, since-4ND CR
44.1 CHAPTER 9. OBJECT- 0RIENT;LTION
FROM Movies m I N QUERY LANGUAGES
vies made before 1920. Its type is Set<Movie>. (title, year) is a key for Movie. Example The statement
9.15: Suppose we want a list of all the movie objects in the class
variable of the same type, then weWHERE maym.year write< 1920 Movie. We can use the title
9.3.1 Assigning Values to Host-Language VariablesmovieList = SELECT m (title, year) isthen theandtype (to break
of theties) the year of theand
variable movie,the
sinceexp

Unlike
STINCT m
es language
m
SQL, which needs INTEGRATING OQL & EXTERNAL
variables, OQL fits
produces the set of all those movies made before 1920. Its type is Set<Movie>.
If
to oldMovies
move is
data
(in C++naturally
a host-language
between
extended withinto
variable of
components the same type,
of
OQL):its host language. That is: the
then
tuples we may
and write
host-
FROM Movies m
ORDER BY m.title, movieListm.year;
a key
legal. for

= SELECT m
Movie. The statement

LANGUAGES
9.3.3FROM MoviesObtaining
mall the MovieEach Membe
arexpressions
< 1920; of OQL that we have learned, such as select-from-where, assigns produce
to host-language variable movieList a list of objects,
oldMovies = SELECT DISTINCT m ORDER BY m.title,
objects as values. It is possible to assign to any host-language variable sorted byoftitle the and year. Obtaining each m.year;
member of a set or bag is
become the set of these Movie objects. FROM Movies
proper type a value that is the result of one of these OQL expressions. m
the cursor-based algorithms we needed in
WHERE m.year < 1920; Once x-e haye a list, sortedassigns to host-language variable
or not. we can or bag access movieList
each
into list.a list\Ye
a element of all
by dotheso
number; Movie objects,
with a se
Example 9.13
ents of Collections : The OQL expression
the ith element of the list L is sorted
obtainedby titleby
andORDER
year.- 11.BY.
L[i Note that lists and arrays
Recall from Section 9.1.4 that
•  OQL fits naturally in OO host languages
and the value of oldMovies will become the set of these Movie objects.
are assunled numbered starting at 0, as in C or C++.
group-bySELECT DISTINCT
expressions m
each produce collections Once x-e haye list
a list,ofsorted
theor selected objects
not. we can access or values.
each element by number;
FROM Movies m
we must do something extra if we 9.3.2 Extracting Elements of Collections E x a m p l e 9.16 : Suppose we want to write
want a single the ith element of the list L is obtained by L[i - Note that lists and arrays
•  Returned objects are assigned in variables in the
11.
WHERE m.year < 1920 E xaa C++ m p l efunction
9.15: Suppose that printswethe want a lis
statement is true even if we have a collection title. year, and length of eacharemovie. assunled numbered
-1Movie.
sketch starting
ofWe at 0, can
the in Cuse
asfunction or C++.is shown in (to bre
Since the select-from-where the title and
e element. OQL provides the operator ELEMENT and group-by expressions each produce collections
isifFig. 9.9.
host program
produces the set of all those - movies
either sets, made
bags, or before
lists - we 1920.
must do Its type
something extra Set<Movie>.
we want a single (title, year) is a key for Movie. The s
o its lone member. This operator can be applied. Example 9.16 : Suppose we want to write a C++ function that prints the
If oldMovies is a host-language
uery that is known to return a element variable of the same type, then we may
of that collection. This statement is true even if we have a collection
singleton. write
title. year, and length of each movie. -1sketch
movieList of the function is shown in
= SELECT m
(in C++ extended with OQL): that n-e are sure contains only one element. OQL provides the operator1) ELEMENTmovieList = SELECT Fig. m9.9. FROM Movies m
ould like to assign to the variable gwtw.
to turn of type
a singleton collection into its lone member. This operator can be applied. FROM Movies m
s type) the oldMovies = SELECT
object representing the DISTINCT
movie Gone m ORDER BY m.title,
for instance, to the result of a query that is known to return a singleton. ORDER BY m.title, m.year;
he query FROM Movies m
2) number0fMovies = ~0UNT(Movies); 1) movieList = SELECT m
WHEREExample
m.year 9.14 <: Suppose
1920; we would like to assign to the variable gwtw. 3) for(i=O; i<numberOfMovies; assigns
of type i++) FROM to host-language variable movie
( Movies m
sortedORDER by BYtitle andm.year;
year.
and the value of oldMovies will become the set of these Movie objects.4) Gone movie = movieList [i] ;
Movie (i.e., the Movie class is its type) the object representing the movie m.title,
lllth the Wind. The result of the query year << I' "
WithVariable
the Wind"in host 5) cout << movie.title << " 'I << =movie.
2) number0fMovies
Once
~0UNT(Movies);
x-e haye a list, sorted or not. we
language (C++ or Java) 6 << movie. length << "\nl' ;
3) for(i=O; i<numberOfMovies; i++) (
9.3.2 Extracting Elements SELECT m of Collections
ne object. 11-e cannot assign this bag to variable 1 4)
the ith element of the list L is obtained b
movie = movieList [i] ;
FROM Movies m are assunled numbered starting at 0, as i
ld get
Sincea type error. However.
the select-from-where Array x e of
if and applyobjects of type Movie
the expressions cout << movie.title << " 'I << movie.year << I' "
WHEREgroup-by
m.title = "Gone With the Wind" each produce collections 5)
- either sets, bags, or lists - we must do something extra if we want a single Figure 9.9: Exanlining 6
and E x<<amovie.
printing llength
m p each e 9.16 << :"\nl'
movie
;
Suppose we want to w
m
element of that collection. is This
the bag statement
containing just is
this true
one even
object. 11-e if we
cannot have
assign this a
bag collection
to variable 1 title. year, and length of each movie. -
that n-e are sure contains only
gvtv one element.
directly, because we OQL
n-ould provides
get a type the
error. operator
However. if xe ELEMENT
apply the
ovies m Line (1) sorts theIterate over the list
Movie class, placing theinresult
Fig. a
9.9. natural
into variableway movielist,
to turn a singleton collection into
ELEMENT its
operatorlone
first,member. This operator can be applied.
~vhosetype is List<Movie>. Line (2) computes
m.title = "Gone With the Wind"
for instance, to the result of a query that is known to return a singleton. Figure 9.9: the number
Exanlining of movies.
and printing using
each movie
the OQL operator COUNT. Lines (3) through ( 6 ) are a for-loop in which integer
gwtw = ELEMENT(SELECT m 1) movieList = SELECT m
Example 9.14 : Suppose we would like to FROMassign
Movies to m the variable gwtw. of type Line (1) sorts the Movie class, placing the result intoFROM variable Movies
movielist, m
Movie (i.e., the Movie class is its type) the object
WHERE m.titlerepresenting
= "Gone With the theWind"movie Gone ~vhosetype is List<Movie>. Line (2)computes the number ORDER BY using
of movies. m.ti
lllth the Wind. The result of the query 1; the OQL operator COUNT. Lines 2) (3)number0fMovies
through (6) are a for-loop in= which integer
~0UNT(Mo
3) for(i=O; i<numberOfMovies
SELECT m
FROM Movies m
4) movie = movieList 33 [i] ;
WHERE m.title = "Gone With the Wind" 5) cout << movie.title <
WHAT’S NEXT

•  First Approach: Object-Oriented Model


•  Concepts from OO programming languages
•  ODL: Object Definition Language
•  What about querying OO databases???
•  OQL: Object Oriented Query Language

•  Second Approach: Object-Relational Model

34
SECOND APPROACH: OBJECT-
RELATIONAL MODEL
•  Object-oriented model tries to bring the main
concepts from relational model to the OO domain
•  The heart is OO concepts with some extensions

•  Object-relational model tries to bring the main


concepts from the OO domain to the relational
model
•  The heart is the relational model with some extensions
•  Extensions through user-defined types

35
CONCEPTUAL VIEW OF OBJECT-
RELATIONAL MODEL
•  Relation is still the fundamental structure

•  Relational model extended with the following features


•  Type system with primitive and structure types (UDT)
•  Including set, bag, array, list collection types
•  Including structures like records
•  Methods
•  Special operations can be defined over the user-defined types
(UDT)
•  Specialized operators for complex types, e.g., images, multimedia,
etc.
•  Identifiers for tuples
•  Unique identifiers even for identical tuples
•  References
•  Several ways for references and de-references

36
ecord in this relation several addresses for the star. The schema for Stars can 4.5.3 References
e written:
The fact that movies like Star Wars will
Stars(name, address(street, city), birthdate, values of the movies attribute in the nest

CONCEPTUAL VIEW OF OBJECT-


movies(title, y .>r , length)) dancy. In effect, the schema of Example 4
not being in BCNF. However, decomposi
An exampl(s F a possible relation for nested relation Stars is shown in nate the redundancy. Rather, we need t o
all the movies relations, a movie appears

RELATIONAL MODEL
ig. 4.17. We srv in this relation two tuples, one for Carrie Fisher and one
or Mark Warnill. The valucs of components are abbreviated to conserve space, To cure the problem, object-relations n
nd the dashed lines separating tuples are only for convenience and have no to another tuple s: rather than incorpora
otational significance. our model an additional inductive rule: t
reference to a tuple with a given schema.

1
If an attribute .I has a type that is

1
riame address birthdate rnovies
I I

9/ 9/ 9 9
I

1 rifle 1 1 1 ~ ~ r ~ ~ ~ j
relation schema named R, we show the
Xotice that this situation is analogous to

mi
Fisher street city year
R; i.e., it connects to a single object of ty
r:-% Star Wars 1977 124 a type that is a set of references to tuple
in a schema as A({*R)).This situation re
•  Allow of nested relations
has type Set<R>.
. - - - - - - - - - - - - - - - - - -

E x a m p l e 4.24: An appropriate way to


•  Repeating movies
to use t inside theone
~ v orelations. stars
for stars and o
will be an ordinary relation ~viththe sam
- - - - -Wars
records is redundancy
Star - - - -1977
--- -124
--
Empire Example 4.23. The relation Stars xvill
- - - - - - - - - 1980
--- -127
--
Return 1983 133
relation Stars of that example. but the m
is a set of references to Movies tuples. T
Star(name, address(street, city), birthdate, •  To avoid redundancy,
thus: use pointers
Figure 4.17: A nested relation for stars and their movies
170 movies(title, year, length)) CH-dPTER 4. OTHER DATA MODELS(references) 4.5. THE OBJECT-RELAT
Movies (title, year, length)
In the Carrie Fisher tuple, we see her name. an atomic value, follo~ved Stars (name, address (street, ci
p a relation for the value of the address component. That relation has two .
interfaces, which are1essential
movies(i*Movies3>
on "Interfaces" in Section 4.3
\ of classes that inherit this in
that manner, ODL offers the
when it comes to sharing the

i r e did not discuss the use of


Movie However, in practice, the SQ
relational ideas allow the sam
Star associated with any37class.
SUPPORT FROM VENDORS

•  Several major software companies including IBM,


Informix, Microsoft, Oracle, and Sybase have all
released object-relational versions of their products

•  Extended SQL standards called SQL-99 or SQL3

38
SQL-99: QUERY LANGUAGE FOR OBJECT-
RELATIONAL MODEL
•  User-defied types (UDT) replace the concept of
classes

•  Create relations on top of the UDTs


•  Multiple relations can be created on top of the same UDT

Create Type <name> AS (attributes and method declarations)

39
CREATE TYPE T AS <attribute and method declarations> plied to objects.; In the definition of the method, ponent the portion
SELF refers to thisdevoted
tuple, ifto th
That is, the definition of a type T has the form
necessary. Example \-ere
component 9.21:'123 LetMaple
us exten St
as the formExample 9.20: ?Ve can create a type representing movie stars, analogous to Fig.
The 9.10
revised with
type a method
definition hous
is thu
the class Star CREATE foundTYPE inTthe AS OQL
<attribute
example andofmethod
Fig. 9.1.declarations>
Example
However, we ; cannot
9.21: Let us extend the definition ofponent the type the AddressType
portion devoted of to
represent directly a set of movies as a field within Star tuples. Thus, we shall Fig. 9.10 with a method houseNumber that extracts from
CREATE the street
TYPE
component \-ere '123 Maple S com-
AddressType

CREATING UDT
bute and method declarations> ; ponent the portion devoted to the house address. For revised
instance,
street if the street is th
CHAR(501,
Example
start with only9.20: the?Vename canand address
create a type components
representing of Star
movietuples.
stars, analogous to The type definition
theTo class
begin,Starnote foundthatin the the type
OQLofexamplean address of Fig. component
9.1. 9.1
in Fig. However,
is itselfwe \-ere '123
cannot
a tuple, Maple St. ', then houseNumber should
city return '123'.
CHAR(20)
ype representing movie stars, analogous to as aThus, The revised type definition is thus: CREATE1 TYPE AddressTy
represent
with directly street
components a set ofand movies
city. field we needStar
within two tuples. Thus, we one
type definitions, shall
example of
9.4.for Fig. 9.1.
USER-DEFZXED
start with only However,TYPES
name we IN cannot
SQL
andforaddress 451
Star tuples. streethouseNumber
METHOD CHAR(501,
addresses andthethe other stars. The components
necessaryofdefinitions are shown
CREATE TYPEinAddressType AS (
a field within Star tuples. Thus, we shall city CHAR(20)
9.10.
Fig. To begin, note that the type of an address in Fig. 9.1 is itself a tuple,
street CHAR(501,
ss components of Star tuples. We see the keyword
1 METHOD, follon
9.4.2with Methods
components User-Defined
instreet and city. TypesThus, we need two type definitions, city one CHAR(20)
f an address in Fig. 9.1 is itself a tuple, sized list of its arguments
METHOD houseNumbe and the
for addresses and the other for stars. The necessary definitions are1 shown in
The declaration
. Thus, we need of
two type
CREATE a method resembles
TYPEdefinitions,
AddressType the way
one AS ( a function in PSM is introdnced; but the parentheses are still nee
Fig. 9.10.
seenecessary
Section 8.2.1. There is no analog of PSI1 procedures as methods. That is, METHOD houseNumber () RETURNS CHAR(^^) ;
s. The definitions are shown in have
We seeappeared, follo~ved
the keyword by their
METHOD, foll
every method returns
street CHAR(~O),
a value of some type. While function Creating
declarations and a type for the address of
in PShf are
definitionsCREATE
city CHAR(20)
combined, a method needs both a declaration, stars
We see
within the the keyword METHOD, follon-edby the name ofsized the list of its
method
Separately, and
we
arguments
aneed
parnithe-
to
and t
define
); TYPE AddressType AS (
definition of its type, and a separate definition, in a CREATE METHOD statement. sized list of its arguments and their types. In this case, there are no arguments, ne
but the parentheses are still
street CHAR(~O), tion
have consists
appeared, of: follo~vedby thei
S ( X method declaration looks like a PSI1 function declaration, with the butkey-the parentheses are still needed. Had there bee11 arguments, they would
CREATE city TYPE StarType
CHAR(20) AS ( have appeared, follo~vedby their types. such as (a INT, b CHAR(^)). 0
word METHOD replacing CREATE FUNCTION. However, SQL methods typically 1.Separately,
The keywords CREATE
we need METH
to defin
) ; name CHAR(30) ,
have no arguments; they are applied to rows, just as ODL methods are Separately, ap- we need to define the metliod. -1simple tion consists of of:
formmethod method defini-
address AddressType 2. The name. argume
plied to objects. In the definition of the method, SELF refers to this tuple, tion if
consists of:
CREATE TYPE StarType AS (
necessary.) ; 1.asThein the declaration
keywords CREATE of theME
name CHAR(30) , A hierarchy of types
1. The keywords CREATE METHOD. 3.2.The
Example 9.21:address AddressType
Let us extend the definition of the type (inheritance)
AddressType of method FOR
Thekeyword name. andargum
tlic
Figure 9.10: Two type definitions declarcd.
Fig. 9.10 )with; a method houseNumber that extracts from the street com- 2. The method name. arguments and their types, and as the
in the declaration
RETURNS clause,of th
ponent the portion devoted to the house address. For instance, if the streetas in the declaration of the method. 4.3.The
h tuple
component \-ere of'123 AddressType
typeMaple has two components,
St. ', then houseNumber should returnwhose'123'.attributes are Thebody of theFOR
keyword method.
and tl
Figure 9.10: Two type definitions bodies of PSJI functions.
The street
revisedand typecity. Theistypes
definition thus: of these components are character3.strings of lengthFOR and tlic name of the UDT in declarcd.
The keyword which the method is
Two type50definitions
and 20, respectively. A tuple of type StarType also has tn-odeclarcd. components.
For instance,
4. The body we couldof thedefine
methodthe
hfirst
TheCREATE is TYPE
tuple attribute
type name,
of AddressType whose
AddressType AS ( type hasis two
a 30-character
components, string,
whoseand attributes
Addingthe second are
a is
method declaration
4. The body of the method. \vhich is ~vrittcnin the bodies same language
of PSJI as the
functions.
as two components,
address,
streetstreet
andwhosewhose
city. type attributes
The
CHAR(501,is itself
typesaof UDT
are theseAddressType.
components are thatcharacter
is, a tuple with of
strings street
length CREATE METHOD houseNmb
componentsand
50 andarecity
city character
20, components. strings of
respectively.
CHAR(20) C]Alength
tuple of type StarType also has tn-o components. for a
bodies type
of (not
PSJI definition)
functions.
FOR AddressType
type StarType
The first1also has tn-o components.
is attribute name, whose type is a 30-character string, (Encapsulation)
and the second is
For instance,
For instance, we could define the method houseNumber from Example 9.21 as:
we could define th
e is a 30-character
address, string,
whose
METHOD and the
type
houseNumber second
is itself a is
UDT AddressType.
() RETURNS CHAR(^^) ; that is, a tuple with street CREATE METHOD houseN
AddressType. that is, a
and city components. C]tuple with street CREATE
CHAPTER METHOD9.houseNmber RETURNS CHAR (10)
OBJECT-ORIENTATION
452 INFORQUERY
AddressTypeLANGU.4G
We see the keyword METHOD, follon-edby the name of the method and a parnithe-FOR AddressType
sized list of its arguments and their types. In this case, there are no arguments, BEGIN
but the parentheses are still needed. Had there bee11 arguments, they would .. .
E N D ;
have appeared, follo~vedby their types. such as (a INT, b CHAR(^)). 0 40
\Ve have omitted the body of the method because accomplishing the intend
separation of the string s t r i n g as intended is nontrivial, even in PSM.
COLLECTIONS AND LARGE OBJECTS

•  Book Type contains collections


•  Arrays of authors à capture the order of authors
•  Set of keywords
create type Book as

" (title varchar(20),

" author-array varchar(20) array [10],

" pub-date date,

" publisher Publisher,

" keyword-set setof(varchar(20)))"

•  Large object types


•  CLOB: Character large objects Usually provide methods inside
book-review CLOB(10KB) the UDT to manipulate CLOB &
•  BLOB: binary large objects BLOB
image BLOB(10MB)
movie BLOB(2GB)

41
necessary.
That is, the definition of a type T has the form
Example 9.21: Let us extend
Fig. 9.10 with a method houseN
CREATE TYPE T AS <attribute and method declarations> ;
CREATING RELATIONS
ponent the portion devoted to the
component \-ere '123 Maple St.
Example 9.20: ?Ve can create a type representing movie stars, analogous to The revised type definition is thus
the class Star found in the OQL example of Fig. 9.1. However, we cannot
represent directly a set of movies as a field within Star tuples. Thus, we shall CREATE TYPE AddressType
start with only the name and address components of Star tuples. street CHAR(501,
city CHAR(20)
•  Once types are created, we can create relations
To begin, note that the type of an address in Fig. 9.1 is itself a tuple,
1
with components street and city. Thus, we need two type definitions, one
METHOD houseNumber (
for addresses and the other for stars. The necessary definitions are shown in
Fig. 9.10.
We see the keyword METHOD, follon
sized list of its arguments and thei
In general,
• CREATE TYPE AddressType we
AS ( can create tables without types but the parentheses are still need
have appeared, follo~vedby their t
street CHAR(~O),
•  But types provide encapsulation, inheritance, etc.Separately, we need to define t
city CHAR(20)
);
tion consists of:
CREATE TYPE StarType AS (
1. The keywords CREATE METHO
CHAR(30) ,
name
address AddressType Create Table MovieStar OF StarType;
2. The method name. argumen
); as in the declaration of the
3. The keyword FOR and tlic
Figure 9.10: Two type definitions declarcd.

Howattributes
h tuple of type AddressType has two components, whose to define
are keys and 4. The body of the method. \v
bodies of PSJI functions.
street and city. The types of these components are character strings of length
50 and 20, respectively. A tuple of type StarType also has tn-orelationships???
components.
For instance, we could define the
The first is attribute name, whose type is a 30-character string, and the second is
address, whose type is itself a UDT AddressType. that is, a tuple with street CREATE METHOD houseNmb
and city components. C] FOR AddressType

42
1. The keywords CREATE TYPE, 9.4.2 Methods in User-Def
The declaration of a method resemble
2. A name for the type, see Section 8.2.1. There is no analog

CREATING RELATIONS
every method returns a value of som
3. The keyword AS, definitions in PShf are combined, a m
definition of its type, and a separate d
4. A parenthesized, comma-separated list of attributes and their types. X method declaration looks like a
454 CHAPTER 9. OBJECT-ORIENTATION IN QUERY LAXGU-AGES
word METHOD replacing CREATE FUNC
5. A comma-separated list of methods, including their argument ty pe(s) , have no arguments; they are applied
and return type. plied to objects. In the definition of
•  A single primary key can be defined using Primary Key
1) CREATE TYPE MovieType AS (
2 title CHAR(30) , necessary.
keyword
That is, the definition of a type T has the form
3,
4)
year INTEGER,
i n c o l o r BOOLEAN Example 9.21: Let us extend the
1; Fig. 9.10 with a method houseNumb
CREATE TYPE T AS <attribute and method 454 declarations> ;
CHAPTER 9. OBJECT-ORIENTATION IN QUERY ponentLAXGU-AGES
the portion devoted to the h
5) CREATE TABLE Movie OF MovieType ( component \-ere '123 Maple St. ',
•  To reference another relation R, R has to be referenceable
Example 9.20: ?Ve can create a type representing movie REF I S movieID SYSTEM GENERATED,
6)stars, analogous to The revised type definition is thus:
7) CREATEPRIMARY
using REF keyword
1) TYPE KEY ( t i t l eAS, y(e a r )
MovieType
the class Star found in the OQL example of Fig. 9.1. However, we cannot
represent directly a set of movies as a field within Star 2tuples.1;Thus, t i t l ewe shallCHAR(30) , CREATE TYPE AddressType AS
yearTuples INTEGER,
can be referenced using attributestreet CHAR(501,
start with only the name and address components of Star tuples.
454 CHAPTER 9. OBJECT-ORIENTATION IN QUERY4) 3,LAXGU-AGES i n c omovieID
l o r BOOLEAN 9.5. OPERATIONS ON cityOBJECT-RELATIONA
To begin, note that the type of an address in Fig. 9.11;is itselfFigure a tuple, 9.11:(system
Creating agenerated)
referenceable table CHAR(20)
with components street and city. Thus, we need two type definitions, one 1
for 1)
addresses
CREATEand theMovieType
other for stars.
AS ( The necessary definitions
* b) PersonType, with a namehouseNumber
METHOD of the person ()
andR
TYPE 5) CREATE
GENERATED" byare shownMovie
TABLE
"DERIVED," inthenOF newMovieType
tuples would ( get aretheir
theirvalue
mother of movieID
and father. You must use t
Fig.2 9.10. t i t l e CHAR(30) , by some REF I Sperformed
6) calculation, movieID by SYSTEM GENERATED,
the system, on the declaration.
values of the primary-key
year INTEGER, We see the keyword METHOD, follon-ed
attributes l e and y eKaErYfrom
7) t i t PRIMARY ( t i the
t l e ,same
y e atuple.
r)
3,
4) i n c o l o r BOOLEAN sized
c) MarriageType, list ofwithits arguments
the date ofand the their ty
marria
1;
CREATE
1; TYPE AddressType AS ( Example 9.25 : Now, let us see how to represent theband but Define
many-many
and the
wife. primary key
parentheses
relationship are still needed
street CHAR(~O), between movies Create and stars Movie usingtable have appeared,
references. Previously, we represented this follo~ved by their typ
Create
5) CREATE type
city TABLE for movies
Movie OF MovieType (
CHAR(20) Figure 9.11: Creating a Exercise
referenceable 9.4.2:
table
relationship by a relation like S t a r s I n that contains tuples with the keys of Redesign our running produc
6) ) ; REF I S movieID SYSTEM GENERATED, Movie and MovieStar. As an alternative, wecise may5.2.1 Separately,
to use
define S t atype to we
haveneed and
r s I ndeclarations to define the
reference
7) PRIMARY KEY ( t i t l e , y e a r ) references to tuples from these-two relations. In particular,
tion in the
consists relations
of: PC: Laptop, and
GENERATED" by "DERIVED," then new tuples would get be
their value of movieID
1; First, we need to redefine MovieStar so it istribute a reference
a referenceable to the Product tuple for th
table, thusly:
CREATE TYPE StarType AS ( by some calculation, performed by the system, on the values of1.the primary-key
The keywords CREATE METHOD.
name CHAR(30) , attributes and yMovieStar
t i t l eTABLE
CREATE e a r from the OFsame tuple.
StarType ! Exercise
( Referenceable,
9.4.3: In Exercise 9.4.2 but no
we suggested
address AddressType
Figure 9.11: Creating a referenceable table REF I S s t a r I D SYSTEM GENERATED tables PC, primary key
2.
Laptop, The method
and P r i n t name.
e r arguments
could be refere
Example 9.25 : Now, let us see how to represent the many-many
table. Is it also possible relationship
); 1; as in thetodeclaration
make the model of theattrib
me
between movies and stars using references. Previously, the tuple inwetherepresented
relation forthis that type of product
GENERATED" by "DERIVED," then new tuples would get their
Create type for stars
value
Then,Create
relationshipofby
we a
movieID
may MovieStar
relation
declarelike
the S t a table
r s
relation I n that
S t a r scontains
I n to havetuples
two with thekeyword
attributes,
3. The keys
~vhich 43 tlic na
of FOR and
by some calculation, performed by the system, on the are references, one to a movie tuple and one*toExercise
Movie
values
Figure 9.10: Two type definitions of and
the MovieStar.
primary-key As an alternative, we may define
a star tuple. S
9.4.4:t a
Herer s I n to have
is a direct
Redesign
declarcd. our running battlesh
GENERATED" by "DERIVED," then new tuples would get their value of movieID
by some calculation, performed by the system, on the values of the primary-key
attributes t i t l e and y e a r from the same tuple.

DEFINING RELATIONSHIPS Example 9.25 : Now, let us see how to represent the many-many relationship
between movies and stars using references. Previously, we represented this
relationship by a relation like S t a r s I n that contains tuples with the keys of
Movie and MovieStar. As an alternative, we may define S t a r s I n to have
9.1. USER-DEFINED TYPES IAr SQL 453to tuples from these-two relations.
references
•  One-to-many Or one-to-one First, we need to redefine MovieStar so it is a referenceable table, thusly:
•  Plug it Ainside the existing types
REF(T) SCOPE R
CREATE TABLE MovieStar OF StarType (
If no scope is specified, the reference can go to any relation of type T
REF I S s t a r I D SYSTEM GENERATED
•  Many-to-many
ExampIe 9.23 : Reference attributes are not sufficient to record in MovieStar1;
the set of all movies they starred in, but they let us record the best movie for
each star. Assume•  Create
that we have a newa relation
declared typeMovie, or new
and thattable
theThen, referencing
we may declare theexisting
type of relation S t a types
r s I n to have two attributes, ~vhich
this relation is the UDT MovieType; we shall define both MovieTypeare andreferences,
Movie one to a movie tuple and one to a star tuple. Here is a direct
later, in Fig. 9.11. The following is a new definition of StarType that includes
a11 attribute bestMovie that is a reference to a movie. definition of this relation:

CREATE TYPE StarType AS ( CREATE TABLE S t a r s I n (


name CHAR(30) , star REF(StarType1 SCOPE MovieStar,
address AddressType, movie REF(MovieType1 SCOPE Movie
bestMovie REF(MovieType) SCOPE Movie
>;
1;
Sow, if For Table
star wefor
Optionally, each
could have star participated
defined inand then declared S t a r s I n
a UDT as above,
each
relation star, keep
MovieStar the
is defined to have the UDT above, then each
best movie (one-many) be which
tuple will have a component that refers to a Movie tuple - thetostar's table ofmovies
a best that type.(many-many)
movie.
9.4.5
S e s t , n-e must arrange that a table such as Movie in Example 9.23 Exercises for Section 9.4
will have
a reference column. Such a table is said to be referenceable. In a CREATE TABLE
statement n-here the type of the table is a UDT (as in SectionSCOPE points
Exercise
9.4.3), we Write type declarations
to a:‘referenceable’
may9.4.1 tablefor the following types:
append a clause of the form:
a) NameType, with components for first, middle, and last names and a title.
REF IS tattribute name> <how generated,

The attribute name is a name given to the column that will serve as an "object
identifier" for tuples. The .-how generated" clause is typically either: 44
WHAT’S NEXT

•  First Approach: Object-Oriented Model


•  Concepts from OO programming languages
•  ODL: Object Definition Language
•  What about querying OO databases???
•  OQL: Object Oriented Query Language

•  Second Approach: Object-Relational Model


•  Conceptual view
•  Data Definition Language (Creating types, tables, and
relationships)
•  Querying object-relational database (SQL-99)

45
QUERYING OBJECT-RELATIONAL
DATABASE
•  Most relational operators work on the object-
relational tables
•  E.g., selection, projection, aggregation, set operations

•  Some new operators and new syntax for some


existing operators

•  SQL-99 (SQL3): Extended SQL to operate on object-


relational databases

46
CREATE TYPE9.MovieType AS (
* b) PersonType, with a name of the person and references to
454 1) CHAPTER OBJECT-ORIENTATION IN QUERY LAXGU-AGES theirOPERATIONS
9.5.
are ON OBJECT-RELATIONAL
mother and father. You must use the type from
2 t i t l e CHAR(30) , declaration.
year INTEGER, * b) PersonType, with a name of the person and ref
3,
4) 1)
2 1;
CREATE
title
year
TYPE MovieType AS (
i n c o l o r BOOLEAN
CHAR(30) ,
INTEGER,
EXAMPLES I band and
are theirwith
c) MarriageType,
wife.
the date
mother
declaration.
of the marriage
and father. You must and
userefere
the

54 3,CHAPTER
454 5) 4) CHAPTER i n c 9.
o 9.
l o OBJECT-ORIENTATION
r OBJECT-ORIENTATION
BOOLEAN
CREATE TABLE Movie OF MovieType ( ININQUERY
QUERYLAXGU-AGES
LAXGU-AGES Exercise9.5. 9.5.
9.4.2:
c) OPERATIONS
OPERATIONS
Redesign our
MarriageType, ON
withON OBJECT-RELATIONA
running
theOBJECT-RELATIONA
date products
of the database
marriage
6) 1;REF I S movieID SYSTEM GENERATED, cise 5.2.1 to use type declarations and reference attributes wh
band and wife.
7) PRIMARY KEY ( t i t l e , yAeSa r )( In particular,**b)b) inPersonType,
the relationswith
PersonType, PC: aaLaptop,
with name
name of ofand
the
thePperson mak
r i n t e r and
person and
1) CREATE
1)5) CREATETYPE TYPEMovieType
MovieType AS ( Exercise 9.4.2: Redesign our running products
CREATE
.1. USER-DEFINED
2 6) 1; t i t l
TABLE
e
TYPESMovieIArOFSQL
CHAR(30) ,
MovieType (
Q1: 453
Find the year of movie
tribute
cise ‘King
be a
5.2.1
are
reference
toKong’
their
are their to mother
mother and father. You must use tt
the Productand father.
tuple
use type declarations and reference att
forYouthat must
model. use
2 t i t lIeS movieID
REF CHAR(30) ,
SYSTEM GENERATED, declaration.
declaration.
7) year
year
PRIMARY INTEGER,
KINTEGER,
EY ( t i t l e , y e a r ) ! Exercise In 9.4.3:
particular, in the relations
In Exercise PC: Laptop,
9.4.2 we suggested thatand modelPr
4)3, 1; iFigure
3,4) ni cnoc lool ro rBOOLEANA REF(T) SCOPE R tribute c) MarriageType,
be a reference towith
the the
Product date of
tuplethe formarria
that
9.11:BOOLEAN
Creating a referenceable table c) MarriageType, with
tables PC, Laptop, and P r i n t e r could be references to tuplesthe date of the marria
1 ;1;
f no scope is specified, the reference can go to any relation of type T Select m.year table. Is it alsoband band
possible and
and towife.
wife.
make the model attribute in Produ
! Exercise 9.4.3: In Exercise 9.4.2 we suggested th
TABLE9.11:
Figure Creating From Movie m the tupletables in thePC,relation
Exercise 9.4.2: for that
9.4.2: and
Laptop, Ptype
Redesign r i n tofeour
rproduct?
running
could beWhy or wh
produc
reference
GENERATED"
ExampIe 5)5) CREATE
by
9.23 TABLE
"DERIVED,"
CREATE : Reference Movie
thenMovie new
attributes OFOFtuples areawould
MovieType referenceable
MovieType
not get( (theirto
sufficient table
value
record of movieID
in MovieStar Exercise Redesign our running produc
yhesome 6)6)
set calculation,
of all movies REF REF Ithey
SI SmovieID
performed movieID by theSYSTEM
starred in,system,
SYSTEM but they GENERATED,
on theletvalues
GENERATED, us recordof thethe primary-key
best movie Where
for m.title *=Exercise
‘King table.
cise Kong’;
cise
9.4.4:
Is it also
5.2.1
5.2.1 to
to use
Redesign
possible
use type
type to
our running
make the model
declarations
declarations and
battleships
attribute
and reference
reference
database
theIn tuple in
particular, the relation
in the for
relationsthat type
PC: of product?
Laptop, and WP
ach 7)
ttributes 7)t iAssume
star.
GENERATED" e PRIMARY
t l by and y e a rwe
that
PRIMARY
"DERIVED," KEKY
from have
EY ( t(declared
the
then itsame
tnew
i lt el e, tuples
,y yeaaerelation
tuple. ra)rwould
) Movie,
get their andvaluethat of themovieID
type of cise 5.2.4 In particular,
to use in the relations
type declarations and reference PC: Laptop,
attributes and wh
tribute
tribute be aareference toto the
the Product tuple for
for th
his relation
by some 1;1; is the UDT
calculation, MovieType;
performed by the wesystem,
shall define on the both MovieType
values and Movie
of the primary-key *
The schemaExercise from be Exercise reference
9.4.4: Redesign 9.1.3 should Productwhere
oursuggest
tuplereferen
running battleships
th
Example
ater, 9.259.11.
in Fig. : Now, The lety following
us see howistoasame represent
new definition the many-many
of StarType relationship
that includes useful. !cise
Look for many-one
attributes
etween movies
t i t l e and
and stars
e a r from the
using references.
tuple.
Previously, we represented this Variable m is important !to reference
5.2.4
Exercise
Exercise to 9.4.3:
use
9.4.3: therelationships
type Infields
In Exercise 9.4.2
declarations
Exercise andandtry
9.4.2 we
we tosuggested
referencerepresen
suggested att
a11 attribute bestMovie that is a reference to a movie. attribute with a reference type.
elationship Figure
Figure 9.11:
9.11: Creating
a Creating a areferenceable
referenceable table
table Thetables
tablesschema PC, from
PC, Laptop,
Laptop, and PP9.1.3
Exercise
and rriinntteeshould
rr could
could suggest
be
be referen
referewhe
Example by 9.25 a relation
: Now, let like usS tsee I n that
r show contains
to represent tuples with the keys
the many-many of
relationship useful. Look for many-one relationships and try to
CREATE TYPE table. Is it also possible to
table. Is it also possible to make the model attribmake the model attrib
Movie
betweenand MovieStar.
movies andStarType As anusing
stars AS references.
alternative,( we may define S twe
Previously, I n to have this
a r srepresented attribute
the tuple with
in a
the reference
relation type.
for that type of product?
toname CHAR(30) ,new the tuple in the relation for that type of product
eferences
relationship
GENERATED"
GENERATED" tuples
byby
address
from
a"DERIVED,"
relation
by"DERIVED," these-two like
then
AddressType,
thenSrelations.
t anewr s Ituples that would
ntuples contains
wouldget gettuples
their with
theirvaluevaluetheofQ2: keys
ofmovieID of
Find
movieID the title of 9.5 best
the Operations
movie ’Jim onCarry’Object-Relational
yMovie
First,
bysome
some and MovieStar.
wecalculation,
need
calculation,
bestMovie
to redefine
performed
performedAs
REF(MovieType)
anbyby
MovieStar alternative,
the the it is a we
sosystem,
system,
SCOPE Movie
ononmay
referenceable
the define
thevalues
values ofSofthe
table, t the
athusly:n to have
r sprimary-key
Iprimary-key ** Exercise
Exercise 9.4.4: Redesign our
9.4.4: Redesign our running
running battleshi
battlesh
references
ttributes t to
i t ltuples
e and from
y e a r these-two
from
attributes t i t l e and y e a r from the same tuple. the relations.
same tuple. -111 9.5
appropriate 5.2.4Operations
SQL operations
cise 5.2.4 to use type declarations and
cise to use type from onprevious
declarations Object-Rela
chapters
and reference apply t
>
CREATE
; weTABLE
First, need to MovieStar
redefine MovieStar OF StarType so it( is a referenceable table, thusly:
Select s.bestMovie->title declared The with a
The schema UDT
schemafrom or that have attributes
Exercise9.1.3
from Exercise 9.1.3 should whose
reference
type
should suggest
suggest is aw w
Example
Example REF9.259.25I S: sNow,a r I Dletlet
:tNow, usussee
SYSTEM howhowtotorepresent
seeGENERATED representthe themany-many
many-manyrelationship relationship also some-111 appropriate
entirely
useful. new
Look SQL
operations
for operations
many-one we can from
use, previous
such
relationships as chapt
reference
and try
useful. Look for many-one relationships and try
Sow, ifCREATE
between
between
uple
relationTABLE
1;willmovies
movies
have a
MovieStar
and and MovieStar
stars
component starsusing
is defined
using
that
OF
references.
to have the
StarType
references.
refers to a
( UDT above,
Previously,
Previously,
Movie tuple
wewe
-
represented
represented
the
From
then each star
star's best this MovieStar ever,
this s some declaredfamiliar
attribute
attribute
with a UDT orespecially
operations.
with
with aa reference
that have
reference type.
attributes whose
type.those that access or
REF I S s t a r I D SYSTEM GENERATED also is a UDT, involve new syntax. can use, such a
some entirely new operations we
elationship
movie.Then,
Movieand
Movie 1; we
by
may
a relation
declare
MovieStar. As
andMovieStar. the
like S
relation
t a
Asananalternative,
r
S
s I
relationship by a relation like S t a r s I n that contains tuples with the
t
n
a
alternative,wer
that
s I n to
contains
have
wemay two
tuples
maydefine
with
attributes,
the
Where
~vhich
keys of s.name =\\-hose
keys
defineSSt at ar sr sI Inntotohave
of
have
‘Jim type Carry’;
ever, some familiar operations. especially those that
rereferences
references, one toarrange
afrommovie tuple and one to a Movie star tuple. Here is 9.23a direct 9.5typeOperations
9.5
\\-hose is a UDT, involveon new Object-Re
syntax.
References on Object-Re
Operations
eferences tototuplestuples from these-two
these-two relations.
relations.
SThen,
e s t , n-ewemust may declare that a table
the relation S t a ras
such s I n to have in Example
two attributes, will~vhich
have 9.5.1 Following
efinition
First,
First,of
we this
we need relation:
need to redefine MovieStar so it is a referenceable table, thusly:
a arereference
references, column. one to Such
to redefinea table
a movie MovieStar
is said
tuple and toso beitreferenceable.
one tois aa star
referenceable
tuple. In aHere table,
CR EAisTEathusly:
TABLE
direct -111
tatement
definition n-here
of this the type
relation: of the table is a UDT (as in Section 9.4.3), we may Suppose9.5.1 x-111isappropriate
aappropriate
Following
value of type SQL
SQL operations
operations
References
REF(T). Thenfrom from
x refersprevious
previous
to some cha
cht
CREATE
CREATE
CREATE TABLE
TABLE
append a clause of the form: TABLE S t a r s
MovieStarI n
MovieStar ( OFOFStarTypeStarType (( Follow
declared
declared a reference
with
with aa UDT
UDT (pointer)
or
or
We can obtain tuple t itself, or components of t: by two meanthat
that have
have attributes
attributes who
wh
sREF
t aREF I SI SREF(StarType1
r TABLE s tsat raIrD SYSTEMSCOPE GENERATED MovieStar, Suppose
usingalso
alsosomeà xoperator
isentirely
a valuenew of type REF(T).
operations weThen
we can
can use,x refers
such
CREATE S t aI D r s ISYSTEM
n ( GENERATED some entirely new operations use, suc
1;1;movie star R EREF(MovieType1
F IS tattribute
REF(StarType1 SCOPE MovieStar, SCOPE
name> Movie <how generated, 1. Operator -> has essentially the same meaning as this by
We ever, can
ever, obtain
some
some tuple
familiar
familiar t itself,
operations.
operations. or components
especially
especially of t:
those
those opth
t
1; \\-hose type is a UDT, involve new syntax.
TheThen, Then,wewemay
attribute
movie declare
may declare
name
REF(MovieType1
is a name the relation
thegivenrelation to the
SCOPE Moviehave two attributes, ~vhich
ar sr Is nI ntoto
S St at column thathavewilltwoserve attributes,
as an "object ~vhich
That\\-hose if type
1.is,Operator ->a UDT,
x is aisreference involve
to
has essentiallya tuplenew the
syntax.
t. same
and is an att
47a meaning
re 1; we x->a is the value of the attribute n
That is, if x is a reference to a tuple t. and a in tuple t.
arereferences,
dentifier"
Optionally, forcould
references, one
tuples. totoThe
onehave a adefined
movie .-how
movie tuple
UDTand
generated"
a tuple one
andabove,
as one toto
clause anda ais
star tuple.
typically
star
then Here
tuple.either:
declared S t a rissisIanadirect
Here direct
CREATE TYPE9.MovieType AS (
* b) PersonType, with a name of the person and references to
454 1) CHAPTER OBJECT-ORIENTATION IN QUERY LAXGU-AGES theirOPERATIONS
9.5.
are ON OBJECT-RELATIONAL
mother and father. You must use the type from
2 t i t l e CHAR(30) , declaration.
year INTEGER, * b) PersonType, with a name of the person and ref
3,
4) 1)
2 1;
CREATE
title
year
TYPE
EXAMPLES II: DE-REFERENCING
MovieType AS (
i n c o l o r BOOLEAN
CHAR(30) ,
INTEGER,
band and
are theirwith
c) MarriageType,
wife.
the date
mother
declaration.
of the marriage
and father. You must and
userefere
the

54 3,CHAPTER
454 5) 4) CHAPTER i n c 9.
o 9.
l o OBJECT-ORIENTATION
r OBJECT-ORIENTATION
BOOLEAN
CREATE TABLE Movie OF MovieType ( ININQUERY
QUERYLAXGU-AGES
LAXGU-AGES Exercise9.5. 9.5.
9.4.2:
c) OPERATIONS
OPERATIONS
Redesign our
MarriageType, ON
withON OBJECT-RELATIONA
running
theOBJECT-RELATIONA
date products
of the database
marriage
6) 1;REF I S movieID SYSTEM GENERATED, cise 5.2.1 to use type declarations and reference attributes wh
band and wife.
7) PRIMARY KEY ( t i t l e , yAeSa r )( In particular,**b)b) inPersonType,
the relationswith
PersonType, PC: aaLaptop,
with name
name of ofand
the
thePperson mak
r i n t e r and
person and
1) CREATE
1)5) CREATETYPE TYPEMovieType
MovieType AS ( Exercise 9.4.2: Redesign our running products
CREATE
.1. USER-DEFINED
2 6) 1; t i t l
TABLE
e
TYPESMovieIArOFSQL
CHAR(30) ,
MovieType (
Q3: 453
Find movies starred by
tribute
cise ‘Jim
be a areCarry’
are
reference
5.2.1
their
their mother and father. You must use tt
to mother
the Productand father.
tuple
to use type declarations and reference att
forYouthat must
model. use
2 t i t lIeS movieID
REF CHAR(30) ,
SYSTEM GENERATED, declaration.
declaration.
7) year
year
PRIMARY INTEGER,
KINTEGER,
EY ( t i t l e , y e a r ) ! Exercise In 9.4.3:
particular, in the relations
In Exercise PC: Laptop,
9.4.2 we suggested thatand modelPr
4)3, 1; iFigure
3,4) ni cnoc lool ro rBOOLEANA REF(T) SCOPE R tribute c) MarriageType,
be a reference towith
the the
Product date of
tuplethe formarria
that
9.11:BOOLEAN
Creating a referenceable table c) MarriageType, with the
tables PC, Laptop, and P r i n t e r could be references to tuples date of the marria
1 ;1;
f no scope is specified, the reference can go to any relation of type T Select DEREF(movie)
table. Is it alsoband band
possible and
and towife.
wife.
make the model attribute in Produ
! Exercise 9.4.3: In Exercise 9.4.2 we suggested th
TABLE9.11:
Figure Creating From StarsIn the tupletables in thePC,relation
Exercise 9.4.2: for that
9.4.2: and
Laptop, Ptype
Redesign r i n tofeour
rproduct?
running
could beWhy or wh
produc
reference
GENERATED"
ExampIe 5)5) CREATE
by
9.23 TABLE
"DERIVED,"
CREATE : Reference Movie
thenMovie new
attributes OFOFtuples areawould
MovieType referenceable
MovieType
not get( (theirto
sufficient table
value
record of movieID
in MovieStar Exercise Redesign our running produc
yhesome 6)6)
set calculation,
of all movies REF REF Ithey
SI SmovieID
performed movieID by theSYSTEM
starred system,
SYSTEM
in, but they GENERATED,
on theletvalues
GENERATED, us recordof thethe primary-key
best movie Where
for star->name
* Exercise =cise
table. ‘Jim
cise
9.4.4:
Is it Carry’;
5.2.1
5.2.1 also
toto use
Redesign
possible
use type
type to
our running
make the model
declarations
declarations and
battleships
attribute
and reference
reference
database
the
In tuple in
particular, the relation
in the for
relationsthat type
PC: of product?
Laptop, and WP
ach 7)
ttributes 7)t iAssume
star.
GENERATED" e PRIMARY
t l by and y e a rwe
that
PRIMARY
"DERIVED," KEKY
from have
EY ( t(declared
the
then itsame
tnew
i lt el e, tuples
,y yeaaerelation
tuple. ra)rwould
) Movie,
get their andvaluethat of themovieID
type of cise 5.2.4 In particular,
to use in the relations
type declarations and reference PC: Laptop,
attributes and wh
tribute
tribute be aareference toto the
the Product tuple for
for th
his relation
by some 1;1; is the UDT
calculation, MovieType;
performed by the wesystem,
shall define on the both MovieType
values and Movie
of the primary-key *
The schema Exercise from be Exercise reference
9.4.4: Redesign 9.1.3 should Productwhere
oursuggest
tuplereferen
running battleships
th
Example
ater, 9.259.11.
in Fig. : Now, The lety following
us see howistoasame represent
new definition the many-many
of StarType relationship
that includes useful.
attributes
etween movies
t i t l e and
and stars
e a r from the
using references.
tuple.
Previously, we represented this DEREF: Get the tuple pointed!Look
!cise
Exercise
Exercise for
5.2.4to many-one
by
to the
use
9.4.3:
9.4.3: type relationships
given pointer
Indeclarations
In Exercise
Exercise andandtry
9.4.2
9.4.2 tosuggested
reference
we
we represen
suggested att
a11 attribute bestMovie that is a reference to a movie. attribute with a reference type.
elationship Figure
Figure 9.11:
9.11: Creating
a Creating a areferenceable
referenceable table
table The
tables schema
tables PC, from
PC, Laptop,
Laptop, and PP9.1.3
Exercise
and rriinntteeshould
rr could
could suggest
be
be referen
referewhe
Example by 9.25 a relation
: Now, let like usS tsee I n that
r show contains
to represent tuples with the keys
the many-many of
relationship useful. Look for many-one relationships and try to
CREATE TYPE table. Is it also possible to make
table. Is it also possible to make the model attrib the model attrib
Movie
betweenand MovieStar.
movies andStarType As anusing
stars AS references.
alternative,( we may define S twe
Previously, I n to have this
a r srepresented attribute
the tuple with
in a
the reference
relation type.
for that type of product?
toname CHAR(30) ,new the tuple in the relation for that type of product
eferences
relationship
GENERATED"
GENERATED" tuples
byby
address
from
a"DERIVED,"
relation
by"DERIVED," these-two like
then
AddressType,
thenSrelations.
t anewr s Ituples that would
ntuples contains
wouldget gettuples
their with
theirvaluevaluetheQ4: Find
keys
ofofmovieID
movieIDof movies starred 9.5 byOperations ‘Jim Carry’ on (AnotherObject-Relational way)
yMovie
First,
bysome
some and MovieStar.
wecalculation,
need
calculation,
bestMovie
to redefine
performed
performedAs
REF(MovieType)
anbyby
MovieStar alternative,
the the it is a we
sosystem,
system,
SCOPE Movie
ononmay
referenceable
the define
thevalues
values ofSofthe
table, t the
athusly:n to have
r sprimary-key
Iprimary-key * * Exercise
Exercise 9.4.4: Redesign our running
9.4.4: Redesign our running battleshi
battlesh
references
ttributes t to
i t ltuples
e and from
y e a r these-two
from
attributes t i t l e and y e a r from the same tuple. the relations.
same tuple. -111 9.5
appropriate 5.2.4Operations
SQL operations
cise 5.2.4 to use type declarations and
cise to use type from onprevious
declarations Object-Rela
chapters
and reference apply t
>
CREATE
; weTABLE
First, need to MovieStar
redefine MovieStar OF StarType so it( is a referenceable table, thusly: declared The with a UDT or that have attributes whose
reference
type is aw
Example
Example REF9.259.25I S: sNow,a r I Dletlet
:tNow, usussee
SYSTEM howhowtotorepresent
seeGENERATED representthe themany-many
many-manyrelationshipSelect
relationship some
The schema
s.movie->title,alsos.movie->year,
-111 entirely
useful.
schemafrom
appropriate new
Look
from
SQL
operations
for
Exercise9.1.3
Exercise
s.movie->inColor,
operations
many-one we can
9.1.3 should
from
use,
should suggest
previous
such
relationships as
suggest
chapt
reference
and try
w
Sow, ifCREATE relationTABLE MovieStar is defined to have the ( UDT above, then each star useful. Look for many-one relationships and try
between
uple 1;willmovies
between movies
have
REF
and
a
I S
and MovieStar
stars
component
s t a
starsusing
r I D
using
that
SYSTEM
OF StarType
references.
references.
refers
GENERATED to a
Previously,
Previously,
Movie tuple
wewe
- the From
represented
represented
star's best StarsIn s
this
this ever, some declared
familiar
attribute
attribute
with a UDT orespecially
operations.
with
with aa reference
that have
reference type.
attributes whose
type.those that access or
elationship by a relation like S t a r s I n that
relationship by a relation like S t a r s I n that contains tuples with the keys of contains tuples with the keys of \\-hosetype is a UDT, involve new syntax. can use, such a
also some entirely new operations we
movie.Then,
Movieand
Movie 1; we may declare
MovieStar. As
andMovieStar. the relation
Asananalternative, S t a
alternative,wer s I n to have
wemay two
maydefine attributes, Where
~vhich
defineSSt at ar sr sI Inntotohave have s.star->name = ever,
‘Jim some Carry’;
familiar operations. especially those that
rereferences
references, one toarrange
afrommovie tuple and one to a Movie star tuple. Here is 9.23a direct 9.5typeOperations
9.5
\\-hose is a UDT, involveon new Object-Re
syntax.
References on Object-Re
Operations
eferences tototuplestuples from these-two
these-two relations.
relations.
SThen,
e s t , n-ewemust may declare that a table
the relation S t a ras
such s I n to have in Example
two attributes, will~vhich
have 9.5.1 Following
efinition
First,
First,of
we this
we need relation:
need to redefine MovieStar so it is a referenceable table, thusly:
a arereference
references, column. one to Such
to redefinea table
a movie MovieStar
is said
tuple and toso beitreferenceable.
one tois aa star
referenceable
tuple. In aHere table,
CR EAisTEathusly:
TABLE
direct -111
Suppose9.5.1 isappropriate
x-111 aappropriate
Following SQL
SQL operations
operations
References Thenfrom from previous
previous cha
cht
tatement
definition
CREATE
CREATE
CREATE
n-here
of this
TABLE
TABLE
append a clause of the form:
the
TABLE S t
type
relation:a r s
MovieStarI
of
n
MovieStar (
the table
OFOFStarType
is a
StarType
UDT
((
(as in Section 9.4.3), we
***may
Using a variable for
declared
declaredStartsIn
value
with
of type
with aa (s
UDT
UDT in
REF(T).
or
or Q4)
that
We can obtain tuple t itself, or components of t: by two meanthat is
have
have not
x refers
attributes
to some
attributes who
wh
sREF
CREATE
t aREF I SI SREF(StarType1
r TABLE s tsat raIrD
S t aI D
SYSTEMSCOPE
r s ISYSTEM
n (
GENERATED MovieStar,
GENERATED necessary because theSuppose table
also
also some
some is not
x isentirely
a valuenew
entirely newbased
of type REF(T).
operations
operations on we type.
weThen
can
can use,x refers
use, such
suc
1;1;movie star R EREF(MovieType1
F IS tattribute
REF(StarType1 SCOPE MovieStar, SCOPE
name> Movie <how generated, 1. Operator -> has essentially the same meaning as this by
Weever, can
ever, obtain
some
some tuple
familiar
familiar t itself,
operations.
operations. or components
especially
especially of t:
those
those opth
t
1; \\-hose type is a UDT, involve new syntax.
TheThen, Then,wewemay
attribute
movie declare
may declare
name
REF(MovieType1
is a name the relation
thegivenrelation to the
SCOPE Moviehave two attributes, ~vhich
ar sr Is nI ntoto
S St at column thathavewilltwoserve attributes,
as an "object ~vhich
That\\-hose if type
1.is,Operator ->a UDT,
x is aisreference involve
to
has essentiallya tuplenew the
syntax.
t. same
and is an att
48a meaning
re 1; we x->a is the value of the attribute n
That is, if x is a reference to a tuple t. and a in tuple t.
arereferences,
dentifier"
Optionally, forcould
references, one
tuples. totoThe
onehave a adefined
movie .-how
movie tuple
UDTand
generated"
a tuple one
andabove,
as one toto
clause anda ais
star tuple.
typically
star
then Here
tuple.either:
declared S t a rissisIanadirect
Here direct
CREATE TYPE9.MovieType AS (
* b) PersonType, with a name of the person and references to
454 1) CHAPTER OBJECT-ORIENTATION IN QUERY LAXGU-AGES theirOPERATIONS
9.5.
are ON OBJECT-RELATIONAL
mother and father. You must use the type from
2 t i t l e CHAR(30) , declaration.
year INTEGER, * b) PersonType, with a name of the person and ref
3,
4) 1)
2 1;
CREATE
title
year
TYPE
CHAR(30) , EXAMPLES III: COMPARISON
MovieType AS (
i n c o l o r BOOLEAN

INTEGER,
band and
are theirwith
c) MarriageType,
wife.
the date
mother
declaration.
of the marriage
and father. You must and
userefere
the

54 3,CHAPTER
454 5) 4) CHAPTER i n c 9.
o 9.
l o OBJECT-ORIENTATION
r OBJECT-ORIENTATION
BOOLEAN
CREATE TABLE Movie OF MovieType ( ININQUERY
QUERYLAXGU-AGES
LAXGU-AGES Exercise9.5. 9.5.
9.4.2:
c) OPERATIONS
OPERATIONS
Redesign our
MarriageType, ON
withON OBJECT-RELATIONA
running
theOBJECT-RELATIONA
date products
of the database
marriage
6) 1;REF I S movieID SYSTEM GENERATED, cise 5.2.1 to use type declarations and reference attributes wh
band and wife.
7) PRIMARY KEY ( t i t l e , yAeSa r )( **b)b) inPersonType,
In particular, the relationswith
PersonType, PC: aaLaptop,
with name
name of ofand
the
thePperson mak
r i n t e r and
person and
1) CREATE
1)5) CREATETYPE TYPEMovieType
MovieType AS ( Exercise 9.4.2: Redesign our running products
CREATE
.1. USER-DEFINED
2 6) 1; t i t l
TABLE
e
TYPESMovieIArOFSQL
CHAR(30) ,
MovieType (
Q5: 453
Find distinct movies starred
tribute be a
cise 5.2.1
areby
are
reference
to use‘Jim
their to mother
the
their mother Carry’
Productand
and father. You must use tt
type declarations
father.
tuple forYouthat must
model.
and reference att
use
2 t i t lIeS movieID
REF CHAR(30) ,
SYSTEM GENERATED, declaration.
7) year
year
PRIMARY INTEGER,
KINTEGER,
EY ( t i t l e , y e a r )
or ‘Mel Gibson’ ! Exercise In 9.4.3:
declaration.
particular, in the relations
In Exercise PC: Laptop,
9.4.2 we suggested thatand modelPr
4)3, 1; iFigure
3,4) ni cnoc lool ro rBOOLEANA REF(T) SCOPE R tribute c) MarriageType,
be a reference towith
the the
Product date of
tuplethe formarria
that
9.11:BOOLEAN
Creating a referenceable table c) MarriageType, with the
tables PC, Laptop, and P r i n t e r could be references to tuples date of the marria
1 ;1;
f no scope is specified, the reference can go to any relation of type T table. Is it alsoband band
possible and
and towife.
wife.
make the model attribute in Produ
Select Distinct DEREF(movie)
! Exercise 9.4.3: In Exercise 9.4.2 we suggested th
the tuple in thePC,relation
Exercise
tables 9.4.2: for that Ptype
Redesign r i n tofeour
rproduct?
runningbeWhy or wh
produc
GENERATED"5)5) CREATE
by TABLE9.11:
Figure
TABLE
"DERIVED," Movie
then Creating
new OFOF areawould
MovieType
tuples referenceableget( (theirto table
value of movieID Exercise 9.4.2: and
Laptop, Redesign our couldrunning reference
produc
ExampIe
yhesome 6)6)
set
CREATE
9.23
calculation,
of all movies
: Reference
REF REF Ithey
SI SmovieID
performed
Movie
attributes
movieID by theSYSTEM
starred system,
SYSTEM
in,
MovieType
but they
not
GENERATED,
on
sufficient
theletvalues
GENERATED, us record
record
of thethe
in MovieStar
primary-key
best movie for
From StarsIn * Exercise table.
cise
cise
9.4.4:
Is it also
5.2.1
5.2.1 toto use
Redesign
possible
use type
type to
our running
make the model
declarations
declarations and
battleships
attribute
and reference
reference
database
7)
ttributes
ach 7)t iAssume
star.
GENERATED" e PRIMARY
t l by and y e a rwe
that
PRIMARY
"DERIVED," KEKY
from have
EY ( t(declared
the
then itsame
tnew
i lt el e, tuples
,y yeaaerelation
tuple. ra)rwould
) Movie,
get their andvaluethat of themovieIDWhere
type of star->namecise 5.2.4 =tribute
the
In
to‘Jim
In tuple
use
in
particular,
particular,
typeCarry’
the relation
in the
declarations
be aareference to
for
relations
in the relations that
and reference
type
PC: of product?
Laptop,
PC: Laptop,
attributes
and
and wh
WP
1;1; tribute
from be reference to the
the Product
Productwhere tuple for
for th
tuplereferen th
his
Example
ater,
relation
by some is the UDT
calculation,
9.259.11.
in Fig. : Now, The
MovieType;
performed
lety following
by the
us see howistoasame
wesystem,
shall define
represent
new definition
on the both
the many-many
MovieType
values
of StarType
and Movie
of the primary-key
relationship
that includes
Or star->name =
The ‘Mel
*
schema
Exercise Gibson’; Exercise
9.4.4: Redesign 9.1.3 should oursuggest
running battleships
attributes t i t l e and e a r from the tuple. useful. !cise
!Look
Exercise
Exercise for many-one
5.2.4 to 9.4.3:
use
9.4.3: typerelationships
Exercise 9.4.2
Indeclarations
In Exercise andandtry
9.4.2 tosuggested
reference
we
we represen
suggested att
etween movies and stars using
a11 attribute bestMovie that is a reference to a movie. references. Previously, we represented this attribute with a reference type.
elationship Figure
Figure 9.11:
9.11: Creating
a Creating a areferenceable
referenceable table
table The
tables schema
tables PC, from
PC, Laptop,
Laptop, and PP9.1.3
Exercise
and rriinntteeshould
rr could
could suggest
be
be referen
referewhe
Example by 9.25 a relation
: Now, let like usS tsee I n that
r show contains
to represent tuples with the keys
the many-many of
relationship useful. Look for many-one relationships and try to
CREATE TYPE table. Is it also possible to make
table. Is it also possible to make the model attrib the model attrib
Movie
betweenand MovieStar.
movies andStarType As anusing
stars AS references.
alternative,( we may define S twe
Previously, I n to have this
a r srepresented attribute
the tuple with
in a
the reference
relation type.
for that type of product?
toname CHAR(30) ,new the tuple in the relation for that type of product
eferences
relationship
GENERATED"
GENERATED" tuples
byby
address
from
a"DERIVED,"
relation
by"DERIVED," these-two like
then
AddressType,
thenSrelations.
t anewr s Ituples that would
ntuples contains
wouldget gettuples
their with
theirvaluevaluethe keys
ofofmovieID
movieIDof 9.5 Operations on Object-Relational
yMovie
First,
bysome
some and MovieStar.
wecalculation,
need
calculation,
bestMovie
to redefine
performed
performedAs anbyby
MovieStar
REF(MovieType)
alternative,
the the it is a we
sosystem,
system,
SCOPE Movie
ononmay
referenceable
the define
thevalues
values ofSofthe
table, t the
athusly:•  That is wrong because
to
r sprimary-key
Iprimary-key
n have ** Exercise
Exercise all objects
9.4.4: Redesign
9.4.4: Redesign of our type
our running
running battleshi
battlesh
references
ttributes t to
i t ltuples
e and from
y e a r these-two
from the relations.
same tuple. -111 9.5
appropriate 5.2.4Operations
SQL operations from onprevious Object-Rela
chapters apply t
attributes t i t l e and y e a r from the same tuple.
>
CREATE
; weTABLE
First, need to MovieStar
redefine MovieStar OF StarType so it( is a referenceable table, thusly: MovieType aredeclared unique cise
cise
with
The a
The schema
even
5.2.4
UDT
to
schemafrom
to use
or
use if
that they
type
type
have
from Exercise
have
declarations
declarations
attributes
Exercise9.1.3 9.1.3 should
the
and
and
whose
reference
reference
type
should suggest
suggest is aw w
Example
Example
Sow, ifCREATE
REF9.259.25
relationTABLE
I S: sNow,a r I Dletlet
:tNow,
MovieStar MovieStar
usussee
SYSTEM
is defined
howhowtotorepresent
seeGENERATED
OF
representthe
to have the
StarType
themany-many
( UDT above,
many-manyrelationship
then each star same
relationship content also some-111 appropriate
entirely
useful.
useful.
declared
new
Look
Look
with
SQL
operations
for
for
operations
many-one
many-one
a UDT orespecially
we can
that have
from
use,
relationshipsprevious
such
relationships as chapt
reference
attributes whose
and
and try
try
between 1;willmovies
between movies and and stars
starsusing using references.
references. Previously,
Previously, wewe represented
represented this
this ever, some familiar operations.
uple have
REF a
I S component
s t a r I D that
SYSTEM refers
GENERATED to a Movie tuple - the star's best attribute
attribute with
with aa reference
reference type. type.those that access or
elationship by a relation like S t a r s I n that
relationship by a relation like S t a r s I n that contains tuples with the keys of
movie.
contains tuples with the keys of \\-hosetype is a UDT, involve new syntax. can use, such a
also some entirely new operations we
Then,
Movieand
Movie 1; we may declare
MovieStar. As
andMovieStar. the relation
Asananalternative, S t a
alternative,wer s I n to have
wemay two
maydefinedefineSSt at ar sr sI• 
attributes, InntotoNeed
~vhich have
have a mechanism ever, tosome definefamiliar how operations. objects especially those that
rereferences
references, one toarrange
afrommovie tuple and one to a Movie star tuple. Here is 9.23a direct 9.5typeOperations
9.5
\\-hose is a UDT, involveon new Object-Re
syntax.
References on Object-Re
Operations
eferences tototuplestuples from these-two
these-two relations.
relations.
SThen,
e s t , n-e
efinition
First,
First,of
we
wemust
this
we need
may
relation:
need to
declare
redefine
that a table
the relation
MovieStar
S t a ras
such
so it
s I n to have
is a
in Example
referenceable
two attributes,
table, compare
will~vhich
have
thusly: to each
9.5.1 other Following
a arereference
references, column. one to Such
to redefinea table
a movie MovieStar
is said
tuple and toso beitreferenceable.
one tois aa star
referenceable
tuple. In aHere table,
CR EAisTEathusly:
TABLE
direct
tatement
definition
CREATE
CREATE
n-here
of this
TABLE
TABLE
the type
relation:
S t a r s
MovieStarI
of
n (
the table
OFOFStarType
is a UDT (as in Section 9.4.3), we (needed
may for any comparison,
Suppose -111
9.5.1 isappropriate
x-111 aappropriate
Following
value of type e.g.,
SQL
SQLREF(T). ordering,
operations
operations
References Thenfrom from
x refersprevious
previous
to some cha
cht
CREATE TABLE MovieStar StarType (( declared
declared with
with aa UDT
UDT or
or that
that have
have attributes
attributes who
wh
append a clause of the form:
sREF
CREATE
t aREF I SI SREF(StarType1
r TABLE s tsat raIrD
S t aI D
SYSTEMSCOPE
r s ISYSTEM
n (
GENERATED MovieStar,
GENERATED duplicate elimination,
We can obtain tuple
Suppose
also
alsosome grouping,
some a valuenew
entirely new etc.)
t itself, or components
x isentirely of type REF(T).
operations
operations
of t: by two mean
weThen
we can
can use,x refers
use, such
suc
1;1;movie star R EREF(MovieType1
F IS tattribute
REF(StarType1 SCOPE MovieStar, SCOPE
name> Movie <how generated, 1. Operator -> has essentially the same meaning as this by
Weever, can
ever, obtain
some
some tuple
familiar
familiar t itself,
operations.
operations. or components
especially
especially of t:
those
those opth
t
1; \\-hose type is a UDT, involve new syntax.
TheThen, Then,wewemay
attribute
movie declare
may declare
name
REF(MovieType1
is a name the relation
thegivenrelation to the
SCOPE Moviehave two attributes, ~vhich
ar sr Is nI ntoto
S St at column thathavewilltwoserve attributes,
as an "object ~vhich
That\\-hose if type
1.is,Operator ->a UDT,
x is aisreference involve
to
has essentiallya tuplenew the
syntax.
t. same
and is an att
49a meaning
re 1; we x->a is the value of the attribute n
That is, if x is a reference to a tuple t. and a in tuple t.
arereferences,
dentifier"
Optionally, forcould
references, one
tuples. totoThe
onehave a adefined
movie .-how
movie tuple
UDTand
generated"
a tuple one
andabove,
as one toto
clause anda ais
star tuple.
typically
star
then Here
tuple.either:
declared S t a rissisIanadirect
Here direct
ORDERING RELATIONSHIPS

•  Need to define how to compare objects of a given


type T

Equality or non-equality (=, ≠)


Identical content
EQUALS
ONLY BY STATE;
Create Ordering For T
BY RELATIVE WITH F;
ORDERING FULL
User-defined function F(O1, O2) and
Full comparison (=, <, >, ≤, ≥, ≠) returns 0, -ve, +ve

50
Alternatively, we could define a conlplete ordering of AddressType objects.
CREATE TYPE9.MovieType AS (
One reasonable ordering is to order
CREATE ORDERING
*FOR addresses first
b) PersonType,
AddressType
withby cities,ofalphabetically,
a name
EQUALS
the person and references
ONLY BY
and
STATE;
to
454 1) CHAPTER OBJECT-ORIENTATION IN QUERY LAXGU-AGES among addresses in the same city, byarestreet 9.5. OPERATIONS
their address,
mother and ON
alphabetically. OBJECT-RELATIONAL
father. You must To do theI{-e
useso, type from
2 t i t l e CHAR(30) , have Alternatively,
to define a function, say AddrLEG, that
declaration. takes two ordering AddressType arguments
year INTEGER, we could define a conlplete of AddressType ob
*
ORDERING FUNCTION
and returns a negative, zero, or positive b) valuePersonType, to indicate with that
a name theoffirst the is less and ref
person
3,
4) 1) CREATE TYPE
i n c o l o r BOOLEAN MovieType A S ( One reasonable ordering is to order
c) MarriageType, addresses with first
the date by cities,
of the marriage alphabetically
and userefere
than, equal to, or greater than the second.areWe their mother
declare: and father. You must the
2 1; title CHAR(30) , among addresses in the same city, band and bydeclaration.
street
wife. address, alphabetically. To do
year INTEGER, FOR AddressType
haveCREATE to define ORDERING
a function, say AddrLEG, that takesON twoOBJECT-RELATIONA
AddressType argu
54 3,CHAPTER
454 5) 4) CHAPTER i n c 9.
o l9.
o OBJECT-ORIENTATION
r
CREATE TABLE Movie OF MovieType ( OBJECT-ORIENTATION
BOOLEAN ININQUERY
QUERYLAXGU-AGES LAXGU-AGES ORDER FULL BY RELATIVE Exercise
WITH
9.5.
9.5.
c)9.4.2: OPERATIONS
OPERATIONS
Redesign our
MarriageType,
AddrLEG; withON
running
theOBJECT-RELATIONA
date products
of the database
marriage
1;REF I S movieID SYSTEM GENERATED,
and returns a negative, zero, or positive value to indicate
cise 5.2.1 to use type declarations and reference attributes wh
band and wife. that the first
6)
than,The equal
functionto,AddrLEG
or greater Inthan
is shown the
**b)b)9.13.
in Fig.
particular, second.
in theNotice
PersonType,
PersonType,
Wethat
relations declare:
PC:if awe
with
with namereach
aLaptop,
name line
ofand
of the (7),
thePperson mak
r i n t e r and
person and
7) PRIMARY KEY ( t i t l e , yAeSa r )(
1) CREATE
1)5) CREATE
CREATE TYPE
TYPE
TABLE MovieType
MovieType
Movie OF A S
MovieType ( ( it must be that the two city tribute Exercise
be
components a are
reference
are9.4.2:
theto the Redesign
same, so
Product we our
are their mother and father. You must use tt
their mother and father.
tuple running
compare forYouthat products
must
the model. use
.1. USER-DEFINED
1; t i t l e TYPES IAr SQL 453
2 6)
2 CHAR(30)
t i t lIeS movieID
REF CHAR(30) ,,
SYSTEM GENERATED, CREATE ORDERING FOR
street components. Likewise, if we reach declaration.AddressType
cise 5.2.1 to use
declaration.
line (9), type the onlydeclarations
remaining andpossi-
reference att
yearyear INTEGER,
KINTEGER, In 9.4.3:
particular, in the relations PC: Laptop, thatand Pr
7) PRIMARY EY ( t i t l e , y e a r )
A REF(T) SCOPE R bility is ORDER that theFULL
cities BY
are RELATIVE
!the
Exercise
same and WITH the InAddrLEG;
firstExercise
street to 9.4.2
precedes we suggested
the second model
4) 3, 1; iFigure
3,4) ni cnoc lool ro rBOOLEAN
BOOLEAN
9.11: Creating a referenceable table tribute c)c) MarriageType,
be a reference
MarriageType, with
the
with
tables PC, Laptop, and P r i n t e r could be references to tuples the
Product
the date
date of
tuple
of the
the formarria
that
marria
1 alphabetically. 13
;1;
f no scope is specified, the reference can go to any relation of type T The function AddrLEG is shown
table. Is it also inbandFig.and
band
possible and towife.
9.13. wife.
make Notice
the model thatattribute
if we reach in Produ lin
! Exercise 9.4.3: In Exercise 9.4.2 we suggested th
it must be that the twothecity tuple components
in thePC,relation
Exercise
tables 9.4.2: are
for that the r i same,
Ptype
Redesign n tofeour so we
rproduct?
runningbeWhy compaor wh
produc
GENERATED"
ExampIe 5)5) CREATEby
9.23 "DERIVED,"
CREATE TABLE9.11:
Figure
TABLE
: Reference Movie
thenMovie Creating
new
attributes OFOFtuples areawould
MovieType referenceable
MovieType
not get( (theirto
sufficient table
value
record of movieID
in MovieStar Exercise 9.4.2: and
Laptop, Redesign our couldrunning reference
produc
street components. Likewise, if
table.
cise we5.2.1 reach
Is it alsoto
to use line
possible
type (9),
to the only
make the model
declarations andremainingattribute
and reference
yhesome 6)6)
set calculation,
of all movies REF REF Ithey
SI SmovieID
performed movieID by theSYSTEM
starred system,
SYSTEM
in, but they GENERATED,
on theletvalues
GENERATED, us recordof thethe primary-key
best movie
bility
1) forCREATE FUNCTION
is that the cities
* areAddrLEG
Exercise
the the
In
cise
(9.4.4:
sametuple
5.2.1
particular,
Redesign
and
in the
use
the
type declarations
our running
relation
in first
the for street
relations that
battleships
precedes
type
PC: of
reference
database
product?
Laptop, the
and sWP
ach 7)
ttributes 7)t iAssume
star.
GENERATED" e PRIMARY
t l by and y e a rwe
that
PRIMARY
"DERIVED," KEKY
from have
EY ( t(declared
the
then itsame
tnew
i lt el e, tuples
,y yeaaerelation
tuple. ra)rwould
) Movie,
get their andvaluethat of themovieID 2) of
type x1 AddressType, cise 5.2.4 In to useparticular,
type declarationsin the relations and reference PC: Laptop,
attributes and wh
alphabetically. 13 tribute
tribute be aareference toto thethe Product tuple for
for th
his relation
by some 1;1; is the UDT
calculation, MovieType;
performed by the wesystem,
shall define on the both MovieType
values and
of the primary-key 3)
Movie x2 AddressType *
The schemaExercise from be Exercise reference
9.4.4: Redesign 9.1.3 should Productwhere
oursuggest
tuplereferen
running battleships
th
Example
ater, 9.259.11.
in Fig. : Now, The lety following
us see howistoasame represent
new definition the many-many
of StarType relationship
that includes 4) ) RETURNS INTEGER useful. !cise
attributes
etween movies
t i t l e and
and stars
e a r from the
using references.
tuple.
Previously, we represented this !Look
Exercise
Exercise for many-one
5.2.4 to 9.4.3:
use
9.4.3: typerelationships
In Exercise 9.4.2
Indeclarations
Exercise andandtry
9.4.2 we
we tosuggested
referencerepresen
suggested att
a11 attribute bestMovie that is a reference to a movie. attribute with a reference type.
elationship Figure
Figure 9.11:
9.11: Creating
a Creating a areferenceable
referenceable table
table The
tables
tables schema PC, from
PC, Laptop,
Laptop, and PP9.1.3
Exercise
and rriinntteeshould
rr could
could suggest
be
be referen
referewhe
Example by 9.25 a relation
: Now, let like usS tsee I n that
r show contains
to represent tuples with the keys
the many-many of 5) IF xl.city() < x2.cityO
relationship useful. THEN Look RETURN(-1)
for many-one relationships and try to
CREATE TYPE 1) CREATE FUNCTION AddrLEG table. Is it also possible to
table. Is (it also possible to make the model attrib make the model attrib
Movie
betweenand MovieStar.
movies andStarTypeAs anusing
stars AS references.
alternative,( we may define S twe
Previously, I n to have6)this
a r srepresented ELSEIF xl.city() > x2.cityO attribute
the tuple THEN
within a
the RETURN(1)
reference
relation type.
for that type of product?
toname CHAR(30) ,new 2)ofELSEIF x1 AddressType, the tuple in the relation for that type of product
eferences
relationship
GENERATED"
GENERATED" tuples
byby from
a"DERIVED,"
relation
by"DERIVED," these-two like
then
thenSrelations.
t anewr s Ituples that would
ntuples contains
wouldget gettuples
their with
theirvaluevaluethe keys
ofofmovieID
movieID
7) xl. street 9.5
() < x2. street () THENon
Operations Object-Relational
RETURN(-1)
address AddressType,
yMovie
First,
bysome
some and MovieStar.
wecalculation,
need
calculation,
bestMovie
to redefine
performed
performedAs
REF(MovieType)
anbyby
MovieStar alternative,
the the it is a we
sosystem,
system,
SCOPE Movie
ononmay
referenceable
the define
thevalues
values ofSofthe
table, t the
athusly: n to8)have
r sprimary-key
Iprimary-key x2 AddressType
3) ELSEIF xl.street() = ** Exercise
Exercise
x2.streetO 9.4.4: Redesign our
9.4.4:THEN Redesign
RETURN(0) our running
running battleshi
battlesh
references
ttributes t to
i t ltuples
e and from
y e a r these-two
from
attributes t i t l e and y e a r from the same tuple. the relations.
same tuple. 4) ) RETURNS
9) ELSE RETURN(1) -111
INTEGER 9.5
appropriate 5.2.4Operations
SQL operations
cise 5.2.4 to use type declarations and
cise to use type from on
previous
declarations Object-Rela
chapters
and reference apply t
> ; weTABLE
CREATE
First, need to MovieStar
redefine MovieStar OF StarType so it( is a referenceable table, thusly:
END IF; declared with
The
The schemaa UDT
schemafrom or that have
from Exercise attributes
Exercise9.1.3 9.1.3 should whose
reference
type
should suggest
suggest is aw w
Example
Example REF9.259.25I S: sNow,a r I Dletlet
:tNow, usussee
SYSTEM howhowtotorepresent
seeGENERATED representthe themany-many
many-manyrelationship relationship also some-111 appropriate
entirely
useful. new
Look SQL
operations
for operations
many-one we can from
use, previous
such
relationships as chapt
reference
and try
Sow, ifCREATE
between
relationTABLE MovieStar MovieStar is defined OF to have the
StarType ( UDT above, then each star 5) IF xl.city() < x2.cityO useful.
declared
Look
with THEN
a UDT
for many-one
RETURN(-1)
orespecially
thattype.
relationships
have attributes whose
and try
uple 1;willmovies
between movies
have
and
a and stars
component starsusing using
that
references.
references.
refers to a
Previously,
Previously,
Movie tuple
wewe
-
represented
represented
the star's
this
bestthis ever, some familiar
attribute
attribute operations.
with
with aa reference
reference type.those that access or
elationship REF
by a I S s t
relation a r I D SYSTEM
like S t a r GENERATED
s I n that
relationship by a relation like S t a r s I n that contains tuples with the keys of contains tuples with the keys 6) of ELSEIF xl.city() >
also
\\-hosetypefunction x2.cityO
some
is a UDT, entirely THEN
new RETURN(1)
operations
syntax. we can use, such a
movie. Figure 9.13: A comparison forinvolve
address newobjects
Then,
Movieand
Movie 1; we may declare
MovieStar. As
andMovieStar. the relation
Asananalternative, S t a r
alternative,we s I n to have
wemay two
maydefine attributes, ~vhich
defineSSt at ar sr sI Inntotohave have ELSEIF xl. street () < x2. street () THEN especially
7) ever, some familiar operations. RETURN(-1) those that
rereferences
references,
eferences
SThen, one
tototuples
e s t , n-ewemust tuples
may
toarrange
afrom
from movie
declare
tuple
these-two
these-two
that and
a table
the relation
one
relations.
relations. to a Movie
S t a ras
such star tuple.
s I n to have
Here is 9.23
in Example a direct
two attributes, will~vhich8) ELSEIF xl.street()
have 9.5
\\-hose
9.5
9.5.1 Following = type Operations
is a UDT, involve
Operations
x2.streetO References THENon new
on Object-Re
syntax.
Object-Re
RETURN(0)
efinition
a are First,
First,
reference of
we this
we need
column. relation:
need to to redefine
Such redefinea MovieStar
table MovieStar
is said so
to sobe itit is isa areferenceable
referenceable
referenceable. In a table,
Ctable,
R E A T Ethusly:
thusly:
TABLE
9) ELSE RETURN(1)
references, one to a movie tuple and one to a star tuple. Here9.5.5 is a direct Exercises for Section 9.5
-111
tatement
definition n-here
of this the type of the table is a UDT (as in Section 9.4.3), we may END IF;
relation: Suppose9.5.1 x-111isappropriate
aappropriate
Following
value of type SQL
SQL operations
operations
References
REF(T). Thenfrom from
x refersprevious
previous
to some cha
cht
CREATE
CREATE
CREATE TABLE
append a clause of the form:
TABLE
TABLE S t a r s
MovieStarI n
MovieStar ( OFOFStarTypeStarType (( declared
declared with
with aa UDT
UDT or
or that
that have
have attributes
attributes who
wh
Exercise 9.5.1: Using the StarsIn We can obtainrelation tuple tExample
itself, or 9.25,components of Movie
t: by two mean
sREF
t aREF I SI SREF(StarType1
r TABLE s tsat raIrD SYSTEMSCOPE GENERATED MovieStar, Suppose
also
alsosome xofisentirely
a valuenew of type and
REF(T).
operations
the
we Then
can
can use,x refers
such
CREATE S t aI D r s ISYSTEM
n ( GENERATED
and Moviestar relations accessihle through some
StarsIn, entirely new
write operations
the following wequer- use, suc
1;1;movie star R EREF(MovieType1
F IS tattribute
REF(StarType1 SCOPE MovieStar, SCOPE
name> Movie <how generated,
ies: 1. Operator -> has essentially the same meaning as this by
Weever,
ever,can obtain
some
some tuple
familiar
familiar t itself,
operations.
operations. or components
especially
especially of
thoset:
those optht
1; Figure 9.13: A comparison
\\-hose type function
is a UDT, for address
involve new objects
syntax.
TheThen, Then,wewemay
attribute
movie declare
may declare
name
REF(MovieType1
is a name the relation
thegivenrelation to the
SCOPE Moviehave two attributes, ~vhich
ar sr Is nI ntoto
S St at column thathavewilltwoserve attributes,
as an "object ~vhich
That\\-hose if type
1.is,Operator ->a UDT,
x is aisreference involve
to
has essentially a tuplenew the
syntax.
t. same
and is an att
51a meaning
re
dentifier" 1; we
arereferences,
references,
Optionally, forcould one
tuples. totoThe
onehave a adefined
movie .-how
movie tuple
UDTand
generated"
a tuple one
andabove,
as one toto
clause anda ais
star tuple.
typically
star
then Here
tuple.either:
declared
* a) Find
S t a rissisIanadirect
Here
the names of the stars of Ishtar.
direct
x->a is the value of the attribute
That is, if x is a reference to a tuple t. and a n in tuple t.
CREATE TYPE9.MovieType AS (
* b) PersonType, with a name of the person and references to
454 1) CHAPTER OBJECT-ORIENTATION IN QUERY LAXGU-AGES theirOPERATIONS
9.5.
are ON OBJECT-RELATIONAL
mother and father. You must use the type from
2 t i t l e CHAR(30) , declaration.
year INTEGER, * b) PersonType, with a name of the person and ref
3,
4) 1)
2 1;
CREATE
title
year
TYPE
CHAR(30) , EXAMPLES IV: COMPARISON
MovieType AS (
i n c o l o r BOOLEAN

INTEGER,
band and
are theirwith
c) MarriageType,
wife.
the date
mother
declaration.
of the marriage
and father. You must and
userefere
the

54 3,CHAPTER
454 5) 4) CHAPTER i n c 9.
o 9.
l o OBJECT-ORIENTATION
r OBJECT-ORIENTATION
BOOLEAN
CREATE TABLE Movie OF MovieType ( ININQUERY
QUERYLAXGU-AGES
LAXGU-AGES Exercise9.5. 9.5.
9.4.2:
c) OPERATIONS
OPERATIONS
Redesign our
MarriageType, ON
withON OBJECT-RELATIONA
running
theOBJECT-RELATIONA
date products
of the database
marriage
6) 1;REF I S movieID SYSTEM GENERATED, cise 5.2.1 to use type declarations and reference attributes wh
band and wife.
7) PRIMARY KEY ( t i t l e , yAeSa r )( **b)b) inPersonType,
In particular, the relationswith
PersonType, PC: aaLaptop,
with name
name of ofand
the
thePperson mak
r i n t e r and
person and
1) CREATE
1)5) CREATETYPE
CREATE TYPEMovieType
TABLE MovieType
MovieIArOFSQL AS (
MovieType ( tribute Exercise are
be a reference 9.4.2: Redesign our
are their mother and father. You must use tt
their to mother
the Productand father.
tuple running
forYouthat products
must
model. use
.1. USER-DEFINED
1; TYPES 453
2 6)
2 t i t l e CHAR(30)
t i t lIeS movieID
REF CHAR(30) , ,
SYSTEM GENERATED, cise 5.2.1 to use type declarations and reference att
declaration.
year INTEGER, declaration.
year KINTEGER, ! Exercise In 9.4.3:
particular, In in the relations
Exercise 9.4.2 we PC: Laptop,
suggested thatand modelPr
4)
7)
3,4)
PRIMARY
3, 1; iFigure
EY ( t i t l e , y e a r )
ni cnoc lool ro rBOOLEANA REF(T) SCOPE R Create Ordering For MovieType
tribute c) Equals
MarriageType,
be a reference Only
towith
the By
the
Product State;
date of
tuplethe formarria
that
9.11:BOOLEAN
Creating a referenceable table c) MarriageType, with the
tables PC, Laptop, and P r i n t e r could be references to tuples date of the marria
1 ;1;
f no scope is specified, the reference can go to any relation of type T table. Is it alsoband band
possible and
and towife.
wife.
make the model attribute in Produ
! Exercise 9.4.3: In Exercise 9.4.2 we suggested th
the tuple in thePC,relation
Exercise
tables 9.4.2: for that Ptype
Redesign r i n tofeour
rproduct?
runningbeWhy or wh
produc
GENERATED"
ExampIe 5)5) CREATE
by
9.23 "DERIVED,"
CREATE TABLE9.11:
Figure
TABLE
: Reference Movie
thenMovie Creating
new
attributes OFOFtuples areawould
MovieType referenceable
MovieType
not get( (theirto
sufficient table
value
record of movieID
in MovieStar Exercise 9.4.2: and
Laptop, Redesign our couldrunning reference
produc
table.
cise Is it also
5.2.1 toto usepossible
type to make the model
declarations and attribute
and reference
yhesome 6)6)
set calculation,
of all movies REF REF Ithey
SI SmovieID
performed movieID by theSYSTEM
starred in,system,
SYSTEM but they GENERATED,
on theletvalues
GENERATED, us recordof thethe primary-key
best movie for * Exercise the
In
cise
9.4.4:
tuple
5.2.1
particular,
Redesign
in the
use
in
type declarations
our running
relation
the for
relationsthat
battleships
type
PC: of
reference
database
product?
Laptop, and WP
ach 7)
ttributes 7)t iAssume
star.
GENERATED" e PRIMARY
t l by and y e a rwe
that
PRIMARY
"DERIVED," KEKY
from have
EY ( t(declared
the
then itsame
tnew
i lt el e, tuples
,y yeaaerelation
tuple. ra)rwould
) Movie,
get their andvaluethat of themovieID
type of cise 5.2.4 In particular,
to use in the relations
type declarations and reference PC: Laptop,
attributes and wh
tribute
tribute be aareference toto the
the Product tuple for
for th
his relation
by some 1;1; is the UDT
calculation, MovieType;
performed by the wesystem,
shall define on the both MovieType
values Q5:
and
of the primary-key Find
Movie distinct movies *
The schemastarred
Exercise from be by
Exercise
9.4.4:
reference
‘Jim 9.1.3Carry’
Redesign should Productwhere
oursuggest
tuplereferen
running battleships
th
Example
ater, 9.259.11.
in Fig. : Now, The lety following
us see howistoasame represent
new definition the many-many
of StarType relationship
that includes useful. !cise
attributes
etween movies
t i t l e and
and stars
e a r from the
using references.
tuple.
Previously, we represented or
this‘Mel Gibson’ !Look
Exercise
Exercise for many-one
5.2.4 to 9.4.3:
use
9.4.3: typerelationships
In Exercise 9.4.2
Indeclarations
Exercise andandtry
9.4.2 we
we tosuggested
referencerepresen
suggested att
a11 attribute bestMovie that is a reference to a movie. attribute with a reference type.
elationship Figure
Figure 9.11:
9.11: Creating
a Creating a areferenceable
referenceable table
table The
tables schema
tables PC, from
PC, Laptop,
Laptop, and PP9.1.3
Exercise
and rriinntteeshould
rr could
could suggest
be
be referen
referewhe
Example by 9.25 a relation
: Now, let like usS tsee I n that
r show contains
to represent tuples with the keys
the many-many of
relationship useful. Look for many-one relationships and try to
CREATE TYPE table. Is it also possible to make
table. Is it also possible to make the model attrib the model attrib
Movie
betweenand MovieStar.
movies andStarType As anusing
stars AS references.
alternative,( we may define S twe
Previously, I n to have this
a r srepresented
eferences
relationship
GENERATED"
GENERATED" tonametuples
byby from
a"DERIVED,"
relation
by"DERIVED,"
CHAR(30)
these-two like
then
then
,new
Srelations.
t anewr s Ituples that would
ntuples contains
wouldget gettuples
their with
theirvaluevaluethe Select
keys
ofofmovieID
movieIDof Distinct DEREF(movie)attribute
the
9.5 Operations
tuple with
in a
the reference
relation type.
for
the tuple in the relation for that type of product
on Object-Relational
that type of product?
yMovie
First,
bysome
some and address
MovieStar.
wecalculation,
need
calculation, to redefine AddressType,
performed
performedAs anbyby
MovieStar alternative,
the the it is a we
sosystem,
system, ononmay
referenceable
the define
thevalues
values ofSofthe
table, t the
athusly:n toFrom
r sprimary-key
Iprimary-keyhave StarsIn ** Exercise
Exercise 9.4.4: Redesign
9.4.4: Redesign our our running
running battleshi
battlesh
references bestMovie
to tuples fromREF(MovieType)
these-two relations. SCOPE Movie -111 9.5
appropriate Operations
SQL operations from onprevious Object-Rela
chapters apply t
ttributes t i t l e and y e a r from the same tuple.
attributes t i t l e and y e a r from the same tuple.
>
CREATE
; weTABLE
First, need to MovieStar
redefine MovieStar OF StarType so it( is a referenceable table, thusly: Where star->name declared=The
cise
‘Jim
cise
with
5.2.4
5.2.4
a
The schema UDT Carry’
to
schemafrom
to use
or
use type
that
type
have
from Exercise
declarations
declarations
attributes
Exercise9.1.3 9.1.3 should
and
and
whose
reference
reference
type
should suggest
suggest is aw w
Example
Example
Sow, ifCREATE
REF9.259.25
relationTABLE
I S: sNow,a r I Dletlet
:tNow,
MovieStar MovieStar
usussee
SYSTEM
is defined
howhowtotorepresent
seeGENERATED
OF
representthe
to have the
StarType
themany-many
( UDT above,
many-manyrelationship
then each star Or
relationship star->name =
also ‘Mel
some-111
useful.Gibson’;
appropriate
entirely
useful.
declared
new
Look
Look
with
SQL
operations
for
for
operations
many-one
many-one
a UDT orespecially
we can
that have
from
use, previous
such
relationships
relationships as chapt
reference
attributes whose
and
and try
try
between 1;willmovies
between movies and and stars
starsusing using references.
references. Previously,
Previously, wewe represented
represented this
this ever, some familiar operations.
uple have
REF a
I S component
s t a r I D that
SYSTEM refers
GENERATED to a Movie tuple - the star's best attribute
attribute with
with aa reference
reference type. type.those that access or
elationship by a relation like S t a r s I n that
relationship by a relation like S t a r s I n that contains tuples with the keys of
movie.
contains tuples with the keys of \\-hosetype is a UDT, involve new syntax. can use, such a
also some entirely new operations we
Then,
Movieand
Movie 1; we may declare
MovieStar. As
andMovieStar. the relation
Asananalternative, S t a
alternative,wer s I n to have
wemay two
maydefine attributes, ~vhich
defineSSt at ar sr sI Inntotohave have ever, some familiar operations. especially those that
rereferences
references, one toarrange
afrommovie tuple and one to a Movie star tuple. Here is 9.23a direct 9.5typeOperations
9.5
\\-hose is a UDT, involveon new Object-Re
syntax.
References on Object-Re
Operations
eferences tototuplestuples from these-two
these-two relations.
relations.
SThen,
e s t , n-ewemust may declare that a table
the relation S t a ras
such s I n to have in Example
two attributes, will~vhich
have 9.5.1 Following
efinition
First,
First,of
we this
we need relation:
need to redefine MovieStar so it is a referenceable table, thusly:
a arereference
references, column. one to Such
to redefinea table
a movie MovieStar
is said
tuple and toso beitreferenceable.
one tois aa star
referenceable
tuple. In aHere table,
CR EAisTEathusly:
TABLE
direct -111
tatement
definition n-here
of this the type
relation: of the table is a UDT (as in Section 9.4.3), we may Suppose9.5.1 isappropriate
x-111 aappropriate
Following
value of type SQL
SQL operations
operations
References
REF(T). Thenfrom from
x refersprevious
previous
to some cha
cht
CREATE
CREATE
CREATE TABLE
TABLE
append a clause of the form: TABLE S t a r s
MovieStarI n
MovieStar ( OFOFStarTypeStarType (( declared
declared with
with aa UDT
UDT or
or that
that have
have attributes
attributes who
wh
We can obtain tuple t itself, or components of t: by two mean
sREF
t aREF I SI SREF(StarType1
r TABLE s tsat raIrD SYSTEMSCOPE GENERATED MovieStar, Suppose
also
alsosome x isentirely
a valuenew of type REF(T).
operations weThen
we can
can use,x refers
such
CREATE S t aI D r s ISYSTEM
n ( GENERATED some entirely new operations use, suc
1;1;movie star R EREF(MovieType1
F IS tattribute
REF(StarType1 SCOPE MovieStar, SCOPE
name> Movie <how generated, 1. Operator -> has essentially the same meaning as this by
Weever, can
ever, obtain
some
some tuple
familiar
familiar t itself,
operations.
operations. or components
especially
especially of t:
those
those opth
t
1; \\-hose type is a UDT, involve new syntax.
TheThen, Then,wewemay
attribute
movie declare
may declare
name
REF(MovieType1
is a name the relation
thegivenrelation to the
SCOPE Moviehave two attributes, ~vhich
ar sr Is nI ntoto
S St at column thathavewilltwoserve attributes,
as an "object ~vhich
That\\-hose if type
1.is,Operator ->a UDT,
x is aisreference involve
to
has essentiallya tuplenew the
syntax.
t. same
and is an att
52a meaning
re 1; we x->a is the value of the attribute n
That is, if x is a reference to a tuple t. and a in tuple t.
arereferences,
dentifier"
Optionally, forcould
references, one
tuples. totoThe
onehave a adefined
movie .-how
movie tuple
UDTand
generated"
a tuple one
andabove,
as one toto
clause anda ais
star tuple.
typically
star
then Here
tuple.either:
declared S t a rissisIanadirect
Here direct
CREATE TYPE9.MovieType AS (
* b) PersonType, with a name of the person and references to
454 1) CHAPTER OBJECT-ORIENTATION IN QUERY LAXGU-AGES theirOPERATIONS
9.5.
are ON OBJECT-RELATIONAL
mother and father. You must use the type from
2 t i t l e CHAR(30) , declaration.
year INTEGER, * b) PersonType, with a name of the person and ref
3,
4) 1)
2 1; EXAMPLES V: GROUPING & NESTING
CREATE
title
TYPE

year
MovieType AS (
i n c o l o r BOOLEAN
CHAR(30) ,
INTEGER,
band and
are theirwith
c) MarriageType,
wife.
the date
mother
declaration.
of the marriage
and father. You must and
userefere
the

54 3,CHAPTER
454 5) 4) CHAPTER
CREATE i TABLE o rOBJECT-ORIENTATION
n c o9.l9. OBJECT-ORIENTATION
BOOLEAN
Movie OF MovieType ( ININQUERY
QUERYLAXGU-AGES
LAXGU-AGES Exercise9.5. 9.5.
9.4.2:
c) OPERATIONS
OPERATIONS
Redesign our
MarriageType, ON
withON OBJECT-RELATIONA
running
theOBJECT-RELATIONA
date products
of the database
marriage
6) 1;REF I S movieID SYSTEM GENERATED, cise 5.2.1 to use type declarations and reference attributes wh
band and wife.
7) PRIMARY KEY ( t i t l e , yAeSa r )( **b)b) inPersonType,
In particular, the relationswith
PersonType, PC: aaLaptop,
with name
name of ofand
the
thePperson mak
r i n t e r and
person and
1) CREATE
1)5) CREATETYPE
CREATE TYPEMovieType
TABLE MovieType
MovieIArOFSQL AS (
MovieType ( tribute Exercise are
be a reference 9.4.2: Redesign our
are their mother and father. You must use tt
their to mother
the Productand father.
tuple running
forYouthat products
must
model. use
.1. USER-DEFINED
1; TYPES 453
2 6)
2 t i t l e CHAR(30)
t i t lIeS movieID
REF CHAR(30) , ,
SYSTEM GENERATED, cise 5.2.1 to use type declarations and reference att
yearyear INTEGER, Q6: Find stars who participated In 9.4.3: in less
declaration.
declaration.
particular, in the thanrelations10 moviesPC: Laptop, thatand Pr
7) PRIMARY KINTEGER,
EY ( t i t l e , y e a r ) ! Exercise In Exercise 9.4.2 we suggested model
4)3, 1; iFigure
3,4) ni cnoc lool ro rBOOLEAN A
BOOLEAN REF(T) SCOPE R tribute c)
c) MarriageType,
be a reference
MarriageType, towith
the
with the
Product
the date
date of
tuple
of the
the formarria
that
marria
9.11: Creating a referenceable table tables PC, Laptop, and P r i n t e r could be references to tuples
f no scope is specified, the reference can go to any relation of type T Select DEREF(star) !IsExercise
1 ;1; table. it alsoband band
possibleand
and towife.
wife.
make the model attribute in Produ
9.4.3: In Exercise 9.4.2 we suggested th
the tuple in thePC,relation for that Ptype
r i n tofeour
rproduct? beWhy or wh
GENERATED"
ExampIe 5)5) CREATE
by
9.23 TABLE9.11:
Figure
TABLE
"DERIVED,"
CREATE : Reference Movie
thenMovie Creating
new
attributes OFOF areawould
MovieType
tuples referenceable
MovieType
not get( (theirto
sufficient table
value
record of movieID From StarsIn
in MovieStar
Exercise
tables
Exercise 9.4.2:
9.4.2: and
Laptop, Redesign
Redesign our running
couldrunning produc
reference
produc
table.
cise Is it also
5.2.1 toto use possible
type to make the model
declarations and attribute
and reference
yhesome 6)6)
set calculation,
of all movies REF REF Ithey
SI SmovieID
performed movieID by theSYSTEM
starred in,system,
SYSTEM but they GENERATED,
on theletvalues
GENERATED, us recordof thethe primary-key
best movieGroup for by DEREF(star) * Exercise the
In
cise
9.4.4:
tuple
5.2.1 Redesign
in
particular, the
use
in
type declarations
our running
relation
the for
relationsthat
battleships
type
PC: of
reference
database
product?
Laptop, and WP
ach 7)
ttributes 7)t iAssume
star. e PRIMARY
t l by and y e a rwe
that
PRIMARY KEKY
from have
EY ( t(declared
the itsame
tnew
i lt el e, tuples
,y yeaaerelation
tuple. ra)rwould
) Movie, andvaluethat of themovieID
type of cise 5.2.4 In particular,
to use in the relations
type declarations and reference PC: Laptop,
attributes and wh
GENERATED"
1;1;
"DERIVED," then get their
Having count(movie) <
tribute 10;
tribute
from be
be aareference
reference toto the
the Product
Productwhere tuple for
for th
tuplereferen th
his
Example
ater,
relation
by some is the UDT
calculation,
9.259.11.
in Fig. : Now, The
MovieType;
performed
lety following
by the
us see howistoasame
wesystem,
shall define
represent
new definition
on the both
the many-many
MovieType
values
of StarType
and
of the primary-key
relationship
that includes
Movie *
The schemaExercise Exercise
9.4.4: Redesign 9.1.3 should oursuggest
running battleships
attributes t i t l e and e a r from the tuple. useful. !cise
!Look
Exercise
Exercise for many-one
5.2.4 to 9.4.3:
use
9.4.3: typerelationships
Exercise 9.4.2
Indeclarations
In Exercise andandtry
9.4.2 tosuggested
reference
we
we represen
suggested att
etween movies and stars using
a11 attribute bestMovie that is a reference to a movie. references. Previously, we represented this attribute with a reference type.
elationship Figure
Figure 9.11:
9.11: Creating
a Creating a areferenceable
referenceable table
table The
tables schema
tables PC, from
PC, Laptop,
Laptop, and PP9.1.3
Exercise
and rriinntteeshould
rr could
could suggest
be
be referen
referewhe
Example by 9.25 a relation
: Now, let like usS tsee I n that
r show contains
to represent tuples with the keys
the many-many of
relationship Create at least anuseful. equality Look ordering
for many-one on StarType
relationships and try to
CREATE TYPE table. Is it also possible to make
table. Is it also possible to make the model attrib the model attrib
Movie
betweenand MovieStar.
movies andStarType As anusing
stars AS references.
alternative,( we may define S twe
Previously, I n to have this
a r srepresented attribute
the tuple with
in a
the reference
relation type.
for that type of product?
toname CHAR(30) ,new the tuple in the relation for that type of product
eferences
relationship
GENERATED"
GENERATED" tuples
byby
address
from
a"DERIVED,"
relation
by"DERIVED," these-two like
then
AddressType,
thenSrelations.
t anewr s Ituples that would
ntuples contains
wouldget gettuples
their with
theirvaluevaluethe keys
ofofmovieID
movieIDof 9.5 Operations on Object-Relational
yMovie
First,
bysome
some and MovieStar.
wecalculation,
need
calculation,
bestMovie
to redefine
performed
performedAs
REF(MovieType)
anbyby
MovieStar alternative,
the the it is a we
sosystem,
system,
SCOPE Movie
ononmay
referenceable
the define
thevalues
values ofSofthe
table, t the
athusly: n to have
r sprimary-key
Iprimary-key ** Exercise
Exercise 9.4.4: Redesign
9.4.4: Redesign our our running
running battleshi
battlesh
references
ttributes t to
i t ltuples
e and from
y e a r these-two
from
attributes t i t l e and y e a r from the same tuple. the relations.
same tuple. Q7: Find movie titles -111
in 2000 9.5
appropriate
cise where Operations
SQL
5.2.4 to operations
5.2.4 to‘Jim use type from
Carry’ onprevious
is
declarations Object-Rela
not chapters
in
and apply t
reference
>
CREATE
; weTABLE
First, need to MovieStar
redefine MovieStar OF StarType so it( is a referenceable table, thusly: declared The
cise
with a
The schema UDT
schemafrom or
use type
that have
declarations
attributes
Exercise9.1.3
from Exercise 9.1.3 should
and
whose
reference
type
should suggest
suggest is aw w
Example
Example REF9.259.25I S: sNow,a r I Dletlet
:tNow, usussee
SYSTEM howhowtotorepresent
seeGENERATED representthe themany-many
many-manyrelationship relationship also some-111 appropriate
entirely
useful. new
Look SQL
operations
for operations
many-one we can from
use, previous
such
relationships as chapt
reference
and try
Sow, ifCREATE relationTABLE MovieStar MovieStar is defined OF to have the
StarType ( UDT above, then each star useful. Look for many-one relationships and try
between 1;willmovies
between movies and and stars
starsusing using references.
references. Previously,
Previously, wewe representedSelect
represented m
this
this ever, somedeclared
familiar with a UDT orespecially
operations. that have attributes whose
uple have
REF a
I S component
s t a r I D that
SYSTEM refers
GENERATED to a Movie tuple - the star's best attribute
attribute with
with aa reference
reference type. type.those that access or
elationship by a relation like S t a r s I n that
relationship by a relation like S t a r s I n that contains tuples with the keys of
movie.
contains tuples with the
From
keys of
Movie m \\-hosetype is a UDT, involve new syntax. can use, such a
also some entirely new operations we
Then,
Movieand
Movie 1; we may declare
MovieStar. As
andMovieStar. the relation
Asananalternative, S t a
alternative,wer s I n to have
wemay two
maydefine attributes, ~vhich
defineSSt at ar sr sI Inntotohave have ever, some familiar operations. especially those that
rereferences
references, one toarrange
afrommovie tuple and one to a Movie star tuple. Here is 9.23 Where
a direct have m.year = 2000 9.5typeOperations
9.5
\\-hose is a UDT, involveon new Object-Re
syntax.
References on Object-Re
Operations
eferences tototuplestuples from these-two
these-two relations.
relations.
SThen,
e s t , n-ewemust may declare that a table
the relation S t a ras
such s I n to have in Example
two attributes, will~vhich 9.5.1 Following
efinition
a are First,
First,
reference of
we
references,
this
we need
column. relation:
need to
one to
redefine
Such
to redefinea table
a movie
MovieStar
MovieStar
is said
tuple and
so
toso it is a referenceable
beitreferenceable.
one tois aa star
referenceable
tuple. In aHere EAAnd
table,
table,
CR thusly:
TEathusly:
is TABLE m.title Not In (
direct -111 isappropriate
x-111 SQL operations Thenfrom previous cha
tatement
definition
CREATE
CREATE
CREATE
n-here
ofTABLE
this
TABLE
the
TABLE
type
relation:
S t a r s
MovieStarI
of
n
MovieStar (
the table
OFOFStarType
is a
StarType
UDT
((
(as in Section 9.4.3), we may Select movie->title
Suppose9.5.1
declared
aappropriate
Following
value
with
of type
a
SQL
UDT
operations
References
REF(T).
or that have
from
x refers previous
attributes
to some cht
who
append a clause of the form: declared with a UDT or that
We can obtain tuple t itself, or components of t: by two mean have attributes wh
sREF
CREATE
t aREF I SI SREF(StarType1
r TABLE s tsat raIrD
S t aI D
SYSTEMSCOPE
r s ISYSTEM
n (
GENERATED MovieStar,
GENERATED From StarsIn Suppose
also
alsosome somex isentirely
a valuenew
entirely of type
new REF(T).
operations
operations weThen
we can
can use,x refers
use, such
suc
1;1;movie star R EREF(MovieType1
F IS tattribute
REF(StarType1 SCOPE MovieStar, SCOPE
name> Movie <how generated, Where star->name ever,
ever, =
some
some‘Jim familiar Carry’
1. Operator -> has essentially the same meaning as this by
We can obtain tuple
familiar t itself,
operations.
operations. or components
especially
especially of t:
those
those opth
t
1; movie declare REF(MovieType1 SCOPE Moviehave two attributes, ~vhich And movie->year \\-hose
That\\-hose =if 2000);
type
type is a
x is aisreference
1.is,Operator
UDT,
->a UDT,
involve
involve
to
has essentiallya tuplenew new
the
syntax.
syntax.
t. same
and is an att
53a meaning
TheThen, Then,wewemay
attribute may declare
name is a name the relation
thegivenrelation to the ar sr Is nI ntoto
S St at column thathavewilltwoserve attributes,
as an "object ~vhich
re 1; we x->a is the value of the attribute n
That is, if x is a reference to a tuple t. and a in tuple t.
arereferences,
dentifier"
Optionally, forcould
references, one
tuples. totoThe
onehave a adefined
movie .-how
movie tuple
UDTand
generated"
a tuple one
andabove,
as one toto
clause anda ais
star tuple.
typically
star
then Here
tuple.either:
declared S t a rissisIanadirect
Here direct
QUERYING COLLECTIONS & ARRAYS

create type Book as
 To get a relation containing pairs of the form
" (title varchar(20),
 title, author-name for each book and each
" author-array varchar(20) array [10],
 author of the book"
" pub-date date,

" publisher Publisher,

select B.title, A

" keyword-set setof(varchar(20)))" " from books as B, unnest (B.author-array) as A"

find all books that have the word database


as one of their keywords

select title

"from books

"where database in (unnest(keyword-set))"
Unnest returns a relation

Get 1st and 2nd authors of certain book

select author-array[1], author-array[2] 



"from books

"where title = `Database System Conceptsʼ"
54
GENERATORS AND MUTATORS

•  How to insert new new data into tables

•  Generators
•  Like the constructors in OO programming
•  Create new objects

•  Mutators
•  Modify the value of an existing object

•  For each attribute x in UDT T, the system automatically


creates:
•  Generator T() that returns an empty object of T
•  Mutator x(v) that sets the value of attribute x to value v

55
458 1 CHAPTER 9. OBJECT-ORIENTATION IN QUERY LANGUAGES
CREATE TYPE9.MovieType AS (
5) DECLARE newAddr AddressType; * b) PersonType, with a name of the person and references to
454 1) CHAPTER OBJECT-ORIENTATION IN QUERY LAXGU-AGES 6) DECLARE newstar StarType; are theirOPERATIONS
9.5. mother and father. ON OBJECT-RELATIONAL
You must use the type from
2 t i t l e CHAR(30) , declaration.
year INTEGER, 1) CREATE PROCEDURE I n s e r t s t a r (
* b) PersonType, with a name of the person and ref
3, 1) CREATE
4)
2 1;
i n c o l oTYPE
title
year
r BOOLEANMovieType AS (
CHAR(30) ,
INTEGER,
EXAMPLE 7) 2,
BEGIN I N s CHAR(5O),c) MarriageType,
3) SETI NnewAddr
8) 4) SETI Nnewstar
c CHAR(10).
n CHAR(30)
= AddressTypeO;
band and
= StarTypeO ;
are theirwith
wife.
declaration.
motherthe date of the marriage
and father. You must and userefere
the

54 3,CHAPTER
454 5) 4) CHAPTER i n c 9.
o l9.
o OBJECT-ORIENTATION
r OBJECT-ORIENTATION
BOOLEAN
CREATE TABLE Movie OF MovieType ( ININ QUERY
QUERY LAXGU-AGES
LAXGU-AGES
458 1
CHAPTER 9. Exercise9.5.
OBJECT-ORIENTATION 9.5. OPERATIONS
9.4.2:
c) OPERATIONS
RedesignINour
MarriageType, ON
withON
QUERY OBJECT-RELATIONA
running
theOBJECT-RELATIONA
dateproducts
LANGUAGESof the database
marriage
9) newAddr.street(s);
1;REF I S movieID SYSTEM GENERATED, cise 5.2.1 to use type declarations and reference attributes wh
band and wife.
6) 10) 5) DECLARE newAddr.newAddr
c i t y (c) AddressType;
In ;particular,
**b)b) inPersonType,
the relationswith
7) PRIMARY KEY ( t i t l e , yAeSa r )( 6) DECLARE newstar StarType; PersonType, PC: aaLaptop,
with name
name of ofand
the
thePperson
person mak
r i n t e r and
and
1) CREATE
1)5) CREATETYPE
CREATE TYPEMovieType
TABLE MovieType
Movie OF AS (
MovieType ( 11) newstar .name(n) ;
tribute Exercise
be
1) CREATE PROCEDURE I n s e r t s t aare a are 9.4.2: Redesign our running
r ( their mother and father. You must use tt
referencetheirto mother
the Product and father.
tuple for You
that products
must
model. use
.1. USER-DEFINED
1; t i t l e TYPES IAr SQL 453
2 6)
2 REF CHAR(30)
t i t lIeS movieIDCHAR(30) ,,
SYSTEM GENERATED, 12) newstar.
I N saddress(newAddr1;
CHAR(5O), cise 5.2.1 to use type declarations and reference att
declaration.
declaration.
7) year
year
PRIMARY INTEGER,
KINTEGER,
EY ( t i t l e , y e a r ) BEGIN ! Exercise In 9.4.3:
particular, in the relations
In Exercise PC: Laptop,
9.4.2 we suggested thatand modelPr
4)3, 1; iFigure
3,4) ni cnoc lool ro rBOOLEANA REF(T) SCOPE R
BOOLEAN
13) 3) INSERT
2, I N INTO Moviestar
c CHAR(10).
tributeVALUES(newStar);
c) MarriageType,
be a reference to with
the the
Product date of the
tuple formarria
that
7) SET newAddr tables = AddressTypeO; c) MarriageType, with the date
and P r i n t e r could be references to tuples of the marria
1
9.11: Creating a referenceable table END 4); I N n CHAR(30) PC, Laptop, band and
;1;
f no scope is specified, the reference can go to any relation of type T 8) 1 SET newstar = StarTypeO
table. Is it also band
;
possible and towife.
wife.
make the model attribute in Produ
! Exercise 9.4.3: In Exercise 9.4.2 we suggested th
newAddr.street(s);
9 ) 5) DECLARE newAddr the AddressType;
tuple in thePC,relation
Exercise
tables 9.4.2: for that Ptype
Redesign r i n tofeour
rproduct?
runningbeWhy or wh
produc
GENERATED"
ExampIe 5)5) CREATE
by
9.23 "DERIVED,"
CREATE TABLE9.11:
Figure
TABLE
: Reference Movie
then
Movie Creating
new
attributes OFOFtuples areawould
MovieType referenceable
MovieType
not table
get( (theirto
sufficient value
recordof movieID
in MovieStar Exercise 9.4.2: and
Laptop, Redesign our couldrunning reference
produc
10) Figure newAddr.
6) DECLARE c i t y (c)StarType;
newstar ; table.
cise Is itaalso
5.2.1 to usepossible
type to make the model
declarations and attribute
and reference
yhesome
set6)6)
calculation,
of all moviesREFREF Ithey
SI SmovieID
performed by theSYSTEM
movieID
starred in,system,
SYSTEM but theyGENERATED,
on the
letvalues
GENERATED, of thethe
us record primary-key
best movie for
11)
9.12: Creating
newstar
* Exercise
.name(n)
and
;
storing
the
In
cise 5.2.1
9.4.4:
tuple
StarType
to
Redesign
in
particular, the
use type object
declarations
our running
relation
in the for
relationsthat
battleships
type
PC: of
reference
database
product?
Laptop, and W
P
ach 7)
ttributes
star.
GENERATED" e PRIMARY
7)t iAssume
t l by and y e a rwe
that
PRIMARY
"DERIVED," KEKY
from
have
EY ( t(declared
the
then itsame
tnew
i lt el e, tuples
,y yeaaerelation
tuple. ra)rwould
) Movie,
get theirandvalue
that of
themovieID
type of cise 5.2.4 In particular,
to use in the relations
type declarations and reference PC: Laptop,
attributes and wh
and 12)
Movie BEGIN newstar. address(newAddr1; tribute
tribute be aareference toto the
the Product tuple for
for th
his relation
by some 1;1;is the UDT
calculation, MovieType;
performed by the wesystem,
shall defineon the both MovieType
values of the primary-key *
The schema Exercise from be Exercisereference
9.1.3 should
9.4.4: Redesign
Productwhere
oursuggest
tuplereferen
running battleships
th
Example
ater, 9.259.11.
in Fig. : Now, The lety following
us see howistoasame represent
new definition the many-many
of StarType relationship
To insert
that 13) 7)
includes SETMovieStar,
a star INSERT
into newAddr
INTO useful. = weAddressTypeO;
Moviestar VALUES(newStar);
can5.2.4callmany-one
toprocedure IExercise
n s e r t s tand aandr .trywe
attributes
etween
t i t l e and
movies and stars
e a r from the
using references.
tuple.
Previously, we represented this 8) SET newstar = !Look
!cise
Exercise for
Exercise
StarTypeO ;
use
9.4.3:
9.4.3: typerelationships
In Exercise 9.4.2
Indeclarations 9.4.2 we tosuggested
represen
reference
suggested att
a11 attribute bestMovie that is a reference to a movie. END ; attribute with a reference type.
elationship Figure
Figure 9.11:
9.11: Creating
a Creating a areferenceable
referenceable table
table The
tablesschema
tables PC, from
PC, Laptop,
Laptop, and PP9.1.3
Exercise
and rriinntteeshould
rr could
could suggest
be
be referenwhe
refere
Example by 9.25 a relation
: Now, let like usS tsee I n that
r show contains
to represent tuples with CALL
the many-many the keys of 9 )
relationship
InsertStar('345 newAddr.street(s);
Spruce S t . ' , 'Glendale',
useful. Look for 'Gwyneth
many-one Paltrow');
relationships and try to
CREATE TYPE table. Is it also possible to make
table. Is it also possible to make the model attrib the model attrib
Movie
betweenand MovieStar.
movies andStarTypeAs anusing
stars AS references.
alternative, ( we may define S twe
Previously, I n to have this
a r srepresented 10) newAddr. c i t y (c) attribute
;
the tuple with
in a
the reference
relation type.
for that type of product?
toname CHAR(30) ,new the tuple in the relation for that type of product
eferences
relationship
GENERATED"
GENERATED" tuples
byby from
a"DERIVED,"
relation
by"DERIVED," these-two
like
then
then Srelations.
t anewr s Ituplesthat would
ntuples contains
wouldget tuples
get their with
theirvalue
isvalue
an the keys 11)
ofofmovieID
movieID
example. of Figurenewstar
9.12: Creating9.5 and
.name(n) ;Operations
storing a StarType on objectObject-Relational
Movie andaddress
First,
ybysome
some MovieStar.AddressType,
wecalculation,
need to redefine
calculation, performedAs an alternative, we may define S t a r s I n to have
performed MovieStar
bybythe thesosystem,
it is a referenceable
system, ononthe thevalues
valuestable,
ofofthe thusly:
the primary-key
primary-key 12) ** Exercise
newstar. address(newAddr1; Exercise 9.4.4: 9.4.4: Redesign
Redesign our our running
running battleshi
battlesh
references bestMovie
to tuples fromREF(MovieType)
these-two relations.SCOPE Movie -111 9.5
appropriate Operations
SQL operations from on
previousObject-Rela
chapters apply t
ttributes t i t l e and y e a r from
attributes t i t l e and y e a r from the same tuple. the same tuple. 13) INSERT INTO Moviestar
cise 5.2.4VALUES(newStar);
5.2.4 to use type declarations and reference
>
CREATE
; weTABLE
First, need to MovieStar OF StarType
redefine MovieStar so it( is a referenceable table, It isthusly:much
To insertsimpler
aENstar
D; to
into insert objects
declared
MovieStar, we
cise
with
The
into
can
The schema a a
UDT
call
to
or
use
relation
procedure
schemafrom that
type with
haveI
declarations
n s a UDT
attributes
Exercise9.1.3
from Exercise e r t s t a r .
9.1.3 should
and
if
whoseyourreference
type
should suggest
suggest is aw w
Example
Example REF9.25 I S: sNow,
9.25 a r I Dletlet
:tNow, usussee
SYSTEM howhowtotorepresent
seeGENERATED representthe themany-many
many-manyDBMS provides, or if you create,
relationship
relationship also asome
generator
-111 appropriate
entirely
useful.
useful.
function
new
Look
Look
SQL
operations
for
for
that
operations
many-one
many-one we takes
can from
use,values
previous
such
relationships
relationships
for
as chapt
reference
and
and try
try
Sow, ifCREATErelationTABLE MovieStar MovieStar is definedOF to have the
StarType ( UDT above, then each star UDT
between
uple 1;willmovies
between movies
have
REF
and
a
I S
and stars
component
s t a
starsusing
r I D
using
that
SYSTEM
references.
references.
refers
GENERATED to a
Previously,
Previously,
Movie tuple
wewe
-
represented
the the attributes
represented thisof the C'DT and
this
star's InsertStar('345
CALL best Sprucereturns
ever, t declared
Ssome a familiar
. 'attributesuitable
,attribute with
'Glendale',with
with
aobject.
operations. orespecially
'Gwyneth
aa reference
reference
thattype.
For have attributes
those
example,
Paltrow');
type. that
if we whose
access or
elationship by a relation like S t a r s I n that contains tuples with the keys of Figure 9.12: Creating also
and some
storingentirelya new
StarType operations
object we can use, such a
relationship
movie.
Then, 1; we may
by a relation
declare the
like
relation
S t a
S
r s
t a
I n
r s
that
I n to
contains
have two
tuples with
have functions
attributes,
the
~vhich
keys AddressType(s ,c) and StarType(n, a) that return objects of
of \\-hose type is a UDT, involve new syntax.
Movieand
Movie MovieStar. As
andMovieStar. Asananalternative,
alternative,we wemay maydefine ntoto
defineSSt at ar srissI Inan have
have ever, some familiar operations. especially those that
the indicated example.
types, then we can make \\-hose the insertion is aat the end of onExample 9.28
rereferences
references,
eferences
SThen, to
e s t , n-e to one
tuples
wemust tuplesto
mayarrange
a
from movie
from
declare that
tuple
these-two
these-two and one
relations.
relations.
a table such
the relation
to
S t a ras
a star
s IMovie
tuple.
n to have
Here
in Example is a direct
9.23 will~vhich
two attributes, have 9.5.1 9.5typeOperations
9.5
Following Operations UDT,
References
involve new Object-Re
on syntax.
Object-Re
aefinition
First,
First,
reference
are
ofwewe
references,
this
need
column.relation:
need to Such
one to
redefine
to redefine a table
a movie
MovieStar
MovieStar
is said
tuple and tososobe
one
ititreferenceable.
isisa areferenceable
to a star In with
referenceable
tuple. aHere
C
anTEthusly:
EAIf
table,
table,
R
INSERT
is ItaDBMS
thusly:
TABLE
direct
is much
statement
To insert
allows of aMovieStar,
a star into
simplercreating
familiar form:
to insert objects
we can call procedure
generators into a with with
relation
Insertstar.
parametersa UDTfrom if your
tatement n-here the type of the table is a UDT (as in Section 9.4.3), we may Suppose9.5.1 -111
x-111 appropriate
is aappropriate
Following
value of type SQL
SQL operations
operations
References
REF(T). Then fromx refersprevious
previous
to some cha
cht
definition
CREATE
CREATE
CREATE of this
TABLE
TABLE
TABLErelation:
S t a r s I
MovieStar n
MovieStar ( OFOFStarType
StarType (( DBMS CALL provides, or
InsertStar('345if you create,
Spruce a S generator
t . '
declared , function
'Glendale',
with a UDT that
'Gwyneth
or takes
that values
Paltrow');
have for
attributes who
append a clause of the form: INSERT INTO MovleStar VALUES (declared with a UDT or
We can obtain tuple t itself, or components of t: by two mean that have attributes wh
sREF
t aREF I SI SREF(StarType1
r TABLE s tsat raIrD SYSTEMSCOPE GENERATED MovieStar, the attributes of the C'DT and Suppose
returns also a some x isentirely
suitable a object.
valuenew of Fortype REF(T).
example,
operations we ifThen
we use,
can x refers
such
CREATE S t aI Dr s ISYSTEM
n ( GENERATED StarType('Gwyneth Paltrow', also some entirely new operations we can use, suc
1;1;movie R EREF(MovieType1
F IS tattribute SCOPE
name> Movie <how generated, have is an example.
functions AddressType(s ,c) We
and ever, can obtain
some
StarType(n,
OperatorS->t .has
ever, some tuple
familiar a)
familiar t itself,
the same meaning as this by
operations.
that or
return
operations. components
especially
objects
especially of of t:
those
those opth
t
star REF(StarType1 SCOPE MovieStar, AddressType('3451.Spruce ' , essentially
'Glendale')));
UDT,
1; movie declare REF(MovieType1 SCOPE Moviehave two attributes, the indicated types, then we can make \\-hose
That\\-hose
1.is,Operator
the type
if type
insertion is a
x is aisreference UDT,
ata the
has end
involve
involve
to new
tuplenew
ofa Example syntax.
syntax.
t. same
and is an att
9.28a meaning
TheThen,Then,wewemay
attribute may declare
name is a name the relation
thegiven
relation to the ar sr Is nI ntoto
S St at column thathave
willtwo
serveattributes,
as an "object ~vhich
It~vhich
is much simpler to insertx->a objects is the into
value a of ->
relation
the
essentially
with an UDT
attribute in
the
tupleif56your
t.
re
dentifier"1; we
arereferences,
references,
Optionally, forcouldone
tuples. totoThe
onehave a adefined
movie.-how
movie tuple
UDTand
generated"
a tuple one
andabove,
as one toto
clause anda ais
star tuple.
typically
star
then Here
tuple.either:
declared S twith
Here a rissisIanan
DBMS
INSERT
adirect
direct statement of a familiar form:
provides, or if you create, a generator That is, functionif x is a reference
that takesto values a tuplefort. and a
CREATING RECORDS OF COMPLEX
TYPES
create type Book as

•  Collection and array types " (title varchar(20),

" author-array varchar(20) array [10],

" pub-date date,

" publisher Publisher,

" keyword-set setof(varchar(20)))"

Array construction
array [ Silberschatz ,`Korth ,`Sudarshan ]
Set value attributes
set( v1, v2, …, vn)

To insert the preceding tuple into the relation books


insert into books values
(`Compilers , array[`Smith ,`Jones ], null,
Publisher( McGraw Hill ,`New York ),
set(`parsing ,`analysis ))

57
WHAT WE COVERED
•  First Approach: Object-Oriented Model
•  Concepts from OO programming languages
•  ODL: Object Definition Language
•  What about querying OO databases???
•  OQL: Object Oriented Query Language

•  Second Approach: Object-Relational Model


•  Conceptual view
•  Data Definition Language (Creating types, tables, and
relationships)
•  Querying object-relational database (SQL-99)

Make use of the interesting features of Object-Oriented into


database systems è ODBMSs
58
WHEN TO CONSIDER
OODBMS OR ORDBMS
•  Complex Relationships
•  A lot of many-to-many relationships, tree structures or network (graph)
structures.

•  Complex Data
•  Multi-dimensional arrays, nested structures, or binary data, images,
multimedia, etc.

•  Distributed Databases
•  Need for free objects without the rigid table structure.

•  Repetitive use of Large Working Sets of Objects


•  To make use of inheritance and reusability

•  Expensive Mapping Layer


•  Expensive decomposition of objects (normalization) and re-
composition at query time

59
KEY BENEFITS OF ODBMS
Object Oriented Databases

•  Persistence & Versioning pointers must be persistent.

•  Created objects are maintained across different database


Implementation Issues runs
(persistent) Persistence !

•  Different evolving copies of the same object


Sharing !
can be created over
time (versioning)
Paging !

Back to the Beginning


!

1. Object-oriented databases give objects persistence, which enables objects to be store


database runs. (NOTE: in the context of ODBMS, PERSISTENCE = POST RUN T
PERSISTENCE), this facilitates versioning (i.e. a new, additional object is stored ea
are made).

PersistentObject Superclass Approach

•  Superclass encapsulates any class for storage and retrieval

•  This superclass implements all functionalities of read/write


operations

60
1. Object-oriented databases allow objects to be shared between processes in a distribu
environment.
KEY BENEFITS OF ODBMS (CONT’D)

•  Sharing in highly distributed environment


•  Easier to share and distribute objects than tables
Object Oriented Databases

61
KEY BENEFITS OF ODBMS (CONT’D)

•  Better memory usage and less paging


1. Object-oriented databases can reduce the need for paging by enabling only the currently required
•  Bringing only
objects to be objects of interest
loaded into memory (relational databases load in tables containing both the equired
data AND other unnecessary data )

ODBMS Relational DBMS

62
OBJECT-ORIENTED VS. OBJECT-
RELATIONAL
•  Object-oriented DBMSs
•  Did not achieve much success (until now) in the market
place
•  No query support (Indexing, optimization)
•  No security layer

•  Object-relational DBMSs
•  Better support from big vendors
•  Tries to make use of all advances in RDBMSs
•  Indexes, views, triggers, query optimizations, security layer, etc.
•  Work in progress --- Long way to go

63
MODIFICATIONS TO RDBMS

•  Parsing
•  Type-checking for methods pretty complex

•  Query Rewriting
•  New rewriting rules including complex types and collections

•  Optimization
•  New algebra operators needed for complex types.
•  Must know how to integrate them into optimization.
•  WHERE clause exprs can be expensive!
•  Selection pushdown may be a bad idea.

64
MODIFICATIONS TO RDBMS (CONT’D)

•  Execution
•  New algebra operators for complex types.
•  OID generation & reference handling.
•  Dynamic linking and overriding.
•  Support objects bigger than 1 page.
•  Caching of expensive methods.

•  Access Methods
•  Indexes on methods, not just columns.
•  Indexes over collection hierarchies.
•  Need indexes for new WHERE clause exprs (not just <, >, =)

•  Data Layout
•  Clustering of nested objects.
•  Chunking of arrays.

65
maintaining backward compatibility with SQL2. ORDBMSs have limited support for inheritance, with
no consistent definition between vendors or with respect to SQL3 (e.g., constructed types). For all

COMPARISON
vendors, base types are abstract types, supporting inheritance of properties and functions. There is no
such agreement for constructed types to be abstract types.

Table 2

A Comparison of Database Management Systems


Criteria RDBMS ORDBMS ODBMS
Defining standard SQL2 (ANSI X3H2) SQL3/4 (in process) ODMG-V2.0
Poor; programmers
spend 25% of coding
Support for object-oriented Limited mostly to new
time mapping the Direct and extensive
programming data types
program object to the
database
Table structures easy to Same as RDBMS, with OK for programmers;
Simplicity of use understand; many end- some confusing some SQL access for
user tools available extensions end users
Objects are a natural
Provides independence Provides independence
way to model; can
of data from application, of data from application,
Simplicity of development accommodate a wide
good for simple good for simple
variety of types and
relationships relationships
relationships
Can handle arbitrary
Limited mostly to new complexity; users can
Extensibility and content None
data types write methods and on
any structure
Can handle arbitrary
complexity; users can
Complex data relationships Difficult to model Difficult to model
write methods and on
any structure 66

You might also like