RDBMS SQL n Types of Relationships

16
. _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ - _ · · , , , I , . I · S V d a l O S . _ - - _ _ _ - _ _ _ _ _ - _ _ _ _ _ _ - _ - o 1 I s J - _ _

Transcript of RDBMS SQL n Types of Relationships

Page 1: RDBMS SQL n Types of Relationships

8/8/2019 RDBMS SQL n Types of Relationships

http://slidepdf.com/reader/full/rdbms-sql-n-types-of-relationships 1/16

.___________________-_

·

·,

,

,

I

,.

I

·

SV

d

a

lO

S

._--___-_____-______-_

-o1IsJ

-__

Page 2: RDBMS SQL n Types of Relationships

8/8/2019 RDBMS SQL n Types of Relationships

http://slidepdf.com/reader/full/rdbms-sql-n-types-of-relationships 2/16

RDBMS

What is a Relational Database Management System (RDBMS)?

A set ofsofrware that enables the user to create, review. update and delete information held Il1 a relational

database.

\"hat are some popular RDBMSs which support SQL?• Oracle

• Sybase

• Microsoft SQL server

• Infonnix

• Ingress

• DB2

• Centura SQLBase (bundled wllh SQL \Vm do ws)

• Sybase SQLAnywhere (bundled with PowerBuilder)

• PerYa sive.SQL (bundled with many accounting packages)

• Borland Database Eng inelInterBase (b undled with Delphi)

What is the history of RDBJ\1Ss'?

Dr EFCodd ofJBM published ".4. Relational Model of Data for Large Shared Data Banks" lD the

Co:m:1Uni : 0; the AC\1 in 1970 . This is the mathema tica lly rigorous theore il c::t: h2 o_ 0: ,i:,' re iallonal

databases. Subsequently. he publIshed hi s famous 12 principles of relational database5 I; 'T he Rela llo:)G

Approach to Data Base Manageme nt: An Overview", at the Third Annual Texas Conferenc e on COrDpumg

Systems in 1974.

What are the different kinds of database management systems?

• Hierarchical

• Network

• Relational

• Object

• Object-Relational

\Vhile hierarchical and network databases are older than relational databases, object and object - relationaldatabases are of relatively recent origin.

What are the features of a hierarchical database?

The main structures used by the hierarchical model are record types and parent-child relationship between a

parent record type and a child record type. Access to lower level data elements must first access their

parents. Relationships are strictly hierarchical in t h a ~ record type caAparticipate as child in at most one

parent-child relationship type. This restriction makes it difficult to represent a database ""here numerous

relationships exist. While storage and retrieval are \;ery fast. it is d\fficult to query a hierarchi cal database.

and impossible to build decision support systems based.on it. .

IMS is an example of a hierarchical databas e. ,I . , ,\\'hat are the features of a network database?

The network model assumes a more complex interrelationship (many to many) between data elements.Relationships and access paths are still predetermined and usually fixed but less restrictive. A record type

can participate as owner or member in any number of set types. This is the main distinction between the

network model and the hierarchical model. So, the network model has a better modeling capability than

does the hierarchIcal model.

\Vhat are the features of a relational database?

Page 3: RDBMS SQL n Types of Relationships

8/8/2019 RDBMS SQL n Types of Relationships

http://slidepdf.com/reader/full/rdbms-sql-n-types-of-relationships 3/16

The relational model makes no presumptions about the interrelationships between data elements.

Relationships are represented by on e table, containing key data extracted from another table. Relations are

dynamic and determined as needed.

In a relational database, everything is stored in tables. Tables contain columns and rows. In formal

relational theory, fIrst proposed by E.F.Codd , tables are known as relations and that is why these came to

be known as relational databases. Creation of these tables and their columns is done using SQL. Similarly

storage and retrieval of data is also done using SQL.

\\ 'hal are the features of an object database?

Object databases allow you to store complex data types or objects . Further more , it supports inheritence ,

pol)1TIorphism and encapsulation for full object-oriented development.

' ' ' 'hat ar e the features of an object-relational database?

This is a hybrid typ e of dat abase . Th e relational database server is usually extended to support objects as if

they are nn\ data types.

What are d a t a t ~ p e s ? At the time of creation of a col umn you need to say what type of data you intend storing in it. Such column

type definitions are knO\v11 as data types. Common data types that can be stored and manipulated are

?\TMBER. CHAR, or DA TE Bu t many RDBMSs also pro\Jde the ability to store newer types such as

TEXT, J!\1.A.GE .. .etc.

What is an Entity-Relationship(E-R) diagram? .A. use ful te cilJli que ill deslgmn g your database is to draw a plC1l1re of your tables showmg the relatJonship

bet ween tables. This graphica l display of a database is called an Entity-Relationship or an E-R diagram.

What is referential integrity?

A feature provided by RDBMSs that prevents users or applicatJons from entering inconsistent data. Most

RDBMSs have various referential integrity rules that you can apply when you create a relationship between

two tables. These rules help in preserving the integrity of the data . In simple tenns referential integrity

constraints make sure that there are no orphan records.

Let us say you have an 'employee ' table that has a foreign key that points to 'department_id', which is a key

in the 'department' table . Referential integrity will prevent you from deleting a department that has

employees assigned to it. This is knO\\ ' l l as a restriction. If you are dealing with 'order' table and multiple

items contained in an order , it is possible for you set it up such a wa y that all items in an order get deleted

when you delete an order. This is Known as a cascading delete.

What is the primary key?

The unique identifIer for a row of data in a table is the primary key. This can be a single column or a

combination of more than one column, in which case it is knO\\ l l as a composite key .

.:I What is the foreign key?

A key column in a table that identifIes records in a different table is called a foreign key.

Let us say that you have an 'order' table and an 'item' table. In the item table, let us say that your primary

key is the combination of 'order_ id' and 'item_number' . In this case, the 'order_id' which is the primary key

of the 'order' table is a foreign ke y in the 'item' table.

What is an alternate key?

Some tables in your database ma y have other columns which can be used as a key, which mayor may not

be unique. These are knOv,ll as alternate keys.

Let us say you have assigned each employee's Social Security Number as the primary key. The employee's

last name would be an alternate key.

What is a composite key?

\\'hen the ro\\'s of3 table can be un iquely identified only by a combination of more than one colunm, it is

said to have a composite key.

2

Page 4: RDBMS SQL n Types of Relationships

8/8/2019 RDBMS SQL n Types of Relationships

http://slidepdf.com/reader/full/rdbms-sql-n-types-of-relationships 4/16

'course_id' and 'start_date' together may uniquely identify each row in a 'session' table In this case. we will

say that the 'course' table has a composite key.

What is normalization?

Normalization is a series of rules tha t we apply on the preliminary database design to eliminate redundancy

and incosistency. Simply stated, normalization is the process of removing redundant data from relational

tables by splitting a relational table into smaller tables. The new tables can be recombined by a natural Join

(using SQL) to recreate the original table without creating any spurious or redundant data. Though there

can be more stages to normalizing a database , the basic process involves three stages.

\\'hat are the three normal forms?

First normal form: Remove repeating groups.

I f, in the employee table, you have a column name_of_children, this will have more than one value for

some of the employees.

Second normal form: Remove columns tha t do not depend on the whO le ke.

I f, in the item table , you have some attr ibutes of the order, then it will de pend Of. onJy part of the key

(namely. the order_number).

Third nonnal form: Remove colunms that do not depend only on the key .

If in the order table, you have some attributes of the item, then it will not de pena only on the key (it will

depend on order_number and item_numbe r)

Here is an easy way to remembe r thIS:

Columns must depend on the k e y ~ the whole key and nothing but the key:

\'·;,:.11 do you d0 with all those co lumns lhat you removed') Make them into separate table,.

What is an index. an d how is it used to improve performance?

indn i, informali 011 ahr>:I ' 'he ! " 1 1 l \ " 2 1 1 n c ~ t i n p 0finf0rT'1:1tin 11 nr: ' ~ " ; ~ : ' \ ' i ~ , : , , . . . ~ . .

hard disk). Indexes tend to slow dO \ \'1i data entry slightly, but speed-up locating the data ..

In a library when a new book comes in , the librarian will assign a rack number to it and make an imh: x card

so that it can be looked up quickly by author or title. Database indexes playa similar role.

Columns should generally be indexed in the following cases:

1. when the column is a primary or foreign key

2. when the column is sorted

3. \\'hen joins will be used on the colunm

4. when users will search for values in that column.All of these operations can benefi t with the help of indexes.

Can I Update From Another Table?

Yes. For ex ample, if we had a table DEPT_SUMMARY , we could update the number of employees fieldas follows:

update DEPT_SUMMARY s

se t NUM EMPS = (

se l ec tcoun t (l)

from EMP E

where E.DEPTNO = S . DEPTNO

) ;

3

Page 5: RDBMS SQL n Types of Relationships

8/8/2019 RDBMS SQL n Types of Relationships

http://slidepdf.com/reader/full/rdbms-sql-n-types-of-relationships 5/16

Can I remove duplicate rows:

Yes. using the ROWID field . The RO\\'ID is guaranteed unique. There are many variations on this theme ,

but the logic is to delete all but one record for each ke y value.

d e l e t e from EMP E

where n o t E . ROWID = (s e l e c t min(F.ROWID)

from EMP F I, 'here F . EM ? ID E. El '1? ID ) ;

How can I get information on the row based on group information?

lmagme we ha\'e the EMP table and want details on the employee who has the highest salary. 'You ne ed to

use a subquery.

se l e c t e.ENAME, e . E ~ ? N O , S ~ L ::::-om EMP e\,:h e r e e . SAL in

se l e c t ma x (e2 . SAL )

from EMP e2

) ;

You could get similar info on employee s wi th th e highest sa lary 10 their departments as follows

s e le c t e .E N.Z\ME, e . S.:.: '

:rom EMP e

v.'here e . SAL =

s e l e c t max ( e 2 .S AL )

from EMP e2

where e2 .DEPTNO = e.DE?TN O

) ;

How can I rename a column?

There is no way a colurrm can be renamed using normal SQ L It can be done carefully by the DBA playing

around with intemal SYS dictionary tables and bouncing the database , but this is not supported. (I have

successfully done it in V4 thru V7) Do bach.llp the database first unless you feel brave . I've \>,'Titten a quick

and dirty script mcol.sgl to do this. If you can't figure out how to use it from the source you definitely

should not run it.

You can use a similar dirty tTick for changing 0\\11ership of tables if storage space is limited.

4

Page 6: RDBMS SQL n Types of Relationships

8/8/2019 RDBMS SQL n Types of Relationships

http://slidepdf.com/reader/full/rdbms-sql-n-types-of-relationships 6/16

"'hat is SQL?

SQL is a tool for organizing, managing, and retrieving da ta from a computer database. The SQL language

is essentially a programming language for relational databases . SQL is independent of the underlying

database structure and many vendors offer SQL implementations for their database systems. The flow of

information between the user and the database using SQL is sirrlllar to that illustrated in Figure 1.

SQL

uest

DRt.2.bas e

Ma.l1agementI

~ D tabase ~ System - - - ~

Data

fl gure 1. Th" flo\ \ of commands and data be t\\ecll the user and th e database

The first concept to understand is the role of the database management sys tem (DBMS) The DB\1S

handles the management of the underlying database, handling all conununications between the user ane the

database . Requests for data are sent to the DBMS (as are all database management calls) whe re they are

processed and turned into actual read and writes to the database engine. This makes the DBM S moderate ly

independent of the underlying database engine and often the y are run on separate machines for perfOm13llCe

reasons .

The process for processing an SQL command is:• DBMS processes SQL request

DB\1S rerrieves data from database by sending a request to the database engine

• DB MS returns data to user

SQL can control all DBMS functions including:

• Data defin itions

• Data retrieval

• Data manipulation

• Acc ess control

• Data sharing

• Data integrity

How SQL manages to accomplish this is based on two principle s. First, the SQL command language is

broad in the scope of functions available offering over 40 commands in the SQL92 standard. Second, SQLdraws much of its power from the underlying definition of rela tiona I da tabases.

There are many definitions of what makes a relational database truly re1a tiona1, but one of the fundamental

ones that most database designers agree on is conunon1y known as the Information rule. The Information

rule stipulates that all infonnation regarding the structure oftJ1Cdatabase must be represented as values in

tables. This means that just like the regular infornlation in a data base, we can query and change the values

associated with the database structure. SQL is indifferent to the fact that we are changing the va lues in the

ta bles tha t control the structure of the database or those that represent end-user data . This allows us to use

the same commands for database management as we use to query end-user data .

5

Page 7: RDBMS SQL n Types of Relationships

8/8/2019 RDBMS SQL n Types of Relationships

http://slidepdf.com/reader/full/rdbms-sql-n-types-of-relationships 7/16

SQL is nOL however, a complete programming language. First, it lacks conditional tests (IF) and flow

control (GOTO, DO, and FOR) statements. Some database vendors may offer extensions to the SQL

language to accomplish these functions, but they are not part of the SQL92 standard. SQL can however be

integrated into other programming languages. Finally, despite the name. SQL lacks the explicit stmcture of

languages like C or Pascal

The primary advantages of SQL are:

• Vendor independencelPortabiliry - For the most part, SQL allows the user to change the

underlying brand of database and DBMS \",ithout having to rewrite the SQL code. (Variations in

the standard and proprietary extensions can complicate the issue)

• HIgh-level, English like structure - This makes SQL relatively easy to use compared to other

programming languag es.

• Standardized - T he standard is established by ANSI, with most vendors now supporting the more

recen t SQL 92 version.

• D}l1amic da la defi nition - SQL offers advanced data processing commands that allow for

embedded and multi-level database que ries.

SQL and relational databases

To bener understand database designs and eventually SQL command structure, we should next consider the

principles of re lational database design. As mentIOned eailie r. there is a lot of disagreement over all of the

features 2. re lauonal database should have. but those fe arures lIsted here are the most common.

In over-simplified terms. a relational database is a database where all data visible to the user is organizedstr ictly as tables of data \'alues and all da tabase operations work on those tables. This definition introduces

~ \ : : , other terms that need definition

Column Atomic value

• A collection of values with a common data type and defin ition

For example. we can separate a group of names into atomic un its of first and last names . One column

" . ~ a ; : . : the i l ~ j : \\ Lih. the e ' : 0 1 i : : \\ uuid (u lH al fl :h( .- na111c :> .

Tables

• Each row defines a single record In the table

• Each column represents one item of data stored about each row/record

• Each column can store only ONE data type

• The set of values a column can contain is called the domain

• Each column in a table is assigned a unjque name

• No standard limit on number of columns per table, but tbe norm is 255

• Rows are in no par ticular order and there are no constraints on the number of rows in a table

f or example a SImple table of names might look like this:

F':'rstName Las::name

~ a r y Jones

John Smith

Lar ry Stone

Primary key

• Since the rows have no specific order, you cannot refer to them by location (fIrst, last, third. etc)

• Every table has a column or columns marked as the primary key

• No two rows will have the same set of values in a column marked as a primary keyPrimary keys come in lots of forms. When working with a table that describes people (such as an employee

or customer table). we most often assign a unique employee or customer number. Our table ""ould now

look like this (note: the primary key does not imply any type of SOn function):

Emp l oyeeID Fir s tName Lastname

12 Mary Jones

2 John Smith

' - . - /3" a r ry Stone

6

Page 8: RDBMS SQL n Types of Relationships

8/8/2019 RDBMS SQL n Types of Relationships

http://slidepdf.com/reader/full/rdbms-sql-n-types-of-relationships 8/16

Relationships

• There are no explicit pointers

• Relationships are defmed by th e sharing of con1rnon data

• The data values in one column of Table I are used as the domain for the \'alues in c colurr.n in

Table 2.

• The val ue in Table 2 can be used to reference information from Table I

Foreign keys

• I f the values in a co lumn from one table match the values of a primary key column in another

table, the first is called a foreign key reference

• This creates a parent/child relationship between tables

• A tabl e can have more than one forei gn key to define re la ti onships with multiple ta bles

Other rules and practices in relational database design will become more 3!lparent as we dive deeper into

the process of building SQL commands in fu ture anicles.

Summary

This is only an introduction to th e bas ic concepts of SQL and relational datat.ases and those interested in

more detailed information should consult a book de dicated to database desir - pnn':lples In pan 2. we will

go into the syntax of SQL commands. sho w ll1g yo u how to use SQL to build::: datab2se. Insert data . and

query the data .

TYPES OF RELATlONSHIPS

One-to-many

The one :to-man y rel ationshi p is the workhorse of relational databases as wel l as b e i n t.he ecs;est

rei atiollsillP to un ders ta nci . LeI s say you need to budd a shoppmg can appiJcatlon for an t - CQ!11Il1erce

Your first draft of th e data base ha s columns for Item 1, Item2 , and Item3 with the corresponciinf Quan·it;- !.

Quantity2, and Quantity3 fi elds

Of course. thi s immediately starts to break down with more than three orders' Any time you find \ ourself

designing a database and adding similar fields like this to the same table, you need to break the table inio

nvo (or more' ) related tables using a one-lo-mam ' relationship.

A one-to-many relationship allows records in Table I to be co nnected to an arbitrary number of records in

Table 2 without th e limitations imposed by resorting to redundant or limited numbers of field s in a single

table . This reduces the size of the database and greatly increa ses the flexibility and performance of quenes

operating on that data. We can take our shopping cart example and break it into an Order table and an Item

table quite simply.

Order Table

OrderID IShiopingInfo

Order Item Table

IOrderItemlD lorderLD lItem !Quantii)'

The two ta bles are linked together using the OrderID field. The contents of any order in the Order table ca n

easily be found by finding all the items with that value in the OrderID field . There is also the added

advantage that the tw o pieces of data are independent and ca n easily be modified. If we now want to add an

ItemNumber to the OrderItem table, we add a single column: in our original monolithic data table. we'd be

adding I em,1\umber 1, ItenL'\'umber2, etc.

7

Page 9: RDBMS SQL n Types of Relationships

8/8/2019 RDBMS SQL n Types of Relationships

http://slidepdf.com/reader/full/rdbms-sql-n-types-of-relationships 9/16

One-to-one

One-to-one table relationships are a little more interesting and more undell.lsed than either of the other two

types of relationships. The key indicator of a possible need for a one-to-one relationship is a table that

contains fields that are only used for a ce.nain subset of the records in that table.

Let's ta ke a look at building a Catalog table for the items that your store sells. Odds are that you need to

store some information about the individual items like catalog numbers, weight, and other common data.

But if you're selling different kinds of items, books and CDs for example, yo u ma y want some item-specific

information in th e database. For example, you may want a page count, author, publish date, and ISB!\ for

books, whi le you want playing tllne, number of tracks, artist. and label for the CDs. You could come up

with some way to fi t both sets of data into the same structure, but th en when management decides you're

als o sellmg pel supplies . your system will probably break

A bener solu tion would be a one-la-one relationship be tween the Item table and another table of item

specific dali: for each type of item. The resulting structure 15 essentially one "J.1.aster " table (Ca talogItems)

wlIh one or more "subtables" (CDs and Books in this example). You link the two subtables to th e master

table through the primary key of the master table.

Cal aloc Ta ble

ICatalogID fPrice !D escription /Q uantityOnHand

CD 5

CatalogID PlaywgT!me INumOfTracks j.\rtist

I IBooks

CatalogID [pageCount h o r iP ublishDate ISB?\ .I IThe one-to-one relationship has saved us from doubling the number of fields in the Catalog table and, more

importantly. helped us break th e database into more discrete ent ities. In this scenario . we can get all the

generalmforrnation about an item from the Catalog table and can use the primary key of that table to pull

up the appropriate information from the subtabJe.

Many-to-manv  .,

Finall y, there is the many-to-many table. This rela tionsh,ip is a little more complex than the one-to-many

because. in addition to the two tables of data, we need another ta ble to join the two tab les of JDterest

together. That's right, we're adding a table to the database -- but it is a SImple table and saves us lots of

effort dOV>11 the road. As an example, let's say you want to add the abilit), to search for CDs by the

mUSICians on any given song. From the musician side, you have one musician related to many songs,

Music ian Table

IMusicianID tMusicianName I-jPaul McCartney

SODg Table-SongID MusicianID SongName

200 44 Sgt. Pepper 's Lonely Heart's Club Band201 44 E ~ o n y a ! l ~ } \ l o r y But from the song side, you potentially have a song related to many musicians. The following visuaJ

represent s that situation.

Song Table

SongID jSongl'\ame

200 ISgt. Pepper's Lonely Hea rt 's Club Band

\1usician Table'--"

1!\1usician ISongID fMusicianName

8

Page 10: RDBMS SQL n Types of Relationships

8/8/2019 RDBMS SQL n Types of Relationships

http://slidepdf.com/reader/full/rdbms-sql-n-types-of-relationships 10/16

3 00 ohn Lennon

  =0 : ,til McCartney

These two tables work individually, but when you tr y to put them together you end up wi:h this TT'jsh-mash

table.

Song Table

tsongID lM usicianID SongName

~ O O 43 Sgt. Pepper's Lonely Heart's Club Band

~ O O 44 Sgt. Pepper's Lonely Heart's Club Band

201 44 jI:bony_ a ~ d Ivory- .-

Musician Table

Musician S IDID ong .

43 200

44 200

44 201

MusicianName

John Lennon

Paul McCartney

Paul McCartne y

This has saved us nothing -- in fac t, it ha s complicated the structure by inlToducing lOiS of Ie jund ant data to

manage. The way to handle th is SItuatIOn is to create two one-to-many relationships Im ·ol ':mg a linking

table which we'll call SonLMusician, since it links those tables. We create a o n e - t o - m a n ~ from Song toSong_Musician since one song will have O-l\' musicians and then another one-to-many from \ il:si:lan to

one muslciall " ill be ill one or more so ng s. The results look ilke J J ~ ;-oiio\\ln f

Song Musician Table

M usicianN arne

John Le nnon

Ipaul McCartney

SonglD M usicianID. - ,

~ O O 143

~ O O 144

~ O l 144- - - -

Song Table-SongID Songl\ame i

~ O O Sgt. Pepper's Lonely Heart's Cl ub Band I

~ O l Ebony and Ivory I

- -- This time around, all of the redundant data is in the SonLMusician table, which is only two coJumm of

integers. Any changes to the slTllcture of the Song or Musician table remain independent of their

relationship, which is precisely what we're after.

9

Page 11: RDBMS SQL n Types of Relationships

8/8/2019 RDBMS SQL n Types of Relationships

http://slidepdf.com/reader/full/rdbms-sql-n-types-of-relationships 11/16

- - - - - - - -- -

JOINS

PARTSUPP Table

sno pn o qty

SJ

SI

PI

P3

300

400

S2 P2 400

S3 P2 200

SI

SJSJ

P2

P4P5

200

200100

Si P6 100

S2 PI 300

S4 P2 200

S4

1S4 1PS

P4 O ( 1 1400

SUPPLIER Table

cit yll O sname sta tu s

L O ~ D O l \ 'MITH 20I

S2 JONES 10 PARIS

BLAKE 30 PARlS3

LONDON II4 CLARK 20

SS ADAMS _ - __ I _ ____________ 30 __ A T H ~ ~ ~ _J

Equijoin

The equUo/n is the most commonly used kind of table Join. Equijoins include ajo/n cOlld/noll requiring the values

derived from one column of a table or view to equal the va lues derIved from another column of a different table orview. Join conditions may be created on an y combination of columns, provided the qualified column names being

compared in the WHERE clause have compatible data types.

For example, suppose the supplier numbers and city names for all suppliers that supply part "P2" are needed. The

next query il lustrates how this could be accomplished:

SELECT sno, c i ty

FROM par t supp , supp l i e r

W H E ~ E par t supp .sno = supp l i e r . sno

Al'JD P:10 "P 2 "

Page 12: RDBMS SQL n Types of Relationships

8/8/2019 RDBMS SQL n Types of Relationships

http://slidepdf.com/reader/full/rdbms-sql-n-types-of-relationships 12/16

The query results appear below:

Isno Icity

S2 PARlS

S3 PARlS

S l LONDON

S4 LONDON

As demonstTated in the previous query, when the tables to be jO I;]ei 3 \ ' e a common column name

appearing in the WHERE clause Jo in condition, column names shou !.:: :::' ;::-efL';ed (qualified) with their tab le

name s to resolve any ambiguity. In the abo\'e qUC[\·. the qualified column nar.. ": P.-\RTSU PP .S)lO specifies that the

5 \0 co lumn of the PARTSUPP table is to be compared with the S:\O col umr. SLPPLlER table

(S UPPLlERS"iO).

C-H ':TION ! If you do not qualify a co lu mn name that is contai ned in more than O i 1 ~ : , · . : ~ r v statement table. the

system uses column da ta from th e first table It finds containing the specifled colu:-:-:.:- : : : : 1 ~ situation can

produce unexpected results, and it is adv isable to prefix common column names th e:.: ~ : : :- "o\\.l1ing" table

names.

If a Jom condi tion (such as, pansupp.sno = supplie rsno ) is not included m a eq uijoin ~ ~ : : . y i . : . ~ ;:-5 '_;- ,5 Co Cartesian

product. This type of jo in conc atenates e \ " e record fro m a table \v1th e\ery re cord fro;:: : - " ~ ~ ~ . ;;::.'es listed In theFROM clause, producing all this information in the query result. Caneslan products ha,'e L-:-it"d : ; . r c . C ' ; ! ~ ~ . 21ue and

can res ult in ",,,rremely large and often nonsenslca l results.

Outer Join

An ourerjoin creates two distinct kinds of query output one after the other -- all in the same resuit no' \ ' a J 3 ' : J l e 11DB2 mode). Records sa tisfYllg the join condition app ea r fi rst In the result. followed immediately b\' records tha t

do not satisfy the join condition_

For example, an ordinary join between the S1:.JPPLlER and PARTSUPP table coul d be perfomled using the

fo llowing query:

SELECT supp l i e r . sno , sname, pno, qty

F R s upp l i e r , par t supp

WHERE s upp l i e r . sno = par t supp . sno

HO\\e\d, the output result wou ld not mclude any information on supplier "SS" , since this is the one supp lier that

does not supply any parts_

By perfonning an outer join, it is possible to retrieve th e information on supplier "55" from the SCPPLIER table

(specifical ly the SNO and SNAME column \'alues) , even tho ugh the join condItion of the \VHERE clause

(s up plier.sno = partsupp.sno) is not being met for thi s ro w of jOllle d output.

SELECT supp l i e r . sno , sname, pno, qty

FROM suppl ie r , p ar tsu pp

WHERE suppl ie r . s no = par t supp. sno(+)

The sample query above illustTates the syntax for an outer jo in . Appending a p lus sign wi thin parentheses (- ) to the

PARTSUPP table name in the j oin condition yield s the following res ults :

2

Page 13: RDBMS SQL n Types of Relationships

8/8/2019 RDBMS SQL n Types of Relationships

http://slidepdf.com/reader/full/rdbms-sql-n-types-of-relationships 13/16

sno sname pno qty

Sl SMITH PI 300

Sl SMITH P3 400

SI SMITH P2 , 200

SI SMITH P4 200

Sl SMITH P5 100SI SMITH P6 100

S2 JONES P2 400

S2 JONES PI 300

S3 BLAKE P2 200

S4 CLARK P2 200

S4 CLARK 300

S4 CLARK P5 -1 00

S5 ADAMS-

Even though the PARTSUPP table con t2111S no rows Wl ih c. : : : ' ; ) g "S5" value , the outer join causes the "55"

row oflhe SUPPLIER tab le to be outp ut anyway (immed la :e:" ; : . all the rows matchlng the Join co nditIOn) . Sincethere are no matching or QTY colwlm values from th e U ~ S L P P table for that Joined row of OU ipliL the

ou ter Join Ji]sens nui! \'alues in the P"."O an d QTY columns C:s ! : " s u l ro w.

RIGHT [OUTER]

Rig ht outer joins (the keyword OLTER is ag ain optional) include nonma tching rows only from the table named', - , after the RlGHT [Ot:TER] clause. tvlissing values in a ro\\ ::! le d WIth nulls. The following sample

query creates a right outer Jom between ihe PART and PARTSCPP e 5 : S ~ L E C T par t . pno , pna me , qcy

FROM p a r t OUT ER JOIN par t s upp

ON par t .pno = part

supp .pno The re sults of this query contains all matched rows, plus non matched ro ws from the PART5l1PP table (o r, th e

table on the right hand side of the RIGHT OUTER JOIN clause) For e:<.2 mple, if the PART5UPP table contained a

norunatching record for a P"."O colunm vaiue of P9, this mformanon would be pan of the resuit. If, however, the

PART table also contained an nonmatched record, this record ll1fOm1atlon would not appear in the re sult rows.

bing the RIGHT [OUTER] JOrN syntax includes nonmatched rOW5 from only the Joined table on the right of the

RIGHT OUTER JOIN clause.

ON

Clause that should be used in place of the WHERE clause when explicitly stating an fl\;l\iER JO IN condition

(however, the WHERE clause still works) . For LEFT and RIGHT OUTER JOIN clauses, however , the Join

condition must begin with the ON clause.

3

Page 14: RDBMS SQL n Types of Relationships

8/8/2019 RDBMS SQL n Types of Relationships

http://slidepdf.com/reader/full/rdbms-sql-n-types-of-relationships 14/16

A?\OTHER EX.!\\llPLE

D7.002.DEPT D7.002 .E:rvTI>

~ i ~ ~ ~ W l e e . SELECT A.DEPTNO l i ~ ~ ~ ~ l k W ! ) R l t D ; ' E P . ; m J r<O 1 ,B .EMPNO 90000" K01

H.J\o.2 ... H .. .9D!XJQ2__ __ ",0"FROM DZO02.DEPT AK03 90000:) ·-(OJ

RIGHT JO INKOA. _" ' ....._.80_0.00.4._._...._Z O 0 2 ...1P B 900005 .' ;,( ~ K05

ON

A.DEPTNO = B.WORr..DEPT

1 ~ ; , r n E P J l J J , h + ~ : E P _ : . . . . 800001

900 00 2 Result9.000.0.3

90000Ll9.00005

4

Page 15: RDBMS SQL n Types of Relationships

8/8/2019 RDBMS SQL n Types of Relationships

http://slidepdf.com/reader/full/rdbms-sql-n-types-of-relationships 15/16

.,

OLT Pl"T OF O HA J"ID OCT

SQL> spool a:out;

SQL> select • from partsupp ;

S]\ PN QTY

SI P I 300 O L e G ~ 4 - t · c. .fc;.1)2S 400

S2 P2 .! :-,) cJ_.....d A ;' X /),1 ctrr+-c-,,S:: p:

SI ?-

5 1 ?::.. 200

S: P5 100

SI P6 100

S2 PI 300

S4 P2 20 0

S4 P4 300

S4 P5 400 .-c

- 7S7 P5 400 /Yo-f---e =:>" /'"'v:; t 'x 'rr-c;, ) ,/')-lot

( ' .....-' ::- .-,,_1 / /.Jf1 '1 ,-, "I V / 1 . - ~ y . f _ ( ' ? - i ( i3 rows se ie ;:::eci .\

SQL> select * from suppl ie r:

J.' ::', \A.;vjc S1AlLS c:r ·

SI SMITH 20 LOl\1DO :\ C,'u<..ca-(c J.( ' To U.I? S2 JONES 10 PARlS

S3 BLAKE 30 PARlS

S4 CLARK 20 LO NDO N

S5 ADAMS 30 LO!',mO

N

SQL > select p.sno,p ,p no,s.sname,s.cny,s .s no

2 lTom partsupp p,supplier s

3 where p.sno=s.sno;

-c X

CL,-,--d /) >0 cterf C\ '

","\[,:::. 1 _. S 5 ' /l.-?

l(r1 /1rf />"V .rvn_ - - - - - - - - - - - - - - -

SN SNAME

SI PI SMITH

SI P3 SMITH

S I P2 SMITH

S I P4 SMITH

S1 P6 SMITH

S I P5 SMITHS2 P2 JONES

S2 PI JONES

S3 P2 BLAKE

S4 P2 CLARK

S4 P4 CLARK

.S4 P5 CLARK

CITY SN

LOl'rDON S I

LON'DO N S I

LONDON S I

LONDON S1 kLONDON S 1

f'J6

J~ I . L< "'" 'ill <' , to f M , ~ k ",O NDON S I

P ARlS S2 " )JJ t<«(/ - "PARlS S2

PARlS S3

LON'DON S4

Lot'mON S4

LON'DO N S4

12 rows selected.--/

() \, //

Page 16: RDBMS SQL n Types of Relationships

8/8/2019 RDBMS SQL n Types of Relationships

http://slidepdf.com/reader/full/rdbms-sql-n-types-of-relationships 16/16

SQL> select p.sno,p.pno,s.sname,s.city,s.sno

2 from partsupp p,supplier s

3 where p.sno=s.sno(');

PN S:\A\1E CITY S:\

'(:(-<2C[ LL ( . - r r - r ' " ~SI

PI SMITH L01'<TIO?\SIS1 P3 SMITH

SI P2 SMITH

LONDON S1

LONDON S I cc." 1n II I - I"- rn en. t--, I ~ , . . - ;

v ir '.-/-t..k.- u:/:'

SI P4 SMITH

SI P6 SMITH

LON"DON S I

LO't',mON SI o c . . n v ~ _ - : d V O J - c £ ' ~ SIPS SMITH

S2 P2 JO NES

LO'f'..TDON S1

PARIS S2 .:; +u 4D:z.S2PIJONE S

S3 P2 BLAKE

PARlS

PARIS

S2

S3 r.; y f-Sv. fP ·

S4 P2 CLARK LONDON S4

SJ P4 CLARK LONDON S4

S4 PS CLARK LOrmaN S4

S7 PS

,2 rows se leered.

SQL > p.sno,p.;::no.s ; - : ' : : : : : : ' : - : .O. sno

2 from partsupp ~ ; : : ::

3 where p.sno (- =s.'>l:o:

SN PN SNA\o1E CITY S ~ · j(...s.J'

{{: I 7%, '

SIP 1 SM ITH

S1 P3 SMITH

~ " D O J ' \ S I

LO l'mON S1 de,f ;

f l J .-:f-'-- .... ju . ~ , I . / c . / ?

SI P2 SMITH

S1 P4 SMITH

SI P6 SMITH

SIPS SMITH

LON"DON S1

LONDON S I

LONDON S I

LOl'mON S1L :/ G

C.(.;,

& (,"p.1 0 - - I r ri-Z/'v'" I

' (

. 7 ' ) ",ch )l-' )7. '7 ':::: ?I -

52 P2 JOl\ES

S2 P I JO NES

PA.R1S S2

PARlS S2- C; vi:?-"! -&Y

S3 P2 BLAKE PARlS S3

S4 P2 CLARK LONDON S4

S4 P4 CLARK LO?"mON S4

S4 P5 CLARK LONDON S4

A D A ~ l S LOl'-lDON S5

13 rows selected.

SQL> spool off;SQL> edit 2:0Ut.!st ("'.!OTE: extension must be dot 1st)