Date post: | 22-Dec-2015 |
Category: |
Documents |
View: | 219 times |
Download: | 0 times |
1
Designing Tables for an Designing Tables for an Oracle Database SystemOracle Database System
Database Course, Fall 2004
2
From theory to practiceFrom theory to practice
• The Entity-Relationship model: a convenient way of representing the world.
• The Relational model: a model of organizing data using tables.
• Oracle: a database infrastructure which implements the relational model.
• Converting ER->Relational model is important!
• SQL(Structured Query Language): A language used to get information from an oracle database.
3
TechnicalitiesTechnicalities
• Add the following to your .cshrc file:
source ~db/oraenv
• You will be able to use Oracle after you log
out and log in again.
• You can run Oracle from os, pita, inferno,
etc. Cannot run from xil-es.
• If you are on xil, do rlogin to one of these
computers (e.g., rlogin inferno-01)
4
Connecting to the Oracle Connecting to the Oracle DatabaseDatabase
At the command line prompt, write:
sqlplus login/[email protected]
In the beginning your password is the same as your login. You can change your password with the command:
password
To disconnect, type: quit
Remember: (almost) Every command must end with a semicolon (;)
5
Running Commands from Running Commands from an .sql Filean .sql File
• Instead of typing commands into the SQLPLUS terminal, you can load commands from a file (no special format is required).
• Invoke by:1. Use the command @file from SQLPLUS to load the file
file.sql
Or:
2. Invoke the SQLPLUS command with the extra parameter @file to load the file at connection:
sqlplus login/[email protected] @file
6
Spooling the OutputSpooling the Output
• Output can be placed in a file:
– spool myFile.out
(output file updates after next command)
• Spooling can be turned off with:
– spool off
7
TablesTables
• The basic element in oracle is a table.
• A table has columns (attributes), and rows
(tuples).
• Every column has a Name and Type (of the
data it stores), and some columns have
constraints.
• Some tables may have additional
constraints.
8
Creating Tables in SQLCreating Tables in SQL
Id Name Dept. Age
0345 Eyal Sales 28
0965 Yair Transport 34
7665 Ori Warehous
e
31
9
Creating a TableCreating a Table
The basic format of the CREATE TABLE
command is:
CREATE TABLE TableName(
Column1 DataType1 ColConstraint, …
ColumnN DataTypeN ColConstraint,
TableConstraint1, …
TableConstraintM
);
10
An ExampleAn Example
CREATE TABLE Employee(ID NUMBER NOT NULL,Fname VARCHAR2(20),Lname VARCHAR2(20),Gender CHAR(1),Salary NUMBER(5) NOT NULL,Dept NUMBER
);
11
An Example (cont.)An Example (cont.)
Oracle is case insensitive in Column names!
If you type describe Employee you get:Name Null? Type
----------- ------------ ------------
SSN NOT NULL NUMBER
FNAME VARCHAR2(20)
LNAME VARCHAR2(20)
GENDER CHAR(1)
SALARY NOT NULL NUMBER(5)
DEPT NUMBER
Notice that “describe” describes the structure and not the contents of the table.
12
13
Examples of Data TypesExamples of Data Types
CHAR(n) String of length n (n <= 2000)
VARCHAR2(n) Variable length string of size <= n (n <=
4000)
LONG Variable length string of length (<= 2GB)
CLOB Character large object (<= 4GB)
BLOB Binary large object (<= 4GB)
DATE Valid dates (up to seconds)
TIMESTAMP Valid timestamps (up to milliseconds)
NUMBER Up to 40 digits
NUMBER(n) Integer of size n
NUMBER(n,m) Number of size n with m digits after
decimal place
Others XML, Abstract types, etc.
14
• What happens if we insert:– 'abc' into char(5)?
– 'abc' into varchar(5)?
– 'abc' into char(2)?
– 'abc' into varchar(2)?
– 105.32 into number(3,2)?
– 105.32 into number(5,2)?
– 105.32 into number(4,1)?
– 105.32 into number(3)?
– 105.32 into number?
– 105.1 into number(7,5) ?
• Why not always use number and not number(n,m)?
• Why not always use varchar2(4000) or long?
• Where is the boolean datatype?
“abc““abc “
105.32
Wrong!
105.32
105.3105
Wrong!
Wrong!
Wrong!
15
Constraints in Create TableConstraints in Create Table
• Adding constraints to a table enables the database system to enforce data integrity.
• However, adding constraints also makes inserting data slower.
• Different types of constraints:
* Not Null * Default Values
* Unique * Primary Key
* Foreign Key * Check Condition
16
Not Null ConstraintNot Null Constraint
CREATE TABLE Employee(SSN NUMBER NOT NULL,Fname VARCHAR2(20),Lname VARCHAR2(20),Gender CHAR(1),Salary NUMBER(5) NOT NULL,Dept NUMBER
);
17
Default Values Default Values
CREATE TABLE Employee(SSN NUMBER NOT NULL,Fname VARCHAR2(20),Lname VARCHAR2(20),Gender CHAR(1) DEFAULT(‘F’),Salary NUMBER(5) NOT NULL,Dept NUMBER
);
18
Unique Constraint (Syntax Unique Constraint (Syntax 1)1)
CREATE TABLE Employee(SSN NUMBER UNIQUE NOT NULL,Fname VARCHAR2(20),Lname VARCHAR2(20),Gender CHAR(1) DEFAULT(‘F’),Salary NUMBER(5) NOT NULL,Dept NUMBER
);
19
Unique Constraint (Syntax Unique Constraint (Syntax 2)2)
CREATE TABLE Employee(SSN NUMBER NOT NULL,Fname VARCHAR2(20),Lname VARCHAR2(20),Gender CHAR(1) DEFAULT(‘F’),Salary NUMBER(5) NOT NULL,Dept NUMBER,UNIQUE(SSN)
);
20
Unique Constraint Unique Constraint (Another Example)(Another Example)
CREATE TABLE Employee(SSN NUMBER UNIQUE NOT NULL,Fname VARCHAR2(20),Lname VARCHAR2(20),Gender CHAR(1) DEFAULT(‘F’),Salary NUMBER(5) NOT NULL,Dept NUMBER,UNIQUE(Fname, Lname)
);
How else can this be written?
21
Primary Key ConstraintPrimary Key Constraint
CREATE TABLE Employee(SSN NUMBER PRIMARY KEY,Fname VARCHAR2(20),Lname VARCHAR2(20),Gender CHAR(1) DEFAULT(‘F’),Salary NUMBER(5) NOT NULL,Dept NUMBER,UNIQUE(Fname, Lname)
);
Primary Key implies: * NOT NULL * UNIQUE. There can only be one primary key.
22
Primary Key Constraint Primary Key Constraint (Syntax 2)(Syntax 2)
CREATE TABLE Employee(SSN NUMBER,Fname VARCHAR2(20),Lname VARCHAR2(20),Gender CHAR(1) DEFAULT(‘F’),Salary NUMBER(5) NOT NULL,Dept NUMBER,UNIQUE(Fname, Lname),PRIMARY KEY(ssn)
);
23
Another TableAnother Table
CREATE TABLE Department(Dept NUMBER PRIMARY KEY,Name VARCHAR2(20),ManagerId NUMBER
);
Shouldn’t all department numbers in Employee appear in Department?
24
Foreign Key ConstraintForeign Key ConstraintCREATE TABLE Employee(
ID NUMBER PRIMARY KEY,Fname VARCHAR2(20),Lname VARCHAR2(20),Gender CHAR(1) DEFAULT(‘F’),Salary NUMBER(5) NOT NULL,Dept NUMBER, UNIQUE(Fname, Lname),FOREIGN KEY (Dept) REFERENCES
Department(Dept));
NOTE: Dept must be unique (or primary key) in Department
25
Foreign Key Constraint Foreign Key Constraint (Syntax 2)(Syntax 2)
CREATE TABLE Employee(ID NUMBER PRIMARY KEY,Fname VARCHAR2(20),Lname VARCHAR2(20),Gender CHAR(1) DEFAULT(‘F’),Salary NUMBER(5) NOT NULL,Dept NUMBER, UNIQUE(Fname, Lname),FOREIGN KEY (Dept) REFERENCES
Department);
NOTE: Dept must be the name of the field in Department, too
26
Foreign KeyForeign Key
ID FName LName Gende
r
Sallary Dept
02334 Larry Bird M 230000 12
04556 Magic Johnson M 270000 45
Foreign Key
Dept Name ManID
12 Sales 988
45 Repair 876
Employee
Department
27
Understanding Foreign Understanding Foreign KeysKeys
• The constraint on the last table should be read as:
“The field Dept in Employee is a foreign key that
references the field Dept in Department”
• Meaning: Every non-null value in the field Dept of
Employee must appear in the field Dept of
Department.
What happens to Employees in department 312 when Department 312 is removed from the Department table?
28
Deleting a Referenced Deleting a Referenced ValueValue
• If nothing additional is specified, then Oracle will not allow Department 312 to be deleted if there are Employees working in this department.
• If the constraint is written as
FOREIGN KEY (Dept) REFERENCES Department ON DELETE CASCADE
then Employees working in 312 will be deleted automatically from the Employee table, when 312 is deleted from Departments
29
Cyclic Foreign KeysCyclic Foreign Keys
CREATE TABLE Department(Dept NUMBER PRIMARY KEY,Name VARCHAR2(20),ManagerId NUMBER, FOREIGN KEY (ManagerId) REFERENCES Employee(SSN)
);
Do you see a problem in defining these tables and in inserting data now?
We should revise the Department table:
30
Foreign KeyForeign Key
ID FName LName Gender Sallary Dept
Foreign Key
Dept Name ManID
31
Solution to Cyclic Solution to Cyclic ConstraintsConstraints
Add one of the constraints later on (after insertion):
CREATE TABLE Department(Dept NUMBER PRIMARY KEY,Name VARCHAR2(20),ManagerId NUMBER);
Insert data here…
ALTER TABLE Department
ADD(FOREIGN KEY (ManagerId)
REFERENCES Employee(SSN));
32
Check ConditionsCheck Conditions
• A check condition is a Boolean expression:
– “And”s and “Or”s of conditions of the type X >
5…
• On a column: it can refer only to the column
• On a table: it can refer only to multiple
columns in the table
33
Check ConstraintsCheck Constraints
CREATE TABLE Employee(SSN NUMBER PRIMARY KEY,Fname VARCHAR2(20),Lname VARCHAR2(20),Gender CHAR(1) DEFAULT(‘F’)
CHECK(Gender = ‘F’ or Gender = ‘M’) ,Salary NUMBER(5) NOT NULL,CHECK (Gender = ‘M’ or Salary > 10000)
);
34
Deleting a TableDeleting a Table
• To delete the table Employee :
DROP TABLE Employee;
• Mind the order of dropping when there are
foreign key constraints. Why?
• Can use:
DROP TABLE Employee cascade constraints;
35
Translating ER-Diagrams to Translating ER-Diagrams to Table DefinitionsTable Definitions
36
Relations vs. TablesRelations vs. Tables
• We show how to translate ER-Diagrams to table definitions
• Sometimes, people translate ER-Diagrams to relation definition, which is more abstract than table definitions.– e.g., Employee(SSN, Fname, Lname, Gender,
Salary, Dept);
– table definitions contain, in addition, constraints and datatypes
37
Simple entity translationSimple entity translation
General Rule:
• Create a table with the name of the Entity.
• There is a column for each attribute
• The key in the diagram is the primary key of the table
Actorid
name address
birthday
38
Simple entity translationSimple entity translation
create table Actor(id varchar2(20) primary key,
name varchar2(40),
birthday date,
address varchar2(100));
Actorid
name address
birthday
Relation: Actor (id, name, birthday, address)
39
Translating Entities with Translating Entities with Relationships Relationships (without constraints)(without constraints)
• Create tables for the entities as before
• Create a table with the name of the relationship
• Relationship table attributes: its own attributes (salary) + all keys of the relating entities (title, id).
Q: What is the primary key of the table?
A: A composite of both entity keys
Q: What foreign keys are needed?
A: From the relationship table to the entities
Actorid
name
address
birthday
Acted In Film
title
type
year
salary
40
Translating relationships Translating relationships (without constraints)(without constraints)
What would be the relation for ActedIn?
How would you define the table for ActedIn?
Actorid
name
address
birthday
Acted In Film
title
type
year
salary
41
Translating Recursive Translating Recursive Relationships Relationships
(without constraints)(without constraints)
Employeeid
name
address
Manages
manager
worker
Relation: Manages (Wid, Mid)
What would be the table definition?create table Manages( Eid varchar2(20), Mid varchar2(20), Foreign key Eid references Employee(id), Foreign key Mid references Employee(id), Primary key(Eid, Mid));
If we want to make sure an employee is not his own manager we
can express it with Check
42
Translating relationshipsTranslating relationships(key constraints): Option 1(key constraints): Option 1
Option 1:
• Same as without key constraints (3 tables), except that the relationship primary key is…?
title.
Directorid
name
Directed Film title
salary year
43
Translating relationshipsTranslating relationships(key constraints): Option 1(key constraints): Option 1
create table Directed(
id varchar2(20),
title varchar2(40),
salary integer,
primary key (title),
foreign key id references Director,
foreign key title references Film);
Directorid
name
Directed Film title
salary year
44
Translating relationshipsTranslating relationships(key constraints): Option 2(key constraints): Option 2
Option 2:• Do not create a table for the relationship
• Add information columns that would have been in the relationship's table to the table of the entity with the key constraint
• Why couldn’t we do this with a regular relation?
Directorid
name
Directed Film title
salary year
45
Translating relationshipsTranslating relationships(key constraints): Option 2(key constraints): Option 2
create table Film(
title varchar2(40),
year integer,
primary key (title),
id varchar2(20),
salary integer,
foreign key(id) references Director);
Directorid
name
Directed Film title
salary year
46
Translating relationshipsTranslating relationships(key constraints)(key constraints)
• What are the different options for
translating this diagram?
A R B
C
47
Translating relationshipsTranslating relationships(participation constraints)(participation constraints)
General Rule:
• If both participation and key constraint exist, use
Option 2 from before (only 2 tables).
• Add the not null constraint to ensure that there will
always be values for the key of the other entity
Directorid
name
Directed Film title
salary year
48
Translating relationshipsTranslating relationships(participation constraints)(participation constraints)
create table Film(
title varchar2(40),
year integer,
id varchar2(20),
salary integer,
foreign key (id) references Director,
primary key (title));
Directorid
name
Directed Film title
salary year
Where should we add NOT NULL?
49
Translating relationshipsTranslating relationships(participation constraints)(participation constraints)
• How would we translate this?
Actorid
name
Acted In Film title
salary year
50
Translating Weak Entity Translating Weak Entity SetsSets
create table award(
name varchar2(40),
year integer,
money number(6,2),
o_name varchar2(40),
primary key(name, year, o_name),
foreign key (o_name) references Organization(name)
on delete cascade
)
Award
Organization
Gives
year
name
name
phonenumber
money
51
Translating ISA:Translating ISA:Option 1Option 1
create table MoviePerson( ... )
create table Actor(id varchar2(20),
picture bfile,
primary key(id),
foreign key (id) references MoviePerson))
create table Director(...)
Movie Person
ISA
id
name
address
picture DirectorActor
52
Translating ISA:Translating ISA:Option 2Option 2
No table for MoviePerson!
create table Actor(id varchar2(20),
address varchar2(100),
name varchar2(20),
picture blob,
primary key(id));
create table Director(...)
Movie Person
ISA
id
name
address
picture DirectorActor
53
Which Option To Choose?Which Option To Choose?
• What would you choose if:
– Actor and Director DO NOT COVER
MoviePerson?
– Actor OVERLAPS Director?
54
Translating Translating AggregationAggregation
• Create table for Won using:– key of ActedIn
– key of Award (careful, award is a weak entity)
Actorpicture
Filmyear
typetitle
Acted Insalary
Award
Organization
Gives
year
name
name
phonenumber
Won
55
SummarySummary
Tables Primary key Remarks
Simple Entity Single table The entity key a column for
each attr.
Simple
Relationship
3 (2 entities
+relationship)
For the
relation: Both
entity keys
Foreign keys
from rel. Table
Key constraint 3 as before or
2 (one for each
entity)
Key of
constrained
ent.
Foreign keys
from rel. Table
Foreign key from
constr. Entity
Key and
Participation
constr.
2 Regular Constrained
entity has a
non-null f. key
56
Tables Primary key Remarks
Weak Entity 2: parent and
weak entities
Weak: its own
and parent
keys
Foreign keys
from weak ent.
ISA: covers
and no
overlap
2: only child
entities
Parent key
ISA: otherwise 3: parent and
child entities
Parent key Foreign keys
from child ent.
Aggregation 3: 2
aggregates
and
relationship
For
relationship:
keys of both
aggregates
Foreign keys
from
relationship
table