11
Oracle ProgrammingOracle Programming
Week 1Week 1Review on the Relational Review on the Relational
Data ModelData Model Basic DefinitionsBasic DefinitionsRelational Database ConceptsRelational Database ConceptsRelational Database Management Relational Database Management SystemsSystems
Chapter 5 Elmasri & Navathe bookChapter 5 Elmasri & Navathe book
22
Basic DefinitionsBasic Definitions
Data:Data: Known facts that can be recorded and have an Known facts that can be recorded and have an implicit meaning.implicit meaning.
Database :Database : A collection of related data A collection of related data Database management system (DBMS):Database management system (DBMS):
a collection of computer programs, which enables users to a collection of computer programs, which enables users to createcreate
and maintain databasesand maintain databases
User1
Database
User2
User3 User4
33
Basic Definitions (Cont.)Basic Definitions (Cont.)
SchemaSchema: description of data at some : description of data at some level (level (e.g., e.g., tables, attributes, tables, attributes, constraints, domains)constraints, domains)
ModelModel: tools and language for : tools and language for describing:describing: Conceptual schema Conceptual schema
Data definition language (DDL)Data definition language (DDL) Integrity constraints, domains (DDL)Integrity constraints, domains (DDL) Operations on data Operations on data
Data manipulation language (DML)Data manipulation language (DML) Directives that influence the physical schema Directives that influence the physical schema
(affects performance, not semantics)(affects performance, not semantics)Storage definition language (SDL)Storage definition language (SDL)
44
RelationRelation
Relation is a set of tuples/recordsRelation is a set of tuples/recordsTuple ordering irrelevantTuple ordering irrelevantCardinality of relation = number of Cardinality of relation = number of
tuplestuplesAll tuples in a relation have the All tuples in a relation have the
same structure; constructed from same structure; constructed from the same set of attributesthe same set of attributesAttributes named (=> ordering Attributes named (=> ordering
irrelevant)irrelevant)Value of an attribute drawn from the Value of an attribute drawn from the
attribute’s domainattribute’s domain
55
General format of a relation General format of a relation when represented as a tablewhen represented as a table
AA11 AA22 AA33 …… AAnn
aa1111 aa1212 aa1313 …… aa1n1n
aan1n1 aan2n2 aan3n3 …… aannnn
Attribute orColumn Name
Row ortuple values
Attribute orColumn Name
66
ExampleExample
77
Relation as A Table (cont.)Relation as A Table (cont.)
Mathematical entity corresponding to Mathematical entity corresponding to a tablea tablerow ~ row ~ tupletuplecolumn ~ column ~ attributeattribute
Values in a tuple are Values in a tuple are related related to each to each otherotherJohn lives at 123 MainJohn lives at 123 Main
88
Relational Database Relational Database Management System (RDBMS)Management System (RDBMS)
Finite set of relationsFinite set of relationsDatabase schema = set of relations Database schema = set of relations
(and other things)(and other things)
99
Database Schema (Example)Database Schema (Example)
Student (Id: INT, Name: STRING, Address: Student (Id: INT, Name: STRING, Address: STRING, Status: STRING)STRING, Status: STRING)
Professor (Id: INT, Name: STRING, DeptId: Professor (Id: INT, Name: STRING, DeptId: DEPTS)DEPTS)
Course (DeptId: DEPTS, CrsName: STRING, Course (DeptId: DEPTS, CrsName: STRING, CrsCode: COURSES)CrsCode: COURSES)
Transcript (CrsCode: COURSES, StudId: INT, Transcript (CrsCode: COURSES, StudId: INT, Grade: GRADES, Semester: SEMESTERS)Grade: GRADES, Semester: SEMESTERS)
Department(DeptId: DEPTS, Name: STRING)Department(DeptId: DEPTS, Name: STRING)
1010
Three-schema ArchitectureThree-schema Architecture
Internal Level Internal Level Internal Schema Internal Schema Describes the physical storage structure of the Describes the physical storage structure of the
databasedatabase Conceptual Level Conceptual Level Conceptual Schema Conceptual Schema
Describes the structure of the whole database Describes the structure of the whole database for all users. It hides the storage details.for all users. It hides the storage details.
Concerned of entities (tables), data types, Concerned of entities (tables), data types, relationships, user operations and constraints.relationships, user operations and constraints.
External or View level External or View level External Schema External Schema Describes part of the database for a group of Describes part of the database for a group of
users.users.
1111
Three-schema Architecture – Three-schema Architecture – Cont.Cont.
Internal Schema
Conceptual Schema
External View External View
Stored Database
DSL
DDL, DML
DCL
1212
Data Definition Language Data Definition Language (DDL)(DDL)
Used by DBAs or designers to define Used by DBAs or designers to define schemaschema
A compiler compiles this language to A compiler compiles this language to construct the database and store its construct the database and store its constraints in DBMS catalogconstraints in DBMS catalog
Examples of DDL Commands:Examples of DDL Commands: CREATECREATE ALTERALTER DROPDROP TRUNCATE (Deletes all records in a table)TRUNCATE (Deletes all records in a table)
1313
Data Manipulation Language Data Manipulation Language (DML)(DML)
Some of its commands:Some of its commands:SELECT (Retrieves data)SELECT (Retrieves data)INSERTINSERTUPDATEUPDATEDELETEDELETE
1414
Data Control Language (DCL)Data Control Language (DCL)
Used to create roles, permissions, Used to create roles, permissions, and referential integrity and to and referential integrity and to control access on a database.control access on a database.
Example of its commands:Example of its commands:GRANT (Grants user privileges)GRANT (Grants user privileges)REVOKE (Withdraws privileges)REVOKE (Withdraws privileges)
1515
Other languagesOther languages
Data Storage Language (DSL)Data Storage Language (DSL) Specifies Internal SchemaSpecifies Internal Schema
Transactional Control Language (TCL)Transactional Control Language (TCL) Used to manage different transactions Used to manage different transactions
occurring within a database.occurring within a database.COMMIT (Saves your work)COMMIT (Saves your work)ROLLBACK (Restore database to original state since ROLLBACK (Restore database to original state since
the last COMMIT)the last COMMIT)SAVE TRANSACTION (Sets a savepoint within a SAVE TRANSACTION (Sets a savepoint within a
transaction)transaction)
1616
Integrity ConstraintsIntegrity Constraints
Part of schemaPart of schema Restriction on state (or sequence of states) Restriction on state (or sequence of states)
of databaseof database Enforced by DBMSEnforced by DBMS Intra-relational - involve only one relationIntra-relational - involve only one relation
Part of relation schemaPart of relation schema e.g., all Ids are uniquee.g., all Ids are unique
Inter-relational - involve several relationsInter-relational - involve several relations Part of relation schema or database schemaPart of relation schema or database schema
1717
Database IntegrityDatabase Integrity
Implies that the data held in the tables Implies that the data held in the tables of the database is consistent in terms of of the database is consistent in terms of the Relational Data Model the Relational Data Model
Two TypesTwo TypesEntity integrity (PK)Entity integrity (PK)Referential Integrity (FK)Referential Integrity (FK)
1818
Relation Keys ConstraintsRelation Keys Constraints
Key ConstraintKey Constraint: : Values in a column (or Values in a column (or columns) of a relation are unique: at most columns) of a relation are unique: at most one row in a relation instance can contain one row in a relation instance can contain a particular value(s) a particular value(s)
What is a Key? What is a Key? A minimal set of attributes satisfying A minimal set of attributes satisfying
key constraintkey constraint
1919
Key Constraint (con’t)Key Constraint (con’t) Every relation has a keyEvery relation has a key Candidate Key-Candidate Key-
No two tuples of the relation will have identical entries in No two tuples of the relation will have identical entries in all attributes of the key.all attributes of the key.
The number of attributes that comprises the key must The number of attributes that comprises the key must be minimal.be minimal.
Primary Key-Primary Key- Since a table may have more than one Since a table may have more than one candidate key, one should be designated as the candidate key, one should be designated as the primary primary key (PK)key (PK) of the relation. of the relation.
Examples:Examples: primary key primary key (Id in Student) –(Id in Student) – candidate key candidate key ((Name, Address) in Student)((Name, Address) in Student)
2020
Candidate Keys & Candidate Keys & Primary KeysPrimary Keys
A RDBMS allows only one primary key per table.A RDBMS allows only one primary key per table. Once a PK has been selected, any remaining candidate Once a PK has been selected, any remaining candidate
keys are called keys are called alternate alternate keys.keys. A primary key may be composed ofA primary key may be composed of
a single attribute (a single attribute (single primary keysingle primary key) ) E.g. IDE.g. ID
More than one attribute (More than one attribute (composite primary keycomposite primary key)) E.g. Code + SerialE.g. Code + Serial
An attribute that is a primary key can not have a An attribute that is a primary key can not have a nullnull value value
An attribute that is part of any key is called a An attribute that is part of any key is called a primeprime attribute. attribute.
2121
EmpIdEmpId NameName SalarySalary NINNIN DnoDno
100100 Hasan H.Hasan H. 15001500 12500111250011 100100
101101 Johns S.Johns S. 20002000 23600312360031 101101
102102 Kelly A.Kelly A. 900900 12999971299997 101101
103103 Ibrams Ibrams S.S. 11101110 23599942359994 101101
104104 Kelly A.Kelly A. 20002000 55023005502300 100100
DnoDno DnameDname LocLoc ManageManagerr
100100 FinanceFinance..
15001500 12500111250011
101101 ITIT 20002000 23600312360031
Employee Employee TableTable
DepartmentDepartmentTableTable
Example 1 Example 1
2222
EmpIdEmpId ProjIdProjIdNumberNumber
Of HoursOf Hours
100100 p22p22 1515
101101 p20p20 99
102102 p22p22 1111
100100 p23p23 2424
104104p23p23 1515
104104 p22p22 1111
Employee -ProjectEmployee -ProjectTableTable
Example 2Example 2
2323
Candidate Keys & Candidate Keys & Primary Keys (Cont.)Primary Keys (Cont.)
Primary keys are Primary keys are defined using Data Definition Language (DDL) defined using Data Definition Language (DDL) Automatically enforced by the RDBMSAutomatically enforced by the RDBMS Generally are defined at the time the tables are Generally are defined at the time the tables are
created.created. When selecting primary keys, we need to When selecting primary keys, we need to
choose attributes that satisfy the uniqueness choose attributes that satisfy the uniqueness and minimalist conditions for all permissible and minimalist conditions for all permissible data.data.
2424
NULLNULL
What isWhat is NULLNULL??a NULL value is used to represent a NULL value is used to represent
missing information, unknown, or missing information, unknown, or inapplicable data.inapplicable data.
A NULL value is not a zero valueA NULL value is not a zero valueA NULL value doesn’t represent a A NULL value doesn’t represent a
particular value within the computer.particular value within the computer.
2525
Foreign Key ConstraintForeign Key Constraint RReferential integrityeferential integrity => Item named for => Item named for primary primary
keykey attribute/s in one relation must correspond to attribute/s in one relation must correspond to tuple(s) in another that describes the itemtuple(s) in another that describes the item Employee (ProjId) references Project(ProjId)Employee (ProjId) references Project(ProjId) Professor(DeptId) references Department(DeptId)Professor(DeptId) references Department(DeptId)
a1 is a a1 is a foreign keyforeign key of R1 referring to a2 in R2 => of R1 referring to a2 in R2 => if v is a value of a1, there is a if v is a value of a1, there is a uniqueunique tuple tuple of R2 of R2 in which a2 has value vin which a2 has value v This is a special case of referential integrity: a2 must be a This is a special case of referential integrity: a2 must be a
candidate keycandidate key of R2 (DeptId is a key of Department) of R2 (DeptId is a key of Department) If no row exists in R2 => violation of referential integrityIf no row exists in R2 => violation of referential integrity Not all rows of R2 need to be referenced: relationship is Not all rows of R2 need to be referenced: relationship is
not symmetric not symmetric Value of a foreign key might not be specified (DeptId Value of a foreign key might not be specified (DeptId
column of some professor might be null)column of some professor might be null)
2626
Foreign Key Constraint Foreign Key Constraint (Example)(Example)
a2v3v5v1v6v2v7v4
a1v1v2v3v4--v3
R1 R2Foreign key
Candidate/Primary key
2727
5.7
2828
Foreign Key (con’t)Foreign Key (con’t) Names of a1 and a2 need not be the same.Names of a1 and a2 need not be the same.
With SQL tables:With SQL tables:Foreign key <name> professor (DeptId) references
Department (Dno)
DeptIdDeptId attribute of attribute of Professor TableProfessor Table references to references to DnoDno attribute inattribute in
Department TableDepartment Table
R1 and R2 need not be distinct.R1 and R2 need not be distinct. The attributes of where the referential The attributes of where the referential
integrity exists must have the same data type integrity exists must have the same data type and length. and length.
2929
Foreign Key (con’t)Foreign Key (con’t)
Foreign key might consist of several columnsForeign key might consist of several columns (CrsCode, Semester) of Transcript references (CrsCode, Semester) of Transcript references
(CrsCode, Sem) of Teaching(CrsCode, Sem) of Teaching R1(a1, …an) references R2(b1, …bn)R1(a1, …an) references R2(b1, …bn)
There exists a 1 - 1 relationship between a1,…an There exists a 1 - 1 relationship between a1,…an and b1,…bnand b1,…bn
ai and bi have same domains (although not ai and bi have same domains (although not necessarily the same names)necessarily the same names)
For every tuple For every tuple TT in R1 over ai’s there exists a in R1 over ai’s there exists a unique tuple unique tuple SS in R2 over bi’s, with in R2 over bi’s, with T = S T = S
b1,…bn is a candidate key of R2b1,…bn is a candidate key of R2
3030
Semantic ConstraintsSemantic Constraints
Domain, primary key, and foreign Domain, primary key, and foreign key are examples of structural key are examples of structural (syntactic) constraints(syntactic) constraints
Semantic constraintsSemantic constraints express express rules of application:rules of application:e.g., number of registered students e.g., number of registered students
maximum enrollmentmaximum enrollmentSQL calls them Check constraintSQL calls them Check constraint
3131
SQLSQL
Language for describing database Language for describing database schema and operations on tablesschema and operations on tables
Data Definition Language (DDL): Data Definition Language (DDL): sublanguage of SQL for describing sublanguage of SQL for describing schema and constraintsschema and constraints
3232
TablesTables
SQL entity that corresponds to a SQL entity that corresponds to a relationrelation
An element of the database schemaAn element of the database schemaSQL is current standard SQL is current standard Database vendors generally deviate Database vendors generally deviate
from standardfrom standard
3333
Table CreationTable Creation Steps in table creation:
1. Identify data types for attributes
2. Identify columns that can and cannot be null
3. Identify columns that must be unique (candidate keys)
4. Identify primary key-foreign key mates
5. Determine default values
6. Identify constraints on columns (domain specifications)
7. Create the table and associated indexes
3434
Common SQL Data Types (from Oracle)Common SQL Data Types (from Oracle)
String typesString types CHAR(n) – fixed-length character data, n characters long Maximum CHAR(n) – fixed-length character data, n characters long Maximum
length = 2000 byteslength = 2000 bytes VARCHAR2(n) – variable length character data, maximum 4000 VARCHAR2(n) – variable length character data, maximum 4000
bytesbytes LONG – variable-length character data, up to 4GB. Maximum 1 per LONG – variable-length character data, up to 4GB. Maximum 1 per
tabletable
Numeric typesNumeric types NUMBER(p,q) – general purpose numeric data typeNUMBER(p,q) – general purpose numeric data type Numeric (p, q)- general purpose numeric data typeNumeric (p, q)- general purpose numeric data type INTEGER(p) – signed integer, p digits wideINTEGER(p) – signed integer, p digits wide FLOAT(p) – floating point in scientific notation with p binary digits FLOAT(p) – floating point in scientific notation with p binary digits
precisionprecision
Date/time typeDate/time type DATE – fixed-length date/time in dd-mm-yy formDATE – fixed-length date/time in dd-mm-yy form
3535
Table Declaration in SQLTable Declaration in SQLCREATE TABLE Student ( Id, numaric(5), Name CHAR(20), AddressVARCHAR(50),Status: Boolean,Constraint Pk_Id primary key(Id));
101222333 John 10 Cedar St Freshman234567890 Mary 22 Main St Sophomore
Id Name Address Status
Student
3636
Primary, Unique, Check, Foreign, Null Primary, Unique, Check, Foreign, Null KeysKeys
Create table department ( Dno numeric(2),Dname varchar2(20),Loc varchar2(30) not null,Constraint Pk_Dno primary key(Dno)Constraint uk_name unique key(Dname));
Create table employee( Eno numeric(4),Ename varchar2(20),Salary numeric(7, 2) not null,Hire_Date Date not null,Extention char(4),DeptNo numeric(2),Constraint Pk_Eno primary key(Eno),Constraint Fk_Dno foreign key(DeptNo) reference department (Dno),Constraint ch_salary check (salary between 900 and 5000));
3737
System CatalogSystem Catalog CREATE TABLE inserts information into the CREATE TABLE inserts information into the
catalogcatalog Catalog is another table that describes Objects Catalog is another table that describes Objects
created such as:created such as: Table namesTable names Constraint namesConstraint names Role NamesRole Names Triggers, Sequences, Views, etcTriggers, Sequences, Views, etc Attribute names of different tablesAttribute names of different tables Corresponding attribute types, etc.Corresponding attribute types, etc.
Catalog schema is generally fixed by vendorCatalog schema is generally fixed by vendor In Oracle SQL this catalog is called DICTIONARYIn Oracle SQL this catalog is called DICTIONARY
3838
Circularity in Foreign Key Circularity in Foreign Key ConstraintConstraint
y x
a1 a2 a3 b1 b2 b3
x yA B
candidate key : a1foreign key : a3 references B(b1)
candidate key : b1foreign key : b3 references A(a1)
Problem 1: Creation of A requires existence of B and vice versaSolution 1: CREATE TABLE A ( ……), (* no foreign key *) CREATE TABLE B ( ……), (* foreign key included *) ALTER TABLE A ADD CONSTRAINT cons FOREIGN KEY (a3) REFERENCES B (b1)
3939
Circularity in Foreign Key Circularity in Foreign Key ConstraintConstraint
Problem 2 : Insertion of row in A requires prior Problem 2 : Insertion of row in A requires prior existence of row in B and vice versaexistence of row in B and vice versa
Solution 2 : Solution 2 : DEFERREDDEFERRED constraint check - constraint check - insert both rows within a singleinsert both rows within a single transactiontransaction
CREATE TABLE Dept (….. DeptId: CHAR (4), MngrId : INTEGER, PRIMARY KEY DeptId, FOREIGN KEY (MngrId) REFERENCES Employee (Id) )CREATE TABLE Employee ( …. DeptId : CHAR (4), Id : INTEGER, PRIMARY KEY Id, FOREIGN KEY (DeptId) REFERENCES Dept ( DeptId) )
4040
Handling Foreign Key Violations/Handling Foreign Key Violations/Anomalies Anomalies
Insert Anomaly:Insert Anomaly: Insertion into A: Reject if no row exists in Insertion into A: Reject if no row exists in
Table B containing a primary key of the Table B containing a primary key of the inserted rowinserted row
Insertion into B: No problemInsertion into B: No problem
xx
A B
4141
Handling Foreign Key Handling Foreign Key ViolationsViolations
Deletion from B: Deletion from B: Reject if the to be Reject if the to be removed is linked to other rows in Aremoved is linked to other rows in A
Deletion from A: Deletion from A: No problemNo problem
SolutionSolution SET NULLSET NULL: Set value of foreign key in referencing : Set value of foreign key in referencing
row(s) in A to nullrow(s) in A to null SET DEFAULTSET DEFAULT: Set value of foreign key in : Set value of foreign key in
referencing row(s) in A to default value (y)referencing row(s) in A to default value (y) CASCADECASCADE: Delete referencing row(s) in A as well: Delete referencing row(s) in A as well
nullA B
yA By
4242
Handling Foreign Key Handling Foreign Key Violations Violations
Update a candidate/primary key in B: Reject if row Update a candidate/primary key in B: Reject if row exists in A containing for the old valueexists in A containing for the old value
Update a foreign key in A (to z): Reject if no row Update a foreign key in A (to z): Reject if no row exists in B containing the new valueexists in B containing the new value
Update a foreign key in A (to z): Update a foreign key in A (to z): NO problem NO problem if a row if a row in B exist, which contain the new updated value in B exist, which contain the new updated value
Solution :Solution : SET NULLSET NULL: Set value of foreign key to null: Set value of foreign key to null SET DEFAULTSET DEFAULT: Set value of foreign key to default: Set value of foreign key to default CASCADECASCADE: Propagate z to foreign key: Propagate z to foreign key
4343
Specifying ActionsSpecifying Actions
CREATE TABLE Teaching ( ProfId INTEGER, CrsCode CHAR (6), Semester CHAR (6), PRIMARY KEY (CrsCode, Semester), FOREIGN KEY (ProfId) REFERENCES Professor (Id) ON DELETE CASCADE, FOREIGN KEY (CrsCode) REFERENCES Course (CrsCode) ON DELETE SET NULL ON UPDATE CASCADE )