0% found this document useful (0 votes)
23 views603 pages

Final

Logical database design transforms the conceptual data model into a logical data model using the relational data model. The relational data model is chosen and the DBA must select a DBMS. Relations are defined using attributes and primary keys. Relationships between relations are represented using foreign keys. Various types of relationships like one-to-one, one-to-many, and many-to-many are mapped. The document also discusses mapping weak entities, associative entities, unary relationships, ternary relationships, and superclass/subclass relationships to relations. Integrity constraints like domain constraints, entity integrity, and referential integrity are also explained.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views603 pages

Final

Logical database design transforms the conceptual data model into a logical data model using the relational data model. The relational data model is chosen and the DBA must select a DBMS. Relations are defined using attributes and primary keys. Relationships between relations are represented using foreign keys. Various types of relationships like one-to-one, one-to-many, and many-to-many are mapped. The document also discusses mapping weak entities, associative entities, unary relationships, ternary relationships, and superclass/subclass relationships to relations. Integrity constraints like domain constraints, entity integrity, and referential integrity are also explained.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 603

Logical Database Design

Logical database design is the process


of transforming the conceptual data
model into logical data model
Relational Data Model will be used in
this regard
DBA has to decide DBMS at this stage
Relational Data Model
Following are the reasons to choose the
Relational Data Model
1. Based on concrete mathematical
theory
2. Most commonly used Data Model
3. Lot of CASE tools exists
4. Some of principals also apply to the
other Data Models
Relation
We can express the relation using the short-
hand notation as:
EMPLOYEE(Emp_ID, Name, Dept_Name,Salary)

CUSTOMER

Customer_ID Customer_Name Address City State


Primary Key
An attribute(Column) or combination of
attributes that uniquely identify each row
in a relation
In short notation we can express this relation
as:
EMPLOYEE(Emp_ID,Name,Dept_Name,Salary)
Composite Key is Primary Key that consists of
more than one attributes
Foreign Key
Relationships in ERD are presented
using the foreign key at logical level
An attribute (primary key) in a
relation of a database that serves as
attribute (mostly part of composite
key )of another relation in the same
database
Schema of a Database
Transformation EER\Relations
The process of converting EER diagram
into Relation consist of different steps
In ER we have:
Entities(Regular,Weak,Associative),
Relationship(Degree,Cardinality)
Attributes(Single value,Multi-
values,Composite,Derived etc.)
Transformation
Step 1: Map Strong entities
Step 2: Map Weak Entities
Step 3: Map Binary Relationship
Step 4: Map Associative Entities
STEP 5: Map Unary Relationship
Step 6: Map Ternary Relations
Step 7: Map Super/Sub
STEP 1: Map Regular Entities
EMPLOYEE
Employee_ID
Employee_Name
Address

EMPLOYEE

Employee_ID Employee_Name Address


STEP 1: Map Regular Entities (Composite
Attributes)

EMPLOYEE
Employee_ID
Employee_Name
Address(Stree_Address, City, State)
EMPLOYEE

Employee_ID Employee_Name City Street_Address State


STEP 1: Map Regular Entities (Multi-Valued)
EMPLOYEE
Employee_ID
Employee_Name
Dept_Name
{Skill}
EMPLOYEE
Employee_ID Employee_Name Dept_Name

EMPLOYEE_SKILL
Employee_ID Skill
EMPLOYEE
Emp_ID Name Dept_Name Skill

100 Margaret Marketing Dbms,Marketing

140 Allen Accounting Java

110 Chris Info Systems C++,Oracle

190 Lorenzo Finance Analyst

150 Susan Marketing C#


EMPLOYEE Skill
Emp_ID Skill

Emp_ID Name Dept_Name 100 Dbms

100 Margaret Marketing 100 Marketing

140 Allen Accounting 140 Java

110 Chris Info Systems 110 C++

190 Lorenzo Finance 110 Oracle

150 Susan Marketing 190 Analyst

150 C#
Step 2: Map Weak Entities
Weak entity is an entity type whose
existence depends on some other
entity type(Strong)
1. Define a new table for each weak
entity
2. The primary key of strong entity
relation serve to make foreign key in
the weak entity relation
Step 2: Map Weak Entities
Surrogate primary key
A serial number or other system
assigned primary key for a relation
Step 3: Map Binary Relationship
A relationship between two entities
known as binary relationship
The cardinality of Binary Relationship
can be of following types:
1:M
M:N
1:1
Step 3: Map Binary Relationship
One to Many Relationship(1:M)
1. Create relations(tables) for each entity
type participating in relationship
2. Include primary key attribute of one
side entity type in the table of many
side entity type as a foreign key
CUSTOMER ORDER
Customer_ID Submit Order_ID
Customer_Name Order_Date
Customer_Address

CUSTOMER
Customer_ID Customer_Name Customer_Address

ORDER

ORDER_ID Order_Date Customer_ID


Step 3: Map Binary Relationship
Many to Many Relationship(M:N)
In M:N relationship we have to create
three relations in spite two
Two relation based on Entity types involved
in relationship
Third relation is based on relationship
type
The primary key attributes of the first
relation work as foreign keys in this relation
Date_Assigned

EMPLOYEE PROJECT
Employee ID Project ID
Employee Name Is_assigned Description

EMPLOYEE
Employee_ID Employee_Name

ASSIGNMENT
Employee_ID Project_ID Date_Assigned

PROJECT
Project_ID Project_Description
Step 3: Map Binary Relationship
One-to-One Relationship(1:1)
1. Two relations(tables) are created
one for each participating entity
2. Primary key of one of relation is
included as foreign key in the other
relation
Employee_ID Employee_Name Department_ID Department_Name

EMPLOYE DEPARTMENT

Manages

EMPLOYEE
Employee_ID Employee_Name

Department
Department_ID Department_Name Employee_Manager
Step 4: Map Associative Entities
M:N relations may be converted into
Associative Entities
The process of Associative Entities is
same as the Many-to-Many binary
relationship
There may be two situations(identifier
defined or not defined)
Identifier Not Defined
Identifier Defined
STEP 5: Map Unary Relationship
Unary One-to-Many
The Unary entity type is mapped using
the procedure of Step 1
A recursive foreign key also included
in the relation
Recursive foreign key reference the
primary key value of same relation
Unary One-to-Many

Supervise EMPLOYE

EMPLOYEE
Employee_ID Employee_Name Birth_Place Supervisor_ID
STEP 5: Map Unary Relationship
Unary Many-to-Many
Two relations are created one for the
entity type and other for relationship
A recursive foreign key also included
in the relation
Recursive foreign key reference the
primary key value of same relation
ITEM
Contains

•ITEM(Item_No,Name,Unit_Cost)

•COMPONENT(Item_No, Component_No,
Quantity)
Unary Many-to-Many

COURSE
Course ID
Course Title
Is_
Prerequisite_
For
Many-to-Many Relationship
Is_
COURSE Prerequisite_
Course ID For
Course Title
Step 6: Map Ternary Relations
Ternary relationship is a relationship type in
which three participating entities are
involved
Good ER design is to convert this type of
relationship into three binary relationships
by making associative entity
We can transform ternary relation into tables
without this simplification
Step 6: Map Ternary Relations
1. Make a table for each participating
entity
2. Make one table for the relationship
3. The primary keys of all
participating tables work as foreign
key in relationship table
PART

VENDOR Supplies WAREHOUSE

Shipping_mode Unit_cost

•VENDER(….)

•PART(…….)

•WAREHOUSE(…….)

•SUPPLY_SCHEDULE(Part_No,Vendor_ID,Ware
house_ID,Shipping_Mode,Unit_cost)
Step 7: Map Super/Sub
Relational data model did not support
Super/Sub Model. Following guidelines can
be uses:
1. Create separate relation for Super type
and each Sub
2. Assign common attributes to Super
Relation
3. Assign Primary key of Super to Sub
tables
Step 7: Map Super/Sub
Many strategies can be used to convert Super\Sub
relation, Most commonly used guidelines are as
following:
1. Create a separate relation for the supertype and for
each of its subtypes.
2. Assign to the relation created for the supertype the
attributes that are common
3. Assign to the relation for each subtype the primary
key of the supertype and unique attributes of
subtype.
4. Assign one (or more) attributes of the supertype to
function as the subtype discriminator
Step 7: Map Super/Sub
Step 7: Map Super/Sub
Transformation
Step 1: Map Strong entities
Step 2: Map Weak Entities
Step 3: Map Binary Relationship
Step 4: Map Associative Entities
STEP 5: Map Unary Relationship
Step 6: Map Ternary Relations
Step 7: Map Super/Sub
Example 1
Example 2
INTEGRITY CONSTRAINTS
Integrity Constraints
Data Integrity refers to the
correctness and consistency of
stored data
Integrity constraints are the
rules(Business rules) that the database
users are not permitted to violate
Integrity Constraints
Common type of integrity constraints
are:
1. Domain Constraints
2. Entity Integrity
3. Referential Integrity
4. General Constraints
Domain Constraints
All of the values that appear in a column of a relation
must be from the same domain.
A domain is the set of values that may be assigned to
an attribute.
A domain definition usually consists of the following
components:
domain name,
meaning,
data type,
size (or length),
allowable values or allowable range (if applicable).
Integrity Constraints
Entity Integrity
This rule applies on the primary key
attribute of a relation
According to the Entity integrity rule,
Primary Key should be unique
no primary key attribute( or component
of a primary key attribute) can be Null
Referential Integrity
Association between the tables are
defined using the foreign keys
Referential Integrity is a constraint
on foreign key values
Either the foreign the value must
match with the primary key of its
home relation or it must be
completely Null
CUSTOMER

Customer_ID Customer_Name Address City State

ORDER

Order_ID Order_Date Customer_ID

ORDER LINE
Order_ID Product_ID Quantity

PRODUCT
Product_ID Product_Description Price
Integrity Constraints
General Constraints
General constraints are the
restrictions that are expressible only
as arbitrary predicates about the data
Suppose in university database no
class may be scheduled for room H221
after 2 P.M
Review
Top Down Process of database design
1. Enterprise Modeling
2. Data Modeling(Analysis)
1. Output of analysis is EERD and Business Rules
3. Logical Database design
1. Convert ERD into relations
4. Validate relations well-structured-ness
using Normalization process
Normalization as Database
Design(Bottom Up )
In top down process(ER diagramming)
we start from un-detailed concepts such
as entities work toward detailed
relations and their attributes
Normalization could be used as an
another design approach
Normalization is bottom-up
Normalization as Database
Design(Bottom Up )
Normalization if used for design can be uses
as follows:
Collect attribute of Organization
Write them in tabular form
Perform Normalization
Create EERD
Normalization
Normalization start from detailed set of
attributes and work upward to
correctly structured relations, each
of which represent a real-world entity
type, and whose foreign keys
represent relationship that also exist
in real world
Normalization
Normalization is a step by step
(1NF,2NF,3NF,..) process of converting
a relation(universal relation) into a well
structured relations(Free of
anomalies)
Well Structured Relation
A relation that contains minimum
redundancy and allows user to insert,
modify and delete the rows in table
without errors and inconsistencies
Relation without anomalies
Anomaly
Redundancies in a table may result
errors or inconsistencies called
anomalies
Anomalies are of three types:
1. Insertion anomaly
2. Deletion anomaly
3. Modification anomaly
Anomaly
Insertion Anomaly–adding new rows
forces user to create duplicate data
Deletion Anomaly–deleting rows may
cause a loss of data that would be
needed for other future rows
Modification Anomaly–changing data
in a row forces changes to other rows
because of duplication
EMPLOYEE
Emp_ID Name Dept_Name Salary Course_ Date_com
Title pleted
100 Margaret Marketing 48,000 SPSS 6/19/2001
100 Margaret Marketing 48,000 Surveys 7/19/1998
140 Allen Accounting 52,000 Tex_Acc 12/19/2001
110 Chris Info Systems 20,000 C++ 1/20/1997
110 Chris Info Systems 20,000 Database 12/19/2001
190 Lorenzo Finance 55,000
150 Susan Marketing 35,000 java 11/19/1990
150 Susan Marketing 35,000 C++ 12/19/2001
Normalization
Normalization is the process of
decomposing relations(attributes)
with anomalies to produce smaller,
well-structured relations(relations
without anomalies)
Normalization Steps
Attributes or table with
repeating values(Universal Relation) Remove repeating
values
First Normal Form(1NF)
Remove Partial
Dependencies
Second Normal Form(2NF)
Remove transitive
Dependencies
Third Normal Form(3NF)
Remove multi-valued
Dependencies
Fourth Normal Form(4NF)
Dependency Structure
Normal forms are based on certain
dependencies
1. 3NF and lower are based on
Functional Dependencies(FDs)
2. 4NF is based on Multi-valued
dependencies
3. 5NF is based on projection-join
dependencies
Functional Dependencies
A constraint between two attributes or
set of attributes
For any relation R attribute B is
functionally dependent on attribute
A if the value of A uniquely
determines the value of B
Each value of A is associated with
exactly one value of B
Last Lecture….
Transformation
Unary
Ternary
Super/Sub Conversion
Integrity Constraints:
1. Domain Constraints
2. Entity Integrity (Primary Key Rule)
3. Referential Integrity (Foreign Key Rule)
4. General Constraints (Business Rules)
A nonprofit organization depends on a number of different
types of persons for its successful operation. The
organization is interested in the following attributes for all
of these persons: SSN, Name, Address, City/State/Zip, and
Telephone. Three types of persons are of greatest
interest: employees, volunteers, and donors. Employees
have only a Date Hired attribute, and volunteers have only
a Skill attribute. Donors have only a relationship (named
Donates) with an Item entity type. A donor must have
donated one or more items, and an item may have no
donors, or one or more donors. There are persons other
than employees, volunteers, and donors who are of
interest to the organization, so that a person need not
belong to any of these three groups. On the other hand, at
a given time a person may belong to two or more of these
groups (e.g., employee and donor).
Tables
PERSON(SSN, Name,Address, City, State, ZipCode, Telephone, E, V, D)

EMPLOYEE(SSN, Date_Hired, PNO, Responsibility)


VOLUNTEER(SSN)
VOLUNTEER_Skill(SSN, Skill)
DONOR(SSN)
DONATION(SSN, ITEM_CODE,)
ITEM(ITEM_CODE, Description)
PROJECT(PNO, Pname, Start Date, Budget, [Days Passed])
Review
Top Down Process of database design
1. Enterprise Modeling
2. Data Modeling(Analysis)
1. Output of analysis is EERD and Business Rules
3. Logical Database design
1. Convert ERD into relations
4. Validate relations well-structured-ness
using Normalization process
Normalization as Database
Design(Bottom Up )
Normalization if used for design can be uses
as follows:
Collect attribute of Organization
Write them in tabular form (Universal
Table)
Perform Normalization
1NF..2NF…3NF…
Create EERD
Normalization
Normalization is a step by step
(1NF,2NF,3NF,..) process of converting
a relation(universal relation) into a well
structured relations(Free of
anomalies)
Normalization
Normalization is a step by step
(1NF,2NF,3NF,..) process of converting
a relation(universal relation) into a well
structured relations(Free of
anomalies)
Well Structured Relation
A relation that contains minimum
redundancy and allows user to insert,
modify and delete the rows in table
without errors and inconsistencies
Relation without anomalies
Anomaly
Redundancies in a table may result
errors or inconsistencies called
anomalies
If we face problems OR Data Loss in
performing basic operations on a table:
1. Insert
2. Delete
3. Modification
Anomalies in Table
Anomalies are of three types:
1. Insertion anomaly
2. Deletion anomaly
3. Modification anomaly
Anomaly
Insertion Anomaly–adding new rows
forces user to create duplicate data
Deletion Anomaly–deleting rows may
cause a loss of data that would be
needed for other future rows
Modification Anomaly–changing data
in a row forces changes to other rows
because of duplication
EMPLOYEE
Emp_ID Name Dept_Name Salary Course_Title Date_compl
eted
100 Margaret Marketing 48,000 SPSS 6/19/2001
100 Margaret Marketing 48,000 Surveys 7/19/1998
140 Allen Accounting 52,000 Tex_Acc 12/19/2001
110 Chris Info Systems 20,000 C++ 1/20/1997
110 Chris Info Systems 20,000 Database 12/19/2001
190 Lorenzo Finance 55,000 XY
150 Susan Marketing 35,000 java 11/19/1990
150 Susan Marketing 35,000 C++ 12/19/2001

Question–Is this a relation? Yes: Unique rows and no multivalued column


Question–What’s the primary key? Composite: EmpID, CourseTitle
Anomalies in the Table
Insertion–can’t enter a new employee
without having the employee take a
course
Deletion–if we remove employee 140,
we lose information about the existence
of a Tax Acc course
Modification–giving a salary increase
to employee 100 forces us to update
multiple records
Why do anomalies exist?
Because there are two themes
(entity types) in this one relation.
This results in data duplication and
an unnecessary dependency
between the entities
Why do anomalies exist?

Theme Theme
? ?
Normalization
Normalization is the process of
decomposing relations(attributes)
with anomalies to produce smaller,
well-structured relations(relations
without anomalies)
Normalization Steps
Attributes or table with
Multi values(Universal Relation) Remove Multi
values
First Normal Form(1NF)
Remove Partial
Dependencies
Second Normal Form(2NF)
Remove transitive
Dependencies
Third Normal Form(3NF)
Remove multi-valued
Dependencies
Fourth Normal Form(4NF)
Dependency Structure
Normal forms are based on certain
dependencies
1. 3NF and lower are based on
Functional Dependencies(FDs)
2. 4NF is based on Multi-valued
dependencies
3. 5NF is based on projection-join
dependencies
Functional Dependencies
A constraint between two attributes or
set of attributes
For any relation R attribute B is
functionally dependent on attribute
A if the value of A uniquely
determines the value of B
Each value of A is associated with
exactly one value of B
Functional Dependencies
Notationaly represented as A→B
“A functionally determines B”
Such as:
Emp_ID→Name
Emp_ID→Address
Emp_ID→Birth_date
ISBN→Title,Author_Name
EMPLOYEE_1
Emp_ID Name Dept_Name Salary

100 Margaret Marketing 48,000


140 Allen Accounting 55,000
110 Chris Info Systems 20,000
190 Lorenzo Finance 55,000
150 Allen Marketing 35,000

Emp_ID→Name ,Dept_Name,Salary
Functional Dependencies
Determinant: In A→B the attribute on
left side of aero is known as
determinant
Candidate Key: An attribute, or
combination of attributes, that uniquely
identify a row in a table
Unique identification
No redundancy
EMPLOYEE_1
Emp_ID Name Dept_Name Salary

100 Margaret Marketing 48,000


140 Allen Accounting 55,000
110 Chris Info Systems 20,000
190 Lorenzo Finance 55,000
150 Susan Marketing 35,000

Emp_ID→Name ,Dept_Name,Salary
EMPLOYEE2
Emp_ID Name Dept_Name Salary Course_ Date_com
Title pleted
100 Margaret Marketing 48,000 SPSS 6/19/2001
100 Margaret Marketing 48,000 Surveys 7/19/1998
140 Allen Accounting 52,000 Tex_Acc 12/19/2001
110 Chris Info Systems 20,000 C++ 1/20/1997
110 Chris Info Systems 20,000 Database 12/19/2001
190 Lorenzo Finance 55,000 X
150 Susan Marketing 35,000 java 11/19/1990
150 Susan Marketing 35,000 C++ 12/19/2001
Functional Dependency
In FDs we have following situations;
1. Fully Functional Dependency: Key
attribute determines non-key attribute or
set of attributes
2. Partially Functional Dependency: Part
of key attribute determines non key
attributes or set of attributes
3. Transitive Dependency: Non-key
attribute determine non-key attribute or
set of attributes
EMPLOYEE_1
Emp_ID Name Dept_Name Salary

100 Margaret Marketing 48,000


140 Allen Accounting 55,000
110 Chris Info Systems 20,000
190 Lorenzo Finance 55,000
150 Susan Marketing 35,000

Emp_ID→Name ,Dept_Name,Salary
EMPLOYEE2
Emp_ID Name Dept_Name Salary Course_ Date_com
Title pleted
100 Margaret Marketing 48,000 SPSS 6/19/2001

100 Margaret Marketing 48,000 Surveys 7/19/1998

140 Allen Accounting 52,000 Tex_Acc 12/19/2001

110 Chris Info Systems 20,000 C++ 1/20/1997

110 Chris Info Systems 20,000 Database 12/19/2001

190 Lorenzo Finance 55,000

150 Susan Marketing 35,000 java 11/19/1990

150 Susan Marketing 35,000 C++ 12/19/2001

Emp_ID,Course_Title→Date_completed
Emp_ID→Name ,Dept_Name,Salary
Normalization Steps
Attributes or table with
Multi values(Universal Relation) Remove Multi
values
First Normal Form(1NF)
Remove Partial
Dependencies
Second Normal Form(2NF)
Remove transitive
Dependencies
Third Normal Form(3NF)
Remove multi-valued
Dependencies
Fourth Normal Form(4NF)
First Normal Form(1NF)
A table is in first Normal form(1NF) if
there exists a single data value at
each intersection of row and column
and primary key is decided
EMPLOYEE (ONF)
ENO Ename Title Sal
Sal PNO Pname
Pname Budget Resp

E1 J.Doe Elect.Eng 58,000 P1 Surveys 150000 Manager

P1 Surveys 150000
E2 M.Smith Analyst 48,000 Analyst
P2 Tex_Acc 135000

P3 C++ 250000 Consultant


E3 A.Lee Mech.Eng 20,000
P4 Database 310000 Engineer

E4 J.Miller Programmer 55,000 P2 Tex_Acc 135000 Programmer

E5 B.Casey Analyst 35,000 P3 C++ 250000 Manager

E6 L.Chu Programmer 35,000 P3 C++ 250000 Manager


EMPLOYEE
ENO Ename Title Sal PNO Pname Budget Resp

E1 J.Doe Elect.Eng 58,000 P1 Surveys 150000 Manager

E2 M.Smith Analyst 48,000 P1 Surveys 150000 Analyst

E2 M.Smith Analyst 48,000 P2 Tex_Acc 135000 Analyst

E3 A.Lee Mech.Eng 20,000 P3 C++ 250000 Consultant

E3 A.Lee Mech.Eng 20,000 P4 Database 310000 Engineer

E4 J.Miller Programmer 55,000 P2 Tex_Acc 135000 Programmer

E5 B.Casey Analyst 48,000 P3 C++ 250000 Manager

E6 L.Chu Programmer 55,000 P3 C++ 250000 Manager

Anomalies?
Example
For a library

Patron ID Borrowed books


C45 B33, B44, B55
C12 B56
1-NF Solution
Patron ID Borrowed book
C45 B33
C45 B44
C45 B33
C12 B56
Example
For an airline

Flight Weekdays
UA59 Mo We Fr
UA73 Mo Tu We Th Fr
1NF Solution
Flight Weekday
UA59 Mo
UA59 We
UA59 Fr
UA73 Mo
UA73 We
… …
Second Normal Form(2NF)
A table is said to be in second normal form if
and only if it is in 1NF and all partial
functional dependency are removed
Second Normal Form(2NF)
• To remove partial functional dependency:
• We create a another table containing
determinant attribute and dependent attributes
• Copy of determinant remains in the original
table
EMPLOYEE
ENO Ename Title Sal PNO Pname Budget Resp

ENO → Ename,Title,Sal
PNO→Pname ,Budget
EMPLOYEE ENO Ename Title Sal

PROJECT PNO Pname Budget

ASG ENO PNO Resp


Third Normal Form(3NF)
A table is said to be in 3NF if and only if it
is in 2NF and all transitive
dependencies have be removed
EMPLOYEE ENO Ename Title Sal

PROJECT PNO Pname Budget

ASG ENO PNO Resp

Title → Sal

PAY Title Sal

EMPLOYEE ENO Ename Title


EMPLOYEE
ENO Ename Title
ASG ENO PNO Resp
E1 P1 Manager
E1 J.Doe Elect.Eng
E2 P1 Analyst
E2 M.Smith Analyst
E2 P2 Analyst
E3 A.Lee Engineer
E3 P3 Consultant
E4 J.Miller Programmer
E3 P4 Engineer
E5 A.Lee Manager
E6 P2 Programmer

ROJECT
PNO Pname Budget
P1 Surveys 150000
PAY Title Sal
Elect.Eng 58,000
P2 Tex_Acc 135000 Analyst 48,000

P3 C++ 250000 Mech.Eng 20,000


Programmer 55,000
P4 Database 310000
Lakewood College
Class List
Fall Semester 2015
Course#: IS305 Instrctor_ID: CS001

Course_title: Database Instructor_Name: CJ_Date

Student_ID Name Major Grade

38214 Bright IS A
38215 Tom CS B
38216 Edward IS A
Student_ID Name Major Grade
Course#: Course_title:Instrctor_IDInstrctor_name

IS305 Database CS001 CJ_Date 38214,38215, Bright,Tom, IS,CS,IS A,B,A


38216 Edward
STUDENT
Student_ID Name Major Grade Course# Course_title Instrctor Instrctor_
_ID name
38214 Bright IS A IS305 Database CS001 CJ_Date

38215 Tom CS B IS305 Database CS001 CJ_Date

38216 Edward IS A IS305 Database CS001 CJ_Date

1NF
Normalization
Zero Normal Form (ONF)
First Normal Form (1NF)
First Normal Form (1NF)
There are anomalies (insertion, deletion,
and updating ) in the table

Functional
Dependen
cies
Second Normal Form (2NF)
Third Normal Form (3NF)
ERD Generated From Tables
Fourth Normal Form (4NF)
Fourth normal form eliminates independent many-to-one
relationships between columns.
To be in Fourth Normal Form,
a relation must first be in Boyce-Codd Normal Form.
a given relation may not contain more than one multi-valued attribute.

Example (Not in 4NF)


Scheme → {MovieName, ScreeningCity, Genre)
Primary Key: {MovieName, ScreeningCity, Genre)
1. All columns are a part of the only candidate key, hence BCNF
2. Many Movies can have the same Genre Movie ScreeningCity Genre

3. Many Cities can have the same movie Hard Code Los Angles Comedy

Hard Code New York Comedy


4. Violates 4NF
Bill Durham Santa Cruz Drama

Bill Durham Durham Drama

The Code Warrier New York Horror


Fourth Normal Form (4NF)
Example 2 (Not in 4NF) Manager Child Employee

Scheme → {Manager, Child, Employee} Jim Beth Alice

1. Primary Key → {Manager, Child, Employee} Mary Bob Jane

2. Each manager can have more than one child Mary NULL Adam

3. Each manager can supervise more than one employee


4. 4NF Violated

Example 3 (Not in 4NF)


Scheme → {Employee, Skill, ForeignLanguage}
1. Primary Key → {Employee, Skill, Language }
2. Each employee can speak multiple languages
3. Each employee can have multiple skills Employee Skill Language
4. Thus violates 4NF 1234 Cooking French

1234 Cooking German


1453 Carpentry Spanish

1453 Cooking Spanish


2345 Cooking Spanish
These cause update, addition and
deletion anomalies.
• Insertion anomaly is that entity integrity
would be violated if you tried to add a
new employee who did not speak a
foreign language.
• Update anomalies would occur if you
tried to change Cooking to Chef.
4NF - Decomposition
1. Move the two multi-valued relations to separate tables
2. Identify a primary key for each of the new table

Example 1 (Convert to 3NF)


Old Scheme → {MovieName, ScreeningCity, Genre}
New Scheme → {MovieName, ScreeningCity}
New Scheme → {MovieName, Genre}

Movie Genre Movie ScreeningCity


Hard Code Comedy Hard Code Los Angles

Bill Durham Drama Hard Code New York

The Code Warrier Horror Bill Durham Santa Cruz

Bill Durham Durham

The Code Warrier New York


4NF - Decomposition
Example 2 (Convert to 4NF) Manager Child Manager Employee
Old Scheme → {Manager, Child, Employee} Jim Beth Jim Alice

New Scheme → {Manager, Child} Mary Bob Mary Jane


Mary Adam
New Scheme → {Manager, Employee}

Example 3 (Convert to 4NF)


Old Scheme → {Employee, Skill, ForeignLanguage}
New Scheme → {Employee, Skill}
New Scheme → {Employee, ForeignLanguage}

Employee Skill Employee Language


1234 Cooking 1234 French

1453 Carpentry 1234 German

1453 Cooking 1453 Spanish

2345 Cooking 2345 Spanish


Fifth Normal Form (5NF)
Fifth normal form is satisfied when all tables are broken
into as many tables as possible in order to avoid
redundancy. Once it is in fifth normal form it cannot be
broken into smaller relations without changing the facts or
the meaning.
Description New New Foreign Key in Remarks
Table Attribute other table

Entities Attribute
Regular Singe/Derived 0 0
Composite 0 N
Multivalued 1 0
Time 1 0 PK added as FK in new

Weak 1 0 Yes Surrogate Key

Associative (ID) 1 0 yes Identifier (AE covert to tab


Associative (NID) 1 0 yes Non-identifier (AE covert to

Relationship Cardinality
Binary 1:M 0 0 Yes
Binary M: N 1 0 yes Relationship covert to table
Binary 1:1 0 0 yes

Unary 1:M 0 1 Key added as new attribute


Unary M:M 1 0 yes PK added as FK in new

Ternary 1 0 yes PKs added as FK in new Tab

Super/Sub Key
Super/Sub Key N PK copied into new table w
Before Mid….
1. Basic Concepts
2. Conceptual Database Design (Data Modeling)
• ERD Modeling
• Entity
• Attributes
• Relationships
• Special Issues
• Enhanced ERD (EERD)
3. Logical Database Design
• Basic Ideas(Primary Key, Foreign Key)
• Transformation from ERD to Relations
• Integrity Constraints
Review
Top Down Process of database design
1. Enterprise Modeling
2. Data Modeling(Analysis)
1. Output of analysis is EERD and
2. Business Rules
3. Logical Database design
1. Convert ERD into relations
4. Validate relations well-structured-ness
using Normalization process
Normalization as Database
Design(Bottom Up )
Normalization if used for design can be uses
as follows:
Collect attribute of Organization
Write them in tabular form
Perform Normalization create small
tables
Create EERD
Normalization
Normalization is a step by step
(1NF,2NF,3NF,..) process of converting
a relation(universal relation) into a well
structured relations(Free of
anomalies)
Well Structured Relation
A relation that contains minimum
redundancy and allows user to insert,
modify and delete the rows in table
without errors and inconsistencies
Relation without anomalies
Anomaly
Redundancies in a table may result
errors or inconsistencies called
anomalies
If we face problems OR Data Loss in
performing basic operations on a table:
1. Insert
2. Delete
3. Modification
Anomalies in Table
Anomalies are of three types:
1. Insertion anomaly
2. Deletion anomaly
3. Modification anomaly
Anomaly
Insertion Anomaly–adding new rows
forces user to create duplicate data
Deletion Anomaly–deleting rows may
cause a loss of data that would be
needed for other future rows
Modification Anomaly–changing data
in a row forces changes to other rows
because of duplication
EMPLOYEE
Emp_ID Name Dept_Name Salary Course_Title Date_compl
eted
100 Margaret Marketing 48,000 SPSS 6/19/2001
100 Margaret Marketing 48,000 Surveys 7/19/1998
140 Allen Accounting 52,000 Tex_Acc 12/19/2001
110 Chris Info Systems 20,000 C++ 1/20/1997
110 Chris Info Systems 20,000 Database 12/19/2001
190 Lorenzo Finance 55,000
150 Susan Marketing 35,000 java 11/19/1990
150 Susan Marketing 35,000 C++ 12/19/2001

Question–Is this a relation? Yes: Unique rows and no multivalued column


Question–What’s the primary key? Composite: EmpID, CourseTitle
Anomalies in the Table
Insertion–can’t enter a new employee
without having the employee take a
course
Deletion–if we remove employee 140,
we lose information about the existence
of a Tax Acc course
Modification–giving a salary increase
to employee 100 forces us to update
multiple records
Why do anomalies exist?
Because there are two themes
(entity types) in this one relation.
This results in data duplication and
an unnecessary dependency
between the entities
Why do anomalies exist?

Theme Theme
? ?
Normalization
Normalization is the process of
decomposing relations(attributes)
with anomalies to produce smaller,
well-structured relations(relations
without anomalies)
Normalization Steps
Attributes or table with
Multi values(Universal Relation) Remove Multi
values
First Normal Form(1NF)
Remove Partial
Dependencies
Second Normal Form(2NF)
Remove transitive
Dependencies
Third Normal Form(3NF)
Remove multi-valued
Dependencies
Fourth Normal Form(4NF)
Dependency Structure
Normal forms are based on certain
dependencies
1. 3NF and lower are based on
Functional Dependencies(FDs)
2. 4NF is based on Multi-valued
dependencies
3. 5NF is based on projection-join
dependencies
Functional Dependencies
A constraint between two attributes or
set of attributes
For any relation R attribute B is
functionally dependent on attribute
A if the value of A uniquely
determines the value of B
Each value of A is associated with
exactly one value of B
Functional Dependencies
Notationaly represented as A→B
“A functionally determines B”
Such as:
Emp_ID→Name
Emp_ID→Address
Emp_ID→Birth_date
ISBN→Title,Author_Name
EMPLOYEE_1
Emp_ID Name Dept_Name Salary

100 Margaret Marketing 48,000


140 Allen Accounting 55,000
110 Chris Info Systems 20,000
190 Lorenzo Finance 55,000
150 Allen Marketing 35,000

Emp_ID→Name ,Dept_Name,Salary
Functional Dependencies
Determinant: In A→B the attribute on
left side of aero is known as
determinant
Candidate Key: An attribute, or
combination of attributes, that uniquely
identify a row in a table
Unique identification
No redundancy
EMPLOYEE_1
Emp_ID Name Dept_Name Salary

100 Margaret Marketing 48,000


140 Allen Accounting 55,000
110 Chris Info Systems 20,000
190 Lorenzo Finance 55,000
150 Susan Marketing 35,000

Emp_ID→Name ,Dept_Name,Salary
EMPLOYEE2
Emp_ID Name Dept_Name Salary Course_ Date_com
Title pleted
100 Margaret Marketing 48,000 SPSS 6/19/2001
100 Margaret Marketing 48,000 Surveys 7/19/1998
140 Allen Accounting 52,000 Tex_Acc 12/19/2001
110 Chris Info Systems 20,000 C++ 1/20/1997
110 Chris Info Systems 20,000 Database 12/19/2001
190 Lorenzo Finance 55,000
150 Susan Marketing 35,000 java 11/19/1990
150 Susan Marketing 35,000 C++ 12/19/2001
Functional Dependency
In FDs we have following situations;
1. Fully Functional Dependency: Key
attribute determines non-key attribute or
set of attributes
2. Partially Functional Dependency: Part
of key attribute determines non key
attributes or set of attributes
3. Transitive Dependency: Non-key
attribute determine non-key attribute or
set of attributes
EMPLOYEE_1
Emp_ID Name Dept_Name Salary

100 Margaret Marketing 48,000


140 Allen Accounting 55,000
110 Chris Info Systems 20,000
190 Lorenzo Finance 55,000
150 Susan Marketing 35,000

Emp_ID→Name ,Dept_Name,Salary
EMPLOYEE2
Emp_ID Name Dept_Name Salary Course_ Date_com
Title pleted
100 Margaret Marketing 48,000 SPSS 6/19/2001

100 Margaret Marketing 48,000 Surveys 7/19/1998

140 Allen Accounting 52,000 Tex_Acc 12/19/2001

110 Chris Info Systems 20,000 C++ 1/20/1997

110 Chris Info Systems 20,000 Database 12/19/2001

190 Lorenzo Finance 55,000

150 Susan Marketing 35,000 java 11/19/1990

150 Susan Marketing 35,000 C++ 12/19/2001

Emp_ID,Course_Title→Date_completed
Emp_ID→Name ,Dept_Name,Salary
Normalization Steps
Attributes or table with
Multi values(Universal Relation) Remove Multi
values
First Normal Form(1NF)
Remove Partial
Dependencies
Second Normal Form(2NF)
Remove transitive
Dependencies
Third Normal Form(3NF)
Remove multi-valued
Dependencies
Fourth Normal Form(4NF)
First Normal Form(1NF)
A table is in first Normal form(1NF) if
there exists a single data value at
each intersection of row and column
and primary key is decided
EMPLOYEE (ONF)
ENO Ename Title Sal
Sal PNO Pname
Pname Budget Resp

E1 J.Doe Elect.Eng 58,000 P1 Surveys 150000 Manager

P1 Surveys 150000
E2 M.Smith Analyst 48,000 Analyst
P2 Tex_Acc 135000

P3 C++ 250000 Consultant


E3 A.Lee Mech.Eng 20,000
P4 Database 310000 Engineer

E4 J.Miller Programmer 55,000 P2 Tex_Acc 135000 Programmer

E5 B.Casey Analyst 35,000 P3 C++ 250000 Manager

E6 L.Chu Programmer 35,000 P3 C++ 250000 Manager


EMPLOYEE
ENO Ename Title Sal PNO Pname Budget Resp

E1 J.Doe Elect.Eng 58,000 P1 Surveys 150000 Manager

E2 M.Smith Analyst 48,000 P1 Surveys 150000 Analyst

E2 M.Smith Analyst 48,000 P2 Tex_Acc 135000 Analyst

E3 A.Lee Mech.Eng 20,000 P3 C++ 250000 Consultant

E3 A.Lee Mech.Eng 20,000 P4 Database 310000 Engineer

E4 J.Miller Programmer 55,000 P2 Tex_Acc 135000 Programmer

E5 B.Casey Analyst 48,000 P3 C++ 250000 Manager

E6 L.Chu Programmer 55,000 P3 C++ 250000 Manager

Anomalies?
Second Normal Form(2NF)
A table is said to be in second normal form if
and only if it is in 1NF and all partial
functional dependency are removed
Second Normal Form(2NF)
• To remove partial functional dependency:
• We create a another table containing
determinant attribute and dependent attributes
• Copy of determinant remains in the original
table
EMPLOYEE
ENO Ename Title Sal PNO Pname Budget Resp

ENO → Ename,Title,Sal
PNO→Pname ,Budget
EMPLOYEE ENO Ename Title Sal

PROJECT PNO Pname Budget

ASG ENO PNO Resp


Third Normal Form(3NF)
A table is said to be in 3NF if and only if it
is in 2NF and all transitive
dependencies have be removed
EMPLOYEE ENO Ename Title Sal

PROJECT PNO Pname Budget

ASG ENO PNO Resp

Title → Sal

PAY Title Sal

EMPLOYEE ENO Ename Title


EMPLOYEE
ENO Ename Title
ASG ENO PNO Resp
E1 P1 Manager
E1 J.Doe Elect.Eng
E2 P1 Analyst
E2 M.Smith Analyst
E2 P2 Analyst
E3 A.Lee Engineer
E3 P3 Consultant
E4 J.Miller Programmer
E3 P4 Engineer
E5 A.Lee Manager
E6 P2 Programmer
PROJECT
PNO Pname Budget
P1 Surveys 150000
PAY Title Sal
Elect.Eng 58,000
P2 Tex_Acc 135000 Analyst 48,000

P3 C++ 250000 Mech.Eng 20,000


Programmer 55,000
P4 Database 310000
Lakewood College
Class List
Fall Semester 2015
Course#: IS305 Instrctor_ID: CS001

Course_title: Database Instructor_Name: CJ_Date

Student_ID Name Major Grade

38214 Bright IS A
38215 Tom CS B
38216 Edward IS A
Student_I Name Major Grade
Course#: Course_title:Instrctor_IDInstrctor_name
D
38214 Bright IS A

38215 Tom CS B
IS305 Database CS001 CJ_Date
38216 Edward IS A
STUDENT
Student_ID Name Major Grade Course# Course_title Instrctor Instrctor_
_ID name
38214 Bright IS A IS305 Database CS001 CJ_Date

38215 Tom CS B IS305 Database CS001 CJ_Date

38216 Edward IS A IS305 Database CS001 CJ_Date

1NF
Normalization
Zero Normal Form (ONF)
First Normal Form (1NF)
First Normal Form (1NF)
There are anomalies (insertion, deletion,
and updating ) in the table

Functional
Dependen
cies
Second Normal Form (2NF)
Third Normal Form (3NF)
ERD Generated From Tables
RELATIONAL ALGEBRA
Querying The Database
EMPLOYEE ASG
ENO PNO Resp
PAY
ENO Ename Title
E1 J.Doe Elect.Eng
E1 P1 Manager Title Sal
E2 M.Smith Analyst E2 P1 Analyst Elect.Eng 58,000

E2 P2 Analyst Analyst 48,000


E3 A.Lee Engineer
E3 P3 Consultant Mech.Eng 20,000
E4 J.Miller Programmer
Programmer 55,000
E3 P4 Engineer
E5 A.Lee Manager
E6 P2 Programm
er
PROJECT
PNO Pname Budget •What is the name of electrical
P1 Surveys 150000 engineer?
P2 Tex_Acc 135000
P3 C++ 250000 •Who are working on Surveys
P4 Database 310000
project?
Querying The Database
Query languages are developed for
Relational model for data
manipulation on database
These languages fall into two
categories:
1. Relational algebra based languages
2. Relational calculus based languages
Relational algebra is more common
Querying The Database
Relational Algebra(Procedural)
In Relational algebra based languages
user is expected to specify how the
result of query is obtained
It is done using some high level
operators
In Relational calculus user only specify
relationship that should hold in the
result
Relational Algebra
Derived from set theory
Operations on database are defined using
some Relational algebra operators
Each operator takes one or two
relations(tables) as operands and
produce a resultant(relation)
Result relation may be operand to
another operator
Relational Algebra
Derived from set theory
Operations on database are defined using
some Relational algebra operators
Each operator takes one or two
relations(tables) as operands and
produce a resultant(relation)
Result relation may be operand to
another operator
Relational Operators
There are five fundamental
relational operator. These are:
1. Selection σ Unary
2. Projection Π Unary
3. Union U Binary
4. Set difference - Binary
5. Cartesian product χ Binary
Relational Operators
Additional operators are defined in
terms of these fundamental
operators:
1. Intersection
2. θ-join
3. Natural join
4. Semi-join
5. Quotient
Selection (σ)
Selection produces a horizontal
subset(relation) of given relation
This relation consists of all tuples
satisfy a Formula(condition)
The selection from a relation R on the
basis of some formula F is:
σF(R)
EMPLOYEE Selection
ENO Ename Title Who are analysts?
E1 J.Doe Elect.Eng
E2 M.Smith Analyst σTitle=“Analyst”(EMPLOYEE)
E3 A.Lee Engineer
F → Title=“Analyst”
E4 J.Miller Analyst R→ EMPLOYEE
E5 A.Lee Manager

ENO Ename Title


E2 M.Smith Analyst
E4 J.Miller Analyst
Projection
Projection produces a
vertical(columns) subset of given
relation
The resultant relation contains only
those attributes over which projection
is performed
Degree of resultant relation is equal to
or less than original relation
Projection of relation R over attributes
A and B is denoted as: Π A,B(R)
Projection
PROJECT
PNO Pname Budget
P1 Surveys 150000 ΠPNO,Budget(PROJECT)
P2 Tex_Acc 135000
P3 C++ 250000
P4 Database 310000

PNO Budget
P1 150000
P2 135000
P3 250000
P4 310000
EMPLOYEE Queries
ENO Ename Title
E1 J.Doe Elect.Eng Tell the names of analysts
E2 M.Smith Analyst ΠEname(σTitle=“Analyst”(EMPLOYEE))
E3 A.Lee Engineer

E4 J.Miller Analyst
E5 A.Lee Manager

σTitle=“Analyst”
ENO Ename Title ΠEname Ename
E2 M.Smith Analyst M.Smith

E4 J.Miller Analyst J.Miller


Querying The Database
EMPLOYEE ASG
ENO PNO Resp
PAY
ENO Ename Title
E1 J.Doe Elect.Eng
E1 P1 Manager Title Sal
E2 M.Smith Analyst E2 P1 Analyst Elect.Eng 58,000

E2 P2 Analyst Analyst 48,000


E3 A.Lee Engineer
E3 P3 Consultant Mech.Eng 20,000
E4 J.Miller Programmer
Programmer 55,000
E3 P4 Engineer
E5 A.Lee Manager
E6 P2 Programm
er
PROJECT
PNO Pname Budget •What is the name of electrical
P1 Surveys 150000 engineer?
P2 Tex_Acc 135000
P3 C++ 250000 •Show names of Project who has
P4 Database 310000
budget greater than 200000
In the Last Lecture
Querying the Database
Relational Algebra Based Queries
Relational Calculus based queries
Relational Algebra Operators
Basic ( Selection, Projection,)
Relational Operators
There are five fundamental
relational operator. These are:
1. Selection σ Unary
2. Projection Π Unary
3. Union U Binary
4. Set difference - Binary
5. Cartesian product χ Binary
Relational Operators
Additional operators are defined in
terms of these fundamental
operators:
1. Intersection
2. θ-join
3. Natural join
4. Semi-join
5. Quotient
Unary Operations
Selection (σ) : Selection produces a
horizontal subset(relation) of given
relation
σTitle=“Analyst”(EMPLOYEE)
Projection (Π) produces a
vertical(columns) subset of given relation
Degree of resultant relation is equal to or
less than original relation
ΠPNO,Budget(PROJECT)
EMPLOYEE Queries
ENO Ename Title
E1 J.Doe Elect.Eng Tell the names of analysts
E2 M.Smith Analyst ΠEname(σTitle=“Analyst”(EMPLOYEE))
E3 A.Lee Engineer

E4 J.Miller Analyst
E5 A.Lee Manager

σTitle=“Analyst”
ENO Ename Title ΠEname Ename
E2 M.Smith Analyst M.Smith

E4 J.Miller Analyst J.Miller


Binary Operators
Other relational algebra Operators are
binary(need two operand relations)
The operands of some of binary
operator should be union
compatible means:
1. They have same number of
columns(same degree)
2. Corresponding fields have same
domains(Left to Right)
Union
Union of two relations R and S is
denoted by R U S
Is the set of all tuples that are in R, or
in S or in both
We can note R and S should be union
compatible
Duplicate rows are written once
Requires Union Compatibility
Employee Student

Employee U Student
Set Difference
The difference between two tables i.e.
R and S is denoted as R-S is a table of
all tuples that are in R but not in S
R and S should be union compatible
This operation is asymmetric means
R-S S-R
Requires Union Compatibility
Employee Student

Student - Employee
Cartesian Product
The Cartesian product of two relations
R of degree k and relation S of
degree l is a relation of degree (k+l)
Where each resultant row is a
concatenation of one row of R with
each row of S
Attributes may have same name, in this
case attributes are prefixed with
relation name
ENO Ename Title Title Sal
E1 J.Doe Elect.Eng
Elect.Eng 58,000
E2 M.Smith Analyst
Analyst 48,000
E3 A.Lee Engineer EMPLOYEE X PAY
Mech.Eng 20,000

Programmer Programmer 55,000


E4 J.Miller
E5 A.Lee Manager

ENO Ename Title.E Title.PAY Sal


E1 J.Doe Elect.Eng Elect.Eng 58,000
E1 J.Doe Elect.Eng Analyst 48,000
E1 J.Doe Elect.Eng Mech.Eng 20,000
E1 J.Doe Elect.Eng Programmer 55,000
E2 M.Smith Analyst Elect.Eng 58,000
E2 M.Smith Analyst Analyst 48,000
E2 M.Smith Analyst Mech.Eng 20,000
E2 M.Smith Analyst Programmer 55,000
….. ……. ……. ….. ……
Intersection
Intersection of two relations R and S
(R  S) consist of all rows that are in
both R and S
In terms of basic operators intersection
can be defined as:
R  S= R-(R-S)
θ-join
Also known as simply join
θ join between two relation is denoted
as: R F S
join predicate(F) is like selection
formula expect terms are of form
R.A θ S.B
θ-join
Natural Join
Join of two relations over a specified
attribute
Mostly attribute of same domain
The attribute over which Natural join is
performed appear once in resultant
relation
Natural join is denoted as:
R A S
Can only be performed on tables which
has primary key and foreign key
relationship
ENO Ename Title Title Sal
E1 J.Doe Elect.Eng
E2 M.Smith Analyst
EMP  Elect.Eng
EMP.Title=PAY.Title
58,000
Analyst 48,000
E3 A.Lee Mech.EngPAY Mech.Eng 20,000
Programmer 55,000
E4 J.Miller Programmer

E5 A.Lee Analyst
E6 R.Davis Mech.Eng ENO Ename Title Sal
E7 J.Jones Elect.Eng E1 J.Doe Elect.Eng 58,000
E2 M.Smith Analyst 48,000
E3 A.Lee Mech.Eng 20,000
Join Condition:
Programmer
EMP.Title=PAY.Title
E4 J.Miller 55000
E5 A.Lee Analyst 48000
E6 R.Davis Mech.Eng 20,000
E7 J.Jones Elect.Eng 58,000
Semi-join
The semi-join of relation R with relation
S is subset of the tuples of R that
participate in the join of R with S
Semi-join is denoted as:
R F S
ENO Ename Title Title Sal
E1
E2
J.Doe
M.Smith
Elect.Eng
Analyst
EMP  Elect.Eng
EMP.Title=PAY.Title
58,000
Analyst 48,000
E3 A.Lee Mech.EngPAY Mech.Eng 20,000
Programmer 55,000
E4 J.Miller Programmer

E5 B.Casey Analyst
E6 R.Davis Mech.Eng ENO Ename Title
E7 J.Jones Elect.Eng E1 J.Doe Elect.Eng

E8 L. E2 M.Smith Analyst
Lavesson
E3 A.Lee Mech.Eng

E4 J.Miller Programmer

E5 B.Casey Analyst
E6 R.Davis Mech.Eng
E7 J.Jones Elect.Eng
Relation Algebra Queries
Since all operators take relations as
input and produce relations as output
We parenthesize relational algebra
operators according to the requirement
of our queries
The parenthesis indicate the order of
query execution
EMPLOYEE ASG
ENO PNO Resp
PAY
ENO Ename Title
E1 J.Doe Elect.Eng E1 P1 Manager Title Sal
E2 M.Smith Analyst E2 P1 Analyst Elect.Eng 58,000

E2 P2 Analyst Analyst 48,000


E3 A.Lee Engineer
Mech.Eng 20,000
E3 P3 Consultant
E4 J.Miller Programmer
Programmer 55,000
E3 P4 Engineer
E5 A.Lee Manager
E6 P2 Programm
PROJECT er

PNO Pname Budget


P1 Surveys 150000
Show name of employees are
P2 Tex_Acc 135000 working on Surveys project?
P3 C++ 250000
P4 Database 310000
Π Ename
(((σPname=“Surveys”PROJECT  ENO EMPLOYE
) PNO ASG)

PNO Pname Budget ENO PNO Resp Pname Budget

P1 Surveys 150000 E1 P1 Manager Surveys 150000

E2 P1 Analyst Surveys 150000

ENO Ename Title PNO Resp Pname Budget


E1 J.Doe Elect.Eng P1 Manager Surveys 150000
E2 M.Smith Analyst P1 Analyst Surveys 150000

Ename
J.Doe
M.Smith
PAY
Title Sal
Elect.Eng 58,000
Analyst 48,000
UPDATE
Mech.Eng 20,000
Replace the salary of programmer by
Programmer 55,000
60000?

PAY-(σTitle=“Programmer”PAY))U(<Programmer,60000>)

Title Sal
Title Sal
Title Sal Elect.Eng 58,000
Elect.Eng 58,000
Programmer 55,000 Analyst 48,000
Analyst 48,000
Mech.Eng 20,000
Mech.Eng 20,000
Programmer 60000
EMPLOYEE ASG
ENO PNO Resp
PAY
ENO Ename Title
E1 J.Doe Elect.Eng E1 P1 Manager Title Sal
E2 M.Smith Analyst E2 P1 Analyst Elect.Eng 58,000

E2 P2 Analyst Analyst 48,000


E3 A.Lee Engineer
Mech.Eng 20,000
E3 P3 Consultant
E4 J.Miller Programmer
Programmer 55,000
E3 P4 Engineer
E5 A.Lee Manager
E6 P2 Programm
ROJECT er

PNO Pname Budget


P1 Surveys 150000
What is the salary of A. Lee?
P2 Tex_Acc 135000
P3 C++ 250000
What is the name of projects
P4 Database 310000 on which M.Smith is working
FINAL PROJECT
(DATABASE & OOP)
Final Project
• Weightage=15 Marks(Theory) & 50% (Lab)
• Front End → C#
• Database → SQL Server (2016) OR
Oracle (18C) Above
• Project Type → Transaction Processing
and Inventory Management System OR
any other idea
• Challenging Feature in Project→ Use of
some hardware for transactions ( such as
Barcode Reader Or Thumb Scanner OR
QR Code ) * This if implemented will
guarantee maximum marks
Final Project
1. Proposal (5%)

2. Analysis and Design (40%)

3. Implementation (40%)

4. Presentation (15%)
Final Project
Proposal (5%)
Deadline → 06 December, 2019
Analysis and Design Phase (40%)
Deadline → 27 December, 2019
Implementation (40%)
Deadline →Announced Later
Software Manual
Code
Complete Running Program developed
on SQL Sever OR Oracle (Latest
Version)
Final Project
Proposal
• Title
• Introduction
• Main Features
• Tools and Technologies Used
Analysis and Design Phase
Part One
• Business Requirements & Rules
• List of Final Entities (At least 7 Regular
entities)
• List of Final Relationships
• EERD Diagram
• Tables Converted From ER Diagram
Project
Analysis and Design Phase
Part Two
Tables After 3NF
Forms & Form Layouts (At least 5 )
Reports & Report Layouts (At least 5 )
Part Three
Enlist Final Classes of the Project
Their methods and Data types
Class Diagram
Examples of TP and Inventory
Management Systems
Departmental Store Management
System
Library Management System
Medical Store Management System
Hospital Management System
School Management System
Transport Management System
SQL
The Concept of Relational Database is
articulated by E.F. Codd of IBM research
SQL/DS→ DOS/VSE → VM→DB2
There are lot of DBMS uses relational
model
According to IDC 85% of the market is
captured by
(Oracle(41%)+IBM(31%)+Microsoft(13%)
SQL
Pronounced “S-Q-L” and “sequel”
Become a standard to create and
query relational database(RDBMS)
Based on Relational Algebra and
Relational calculus
Famous ANSI SQL standards are
(SQL-92), (SQL-99) and (SQL-
2003)
SQL
First Commercial DBMS that support
SQL was Oracle 1979
A variety of RDBMS Supports SQL i.e.
Microsoft SQL Sever, Sybase,
Informix,MySql etc.
All relational algebra operators are
implemented by these DBMS
The SQL Environment
The power of SQL cannot guessed by
the application user(Naïve user)
Every information is retrieved from the
database using some SQL query
through the RDBMS
End User Application DBA
Programmer
Naive Casual

Programs in C++, Commands that


Prewritten Online Query Pascal Create and modify
Program Language Ada,COBOL etc Database
structure
SQL Query SQL Query
SQL Query
SQL Query

Database Management System

Database
Benefits of using SQL
Reduced training Cost
Productivity
Application portability
Application longevity
Reduced dependence on a single
vendor
Cross-system communication
DBMS SQL Query

Syntax Checking
Correct SQL
SQL Query Result
Quer Translation
y Relational Algebra
Query
Code Generation

Code for Query


SQL
Mostly Structure Query Language(SQL) is
used :
1. Implement database
2. Manipulate database
3. Control database
SQL Commands
SQL commands can be classified into
three categories
1. Data Definition Language(DDL)
2. Data Manipulation
Language(DML)
3. Data Control Language(DCL)
Data Definition Language(DDL)
Commands that define the database are
included in this class. They can be:
Creating tables
Altering table
Dropping Tables
Establishing Constraints
Data Manipulation Language(DML)
DML include those command that are
used to maintain and query a
database
SELECT (Query the database)
UPDATE
INSERT
DELETE
Data Control Language(DCL)
DCL include commands that are use to
control the database:
Grant Privileges
Revoke
Committing and saving of database
Data Definition Language(DDL)
Commands that define the database are
included in this class. They can be:
Creating tables (CREATE)
Altering table (ALTER)
Dropping Tables (DROP)
Establishing Constraints
In the Last Lecture
RA Basic Operators
1. Selection σ Unary
2. Projection Π Unary
3. Union U Binary
4. Set difference - Binary
5. Cartesian product χ Binary
RA Additional Operators
1. Intersection
2. θ-join
3. Natural join
4. Semi-join
• RA Queries
Relation Algebra Queries
Since all operators take relations as
input and produce relations as output
We parenthesize relational algebra
operators according to the requirement
of our queries
The parenthesis indicate the order of
query execution
Π Ename  ENO EMPLOYE
) PNO ASG)
(((σPname=“Surveys”PROJECT

PNO Pname Budget ENO PNO Resp Pname Budget

P1 Surveys 150000 E1 P1 Manager Surveys 150000

E2 P1 Analyst Surveys 150000

ENO Ename Title PNO Resp Pname Budget


E1 J.Doe Elect.Eng P1 Manager Surveys 150000
E2 M.Smith Analyst P1 Analyst Surveys 150000

Ename
J.Doe
M.Smith
DBMS SQL Query

Syntax Checking
Correct SQL
SQL Query Result
Quer Translation
y Relational Algebra
Query
Code Generation

Code for Query


SQL
Mostly Structure Query Language(SQL) is
used :
1. Implement database
2. Manipulate database
3. Control database
SQL Commands
SQL commands can be classified into
three categories
1. Data Definition Language(DDL)
2. Data Manipulation
Language(DML)
3. Data Control Language(DCL)
Data Definition Language(DDL)
Commands that define the database are
included in this class. They can be:
Creating tables
Altering table
Dropping Tables
Establishing Constraints
Data Manipulation Language(DML)
DML include those command that are
used to maintain and query a
database
SELECT (Query the database)
UPDATE
INSERT
DELETE
Data Control Language(DCL)
DCL include commands that are use to
control the database:
Grant Privileges
Revoke(Revoke command withdraw
user privileges on database)
Committing and saving of database(
Data Definition Language(DDL)
Commands that define the database are
included in this class. They can be:
Creating tables (CREATE)
Altering table (ALTER)
Dropping Tables (DROP)
Establishing Constraints
Creating Table

CREATE TABLE table_name


( column definition
table constraints);
Creating Table
Column Definition
column_name
datatype(Size)
column_constraint_clause
Default Value
Creating Table
Constraint Definition
CONSTRAINT constraint_name
Constraint_type(attribute)
DML QUERIES
Data Manipulation Language(DML)
DML include those command that are
used to maintain and query a
database
SELECT (Query the database)
UPDATE
INSERT
DELETE
Structured Query Language
SELECT (Columns, Aggregate Functions)
FROM (Table Names)
AS (Column Alias)
DISTINCT (Unique Values of Column)
Arithmetic Operations on Columns
WHERE Clause (Restrict Rows)
Formula of Where Clause
(Column Operator Column/Value (Number, Text)
Comparison Operators (<, >, <=, >=, <>, =)
Structured Query Language
Other Operators
BETWEEN… AND, NOT BETWEEN… AND
IN, NOT IN,
LIKE (%,_), NOT LIKE (%,_)
IS NULL
Logical Operators
AND,
OR,
NOT
Precedence of Operators
Aggregate Functions (MIN, MAX, AVG, SUM, COUNT)
GROUP BY Clause
GROUP BY Clause
GROUP BY clause is used to divide the
rows in a table into groups
GROUP BY Column_Name
There can be single column groups and
multiple column groups
Show total number of employee for
each title
Group By Clause (on multiple
Columns)
Show all title who have same city as
well
Show all title who have same city as
well
Show only those categories where products are greater
than 10?
Illegal Query
We cannot use the where clause to
restrict groups
Use HAVING clause to restrict groups
HAVING Clause
Use the HAVING Clause to restrict
the groups
The flow is:
1. Rows are grouped
2. The aggregate function is applied
3. Groups matching the HAVING clause
are displayed
SELECT Query
SELECT column, group_function
FROM table
WHERE condition
GROUP BY group_by_expression
Having group_condition
ORDER BY column
JOIN QUERIES
Retrieving Data From Multiple
tables
Sometimes a user information cannot
be retrieved from the one table
We have to use multiple tables to
answer the query
Commonly used operation is join to
retrieved data from multiple tables
JOIN Operation
Rows of one table can be joined with
the row of other table on the basis of
common values(Join Condition)
Write the join condition in WHERE
clause
Prefix the column name with the table
name if tables has common columns
JOIN Operation
The syntax of join can be:
SELECT table1.column,table2.column
FROM table1,table2
Where table1.column1=table2.column2
If we skip join condition in the WHERE clause
then Cartesian product is performed
Cartesian Product
A Cartesian product is performed when:
A join condition is omitted
A join condition is invalid
All rows in the first table are joined to
the all rows in the second table
Types of Join
There are following major types of Join
operation:
1. Equijoin/ Inner Join
2. Natural Join
3. Outer Join
• Left Outer Join
• Right Outer Join
• Full Outer Join
4. Self Join
5. Union Join
Equi-join
Join in which the joining condition is
based on equality between the values
in the common column appear
redundantly in the result table
Join Condition
Using AND Operator
We can use AND operator with the Join
condition
In this way we can further restrict
Number of rows involved in join
operation
What is name of the employee who get
the Order Number 10358?
What are Order Ids acquired by Nancy?
Employee Order

Product Order Line


Table Aliases
Equi-Join Variations
To avoid to mix the Selection
Formula and Join Condition DBMS also
allow to write Join Condition in FROM
Clause
Two Possible Clauses to write the Join
Condition
WHERE
FROM
Equi-Join Variations
Equi-Join Variations
SELECT Ename, Employee.Title , Salary.sal
FROM Employee INNER JOIN Salary ON
Employee.Title=Salary.Title
WHERE Ename='J.Miller';
Equi-join (three methods)
SELECT CUSTOMER_T.CUSTOMER_ID,
ORDER_T.CUSTOMER_ID, CUSTOMER_NAME, ORDER_ID
FROM CUSTOMER_T, ORDER_T Recommended
WHERE CUSTOMER_T.CUSTOMER_ID = preferred
ORDER_T.CUSTOMER_ID;
SELECT CUSTOMER_T.CUSTOMER_ID, ORDER_T.CUSTOMER_ID,
CUSTOMER_NAME, ORDER_ID FROM CUSTOMER_T, ORDER_T
FROM CUSTOMER_T INNER JOIN ORDER_T ON
CUSTOMER_T.CUSTOMER_ID = ORDER_T.CUSTOMER_ID;
SELECT CUSTOMER_T.CUSTOMER_ID,
ORDER_T.CUSTOMER_ID, CUSTOMER_NAME, ORDER_ID
FROM CUSTOMER_T, ORDER_T
FROM CUSTOMER_T INNER JOIN ORDER_T USING
CUSTOMER_ID;
Joining Multiple Tables
We can Join Multiple (more than 2
tables) tables according to the
requirement of the query
AND operator is used to join multiple
tables
Consider the question:
What are the names of Products whose
order is get by Nancy?
Employee Order

Product Order Line


Joining Multiple Tables
SELECT CUSTOMER_t.CustomerID,
ORDER_t.CustomerID,
CUSTOMER_t.CustomerName, ORDER_t.OrderID
FROM ((CUSTOMER_t INNER JOIN ORDER_t
ON CUSTOMER_t.CustomerID=
ORDER_t.CustomerID)
INNER JOIN OrderLine_T
ON Order_t.OrderID=OrderLine_t.OrderID)
Equi Join Natural Join
SELECT
SELECT
CUSTOMER_t.CustomerID,
CUSTOMER_t.CustomerID,
ORDER_t.CustomerID,
CUSTOMER_t.CustomerName,
CUSTOMER_t.CustomerName,
ORDER_t.OrderID
ORDER_t.OrderID
FROM CUSTOMER_t INNER
FROM CUSTOMER_t INNER
JOIN ORDER_t ON
JOIN ORDER_t ON
CUSTOMER_t.[CustomerID] =
CUSTOMER_t.[CustomerID] =
ORDER_t.[CustomerID]
ORDER_t.[CustomerID]
ORDER BY ORDER_t.OrderID;
ORDER BY
ORDER_t.OrderID;
Outer Join Example
Outer Join Example
List the customer name, ID number, and order
number for all customers. Include customer
information even for customers that do have an order.

LEFT OUTER JOIN clause causes customer data to


appear even if there is no corresponding order data
Unlike
INNER
join, this
will
include
custome
r rows
with no
matchin
g order
rows
LEFT outer join:

Customer_T Order_T
RIGHT outer join:

Order_T RIGHT OUTER JOIN Customer_T

Logically,
300 A LEFT join B=B RIGHT join A:
Right Outer Join
Right Outer Join
Types of Joins
Full Join
SELECT Customers.CustomerName,
Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders ON
Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
SUB QUERIES
•What are the Products whose unit price is
greater than the price of Tofu?
•What is Price of Tofu?
Subqueries
We can write Subqueries in SQL
Statements
The Subquery(inner query) executes
once before the main query
The result of Subquery is used by the
main query(outer query)
Subquery can be placed in WHERE
clause
SubQuery
SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);
Subquery
In the Last Lecture
Classification of SQL Queries
DML Queries
Join Operation
Cartesian Product/ Theta Join
1. Equijoin/ Inner Join
2. Natural Join
3. Outer Join
• Left Outer Join
• Right Outer Join
• Full Outer Join
• Join Variations
Table Aliases
Equi-join (three methods)
SELECT CUSTOMER_T.CUSTOMER_ID,
ORDER_T.CUSTOMER_ID, CUSTOMER_NAME, ORDER_ID
FROM CUSTOMER_T, ORDER_T Recommended
WHERE CUSTOMER_T.CUSTOMER_ID = preferred
ORDER_T.CUSTOMER_ID;
SELECT CUSTOMER_T.CUSTOMER_ID, ORDER_T.CUSTOMER_ID,
CUSTOMER_NAME, ORDER_ID FROM CUSTOMER_T, ORDER_T
FROM CUSTOMER_T INNER JOIN ORDER_T ON
CUSTOMER_T.CUSTOMER_ID = ORDER_T.CUSTOMER_ID;
SELECT CUSTOMER_T.CUSTOMER_ID,
ORDER_T.CUSTOMER_ID, CUSTOMER_NAME, ORDER_ID
FROM CUSTOMER_T, ORDER_T
FROM CUSTOMER_T INNER JOIN ORDER_T USING
CUSTOMER_ID;
Joining Multiple Tables
SELECT CUSTOMER_t.CustomerID,
ORDER_t.CustomerID,
CUSTOMER_t.CustomerName, ORDER_t.OrderID
FROM ((CUSTOMER_t INNER JOIN ORDER_t
ON CUSTOMER_t.CustomerID=
ORDER_t.CustomerID)
INNER JOIN OrderLine_T
ON Order_t.OrderID=OrderLine_t.OrderID)
Outer Join Example
List the customer name, ID number, and order
number for all customers. Include customer
information even for customers that do have an order.

LEFT OUTER JOIN clause causes customer data to


appear even if there is no corresponding order data
Right Outer Join
Types of Joins
Full Join
SELECT Customers.CustomerName,
Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders ON
Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
SUB QUERIES
•What are the Products whose unit price is
greater than the price of Tofu?
•What is Price of Tofu?
Subqueries
We can write Subqueries in SQL
Statements
The Subquery(inner query) executes
once before the main query
The result of Subquery is used by the
main query(outer query)
Subquery can be placed in WHERE
clause
SubQuery
SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);
Subquery
Using Subquery
Enclose subqueries in parentheses
Do not add an ORDER BY clause in
subquery
Use single row operator with single row
subquery
Use Multiple row operators with
multi-row subquery
Types of Subqueries
Single Row subqueries

Multiple Row Subqueries

Multiple Column Subqueries


Types of Subqueries

Single-row Subqueries

Main query
Returns 15.5
Subquery
Types of Subqueries

Multiple-row Subqueries

Main query 15.5


Returns
Subquery 10
15
Types of Subqueries

Multiple-Column Subqueries

Main query A 15.5


Returns
Subquery B 10
Single-Row Subquery
Return only one row
Use single row comparison operator
Operator Meaning
= Equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
<> Not equal to
Display EmployeeID,FirsrtName of all employees
whose Title is same as that of Robert
Show products whose unitisonOrder are greater
than
ShowChang?
products whose UnitPrice is less than the
price
Show of Konbu?
product id whose SupplierID is same as
AND / OR Clause Subqueries
Subqueries can also written in OR and
AND clauses
Show product names and unitsOnOrder whose
unitsonOrder are greater than Chang and less
than
ShowAniseed
productSyrup?
names and unitPrice whose
UnitPrice is greater equal than the price of
Subqueries With Aggregate Functions
We can use aggregate function in sub
query
Consider the question:
Display the name and ids of all products
whose unit price is equal to the
minimum price?
Show names of product who has maximum Unit
Price in each category ?
Show product names whose maximum units on
order in each category?
Multi-Row Subqueries
Return more than one row
Use multi-row comparison operator
Operator Meaning
IN Equal to a member in list
NOT IN Not Equal to a member in list
ANY Compare value to each value
returned by sub-query
ALL Compare value to every value
returned by sub-query
EXISTS, Correlated Subquery Compare
NOT EXISTS with outer query
Show name of Customers who do not order for
desks
ANY & ALL Operators
These Operators are used in combination
with relational operators
> ANY: Greater than Smallest value in list.
> ANY(1,2,3) means greater than 1 value
> ALL : Means Greater than Largest Value
in the List
>ALL (1, 2, 3) means greater than 3
Multi-Row Subqueries
Qualifications such as < ANY or >= ALL
instead of IN are also useful
the qualification >= ALL can be used to
match with the maximum value in a set.
But be careful: Some combinations of
qualifications may not make sense, such as
= ALL(which makes sense only when the all
the elements of the set have the same
value).
Subquery & Join (Using Subquery
on different Table)
What are the name and address of the
customer who placed order #1008?
SELECT CUSTOMER_NAME, CUSTOMER_ADDRESS
FROM CUSTOMER_T
WHERE CUSTOMER_T.CUSTOMER_ID =
(SELECT CUSTOMER_ID FROM ORDER_T
WHERE ORDER_ID = 1008);

*If* a subquery is in the WHERE-


clause, data from subquery cannot
be included in the final results
Join tables vs. subquery
Join tables vs. subquery
Join tables vs. subquery
Subquery – “IN”
Show all customers who have placed an order
The IN operator will test to see if
the CUSTOMER_ID value of a
row is included in the list returned
from the subquery
SELECT CUSTOMER_NAME FROM CUSTOMER_T
WHERE CUSTOMER_ID IN
(SELECT DISTINCT CUSTOMER_ID FROM ORDER_T);
CORRELATED SUBQUERIES
Using Subqueries
Subquery–placing an inner query (SELECT
statement) inside an outer query
Options:
1. In a condition of the WHERE clause
2. As a “table” of the FROM clause
3. Within the HAVING clause
Types of Subqueries
Subqueries can be:
Noncorrelated–executed once for the entire
outer query
Correlated–executed once for each row
returned by the outer query
Correlated subquery
In SQL, a subquery in which processing
the inner query depends on data from
the outer query.
EXISTS or NOT EXISTS Clause
Two other conditions associated with using
subqueries are EXISTS and NOT EXISTS.
These keywords are included in an SQL query
at the same location where IN
EXISTS will take a value of true if the
subquery returns an intermediate result table
that contains one or more rows and false if
no rows are returned.
NOT EXISTS will take a value of true if no
rows are returned and false if one or more
rows are returned.
Places for a subquery
Clause Use Remark
subQ
SELECT Yes? SubQ generate column

FROM Yes SubQ generate a “dynaset”

WHERE Yes SubQ participate in condition

GROUP BY No? Grp by seems work w field


only?
HAVING Yes Same/similar with in WHERE

ORDER BY Yes? SubQ can generate column…


Using Derived Tables
Subqueries are not limited to inclusion
in the WHERE clause they may also be
used in the FROM clause to create a
temporary derived table (or set)
Derived Tables can be used in the
query
SubQ in FROM - dynaset
If I want to see the average sales of the top-
sale restaurants from each city, the “top-sale
restaurants from each city” must be obtained
in a subquery:
SELECT AVG(AnnualSales) FROM
(SELECT MAX(AnnualSales)
FROM Restaurant GROUP BY City);
OTHER DML
QUERIES
Data Manipulation Language(DML)
DML include those command that are
used to maintain and query a
database
Insert
Update
Delete
INSERT
Insert a row containing values for each
column
List values in default order
Optionally list columns in INSERT clause
Enclose characters and date within
single quotation marks
Insert Statment
INSERT INTO Customers
(CustomerName, ContactName,
Address, City, PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen',
'Skagen 21', 'Stavanger', '4006',
'Norway');
Specified Columns
INSERT INTO Customers (CustomerName, City, Country)

VALUES ('Cardinal', 'Stavanger', 'Norway');


Inserting Null Values
Explicit Way
INSERT INTO dept
VALUES (51,'Marketing',NULL);
Implicit Way
INSERT INTO dept(deptno,dname)
VALUES (52,‘Accounts');
Subquery with INSERT
We can use subquery with INSERT
statement
Do not use VALUES clause
The UPDATE Statement
Modify the existing rows with the
UPDATE statement
Update more than one row at a time, if
required
UPDATE table
SET column=value
WHERE condition
EMPLOYEE Update Queries
ENO Ename Title City
E1 Ali Engineer Lahore
Update the name of
E2 Ahmad Analyst Lahore
Tex_Acc to “Tax and
E3 Waqas Engineer Faisalabad
Accounting”
E4 Abdullah Programmer Multan
E5 Mansoor Programmer Lahore
Change P1 to P20 and
E6 Shehraz Analyst Lahore
Budget=30000
E7 Khubab Engineer Faisalabad Give Mansoor same title as
E8 Faraz Engineer Faisalabad
the title of Ahmad
OJECT
PNO Pname Budget

P1 Surveys 150000

P2 Tex_Acc 135000

P3 C++ 250000

P4 Database 310000
Updating Values (Using Sub-Query)
DELETE Statement
DELETE Clause is used to delete rows
from a table
DELETE FROM table_name
WHERE condition;
DELETE Statement
DELETE Statement
EMPLOYEE Update Queries
ENO Ename Title City
E1 Ali Engineer Lahore
Delete record of employee
E2 Ahmad Analyst Lahore
E5
E3 Waqas Engineer Faisalabad
E4 Abdullah Programmer Multan Delete Record of Surveys
E5 Mansoor Programmer Lahore
Project
E6 Shehraz Analyst Lahore Delete Record of all
E7 Khubab Engineer Faisalabad Programmers
E8 Faraz Engineer Faisalabad

PROJECT
PNO Pname Budget

P1 Surveys 150000

P2 Tex_Acc 135000

P3 C++ 250000

P4 Database 310000
In Last WEEK
Subquery Types (Values Returned By Sub Query)
Single Row (>, <, >=, <=, =, <>)
Multiple Row ( IN, NOT IN, ANY, ALL)
Multiple Column
Subquery with aggregate Functions
Subquery vs. Join (Retrieving data from multiple
tables)
Subquery Types (Order of Execution Sub Query)
Correlated Vs. Non Correlated
Exists, Not Exists Operators
Other DML Queries
Specified Columns
INSERT INTO Customers (CustomerName, City, Country)

VALUES ('Cardinal', 'Stavanger', 'Norway');


Inserting Null Values
Explicit Way
INSERT INTO dept
VALUES (51,'Marketing',NULL);
Implicit Way
INSERT INTO dept(deptno,dname)
VALUES (52,‘Accounts');
Subquery with INSERT
We can use subquery with INSERT
statement
Do not use VALUES clause
The UPDATE Statement
Modify the existing rows with the
UPDATE statement
Update more than one row at a time, if
required
UPDATE table
SET column=value
WHERE condition
EMPLOYEE Update Queries
ENO Ename Title City
E1 Ali Engineer Lahore
Update the name of
E2 Ahmad Analyst Lahore
Tex_Acc to “Tax and
E3 Waqas Engineer Faisalabad
Accounting”
E4 Abdullah Programmer Multan
E5 Mansoor Programmer Lahore
Change P1 to P20 and
E6 Shehraz Analyst Lahore
Budget=30000
E7 Khubab Engineer Faisalabad Give Mansoor same title as
E8 Faraz Engineer Faisalabad
the title of Ahmad
PROJECT
PNO Pname Budget

P1 Surveys 150000

P2 Tex_Acc 135000

P3 C++ 250000

P4 Database 310000
Updating Values (Using Sub-Query)
DELETE Statement
DELETE Clause is used to delete rows
from a table
DELETE FROM table_name
WHERE condition;
DELETE Statement
DELETE Statement
EMPLOYEE Update Queries
ENO Ename Title City
E1 Ali Engineer Lahore
Delete record of employee
E2 Ahmad Analyst Lahore
E5
E3 Waqas Engineer Faisalabad
E4 Abdullah Programmer Multan Delete Record of Surveys
E5 Mansoor Programmer Lahore
Project
E6 Shehraz Analyst Lahore Delete Record of all
E7 Khubab Engineer Faisalabad Programmers
E8 Faraz Engineer Faisalabad

PROJECT
PNO Pname Budget

P1 Surveys 150000

P2 Tex_Acc 135000

P3 C++ 250000

P4 Database 310000
DATA DEFINITION
LANGUAGE (DDL)
CREATE TABLE
Creating Table

CREATE TABLE table_name


( column definition
table constraints);
Creating Table
Column Definition
column_name
datatype(Size)
column_constraint_clause
Default Value
Creating Table
Constraint Definition
CONSTRAINT constraint_name
Constraint_type(attribute)
CREATE TABLE (Using
Another Table)
CREATE TABLE new_table_name AS
SELECT column1, column2,...
FROM existing_table_name
WHERE ....;
CREATE TABLE TestTable AS
SELECT customername, contactname
FROM customers;
CREATE Table by SELECT
INTO
SELECT INTO statement is used to create a
table from an existing table by copying the
existing table's columns. It is important to
note that when creating a table in this way,
the new table will be populated with the
records from the existing table (based on
the SELECT Statement ).
SELECT INTO
SELECT INTO
SELECT INTO

Empty
Table
DATA DEFINITION
LANGUAGE (DDL)
CONSTRAINTS
Constraints
Enforce rules/Constraints in two ways
Table level
Column level
The constraint must be satisfied for an
operation(insert, update, delete) to
succeed
Constraint also prevent the deletion of
table if there are dependencies
CREATE Table (Column Level Versus
Table Level Constraints)
Column Lev
Column Level

Table Level
create table DEPT create table STR
( (
DEPT_ID number(2) primary key, DEPT_ID number(2) references dept (dept_id)
DEPT_NAME varchar2(50) not null, DSG_ID number(2) references dsg (dsg_id)
LOCTION varchar2(50) );
);
Constraints
The following constraints are valid:
1. DEFAULT
Provides Default value for column
2. NOT NULL
Specify this column may not contain NULL value
3. UNIQUE
Specify this column or combination of columns whose
values must be unique for all rows in table
4. PRIMARY KEY
Uniquely identify each row of table
5. FOREIGN KEY
Establish a foreign key relationship between tables
6. CHECK
Specify a condition that must be true
CREATE Table (Default Constraint)
CREATE Table (Default Constraint)
PRIMARY KEY Constraint
Only one PRIMARY KEY constraint can be
defined in a table
All columns involved in primary key cannot be
NULL
Column Level: job_id smallint PRIMARY KEY
Table Level: CONSTRAINT PK_emp_id
PRIMARY KEY (job_id,..)
UNIQUE Constraints
Enforce uniqueness on Non-Primary key
columns
Column Level: abc varchar(30) UNIQUE
Table Level: CONSTRAINT U_store
UNIQUE (stor_name, city)
FOREIGN KEY Constraint
FOREIGN KEY constraint reference
the other column table in database
FOREIGN KEY can also reference other
column in the same table(Self
reference)
A table can contain maximum of 253
FOREIGN KEY constraints
FOREIGN KEY Constraint
Following clauses can be used with FOREIGN
KEY constraints
FOREIGN KEY (column)
Column name in child table that is referenced
REFERENCES parent_table(column)
Parent table column should have the same
data type
ON DELETE CASCADE
ON UPDATE CASCADE
FOREIGN KEY Constraint
Column Level: job_id smallint NOT
NULL DEFAULT 1 FOREIGN KEY
(job_id) REFERENCES jobs(job_id)
Table Level: CONSTRAINT
FK_sales_backorder FOREIGN KEY
(stor_id, ord_num, title_id)
REFERENCES sales (stor_id, ord_num,
title_id)
CREATE Table (Foreign Key
Constraint)

A customer ID can only be deleted if it is not


found in ORDER table
CREATE Table (Foreign Key
Constraint)

ON UPDATE CASCADE);
Cascaded Update: Changing a customer ID in the
CUSTOMER table will result in that value changing in
the ORDER table to match
CREATE Table (Foreign Key Constraint)

ON UPDATE SET NULL);


When a customer ID is changed, any customer ID in the ORDER table that
matches the old customer ID is set to NULL.
ON UPDATE SET DEFAULT);
When a customer ID is changed, any customer ID in the ORDER
tables that matches the old customer ID is set to a predefined default
value.
UPDATE Employee
SET Eno='E3'
WHERE Eno='E1';
CREATE Table (Check Constraint)
The CHECK Constraint
Check constraint can restrict the type of value
that can be entered into the table
Column Level
CHECK (column_name expression)
CHECK (abc >= 10)
CHECK (pub_id IN ('1389', '0736', '0877', '1622',
'1756'))
Table Level: CONSTRAINT emp_deptno
CHECK (deptno BETWEEN 10 AND 99)
INSERT INTO Employee(Eno,Ename,Gender)
VALUES ('E1','J.Doe','F');
Example
CREATE TABLE Tutor

(
ID int PRIMARY KEY CHECK (ID>100),

JoiningDate varchar(50) DEFAULT ‘SYSTEM DATE’,

Status varchar(20) CHECK (Status in (‘Active’ , Non-Active , ’Dropped’)),

)
CREATE Table
TUTOR (ID, Joining_Date, Status)
ID: Greater than 100 )
Joining Date: Default system Date
Status: Active, Non-Active, Dropped
DATA DEFINITION
LANGUAGE (DDL)
ALTER TABLE
ALTER TABLE
Use the ALTER TABLE Clause to:
Add a new column
Modify the existing column
Dropping a column
ALTER Table
ALTER TABLE
ALTER TABLE table
ADD COLUMN datatype, CONSTRAINT;

ALTER TABLE table


MODIFY/ALTER COLUMN column_name SET
DEFAULT default-value

ALTER TABLE table


DROP COLUMN column_name
ALTER TABLE table
MODIFY/ALTER COLUMN column_name DROP DEFAU
ALTER Table
ALTER TABLE STR ADD CONSTRAINT
FK_DEPT FOREIGN KEY (DEPT_ID)
REFERENCES dept (dept_id);
MODIFY strength NOT NULL;
ALTER TABLE DEPT
MODIFY dept_name NOT NULL;

ALTER TABLE DEPT MODIFY


dept_name NULL;
Last Week Review
Constraints:
1. DEFAULT
2. NOT NULL
3. UNIQUE
4. PRIMARY KEY
5. FOREIGN KEY
6. CHECK
• ALTER Table
1. ADD new Column\Constraint
2. ALTER\MODIFY existing Column\Constraint
3. DROP existing Column\Constraint
DATA DEFINITION
LANGUAGE (DDL)
ALTER TABLE
ALTER Table
ALTER TABLE
ALTER TABLE table
ADD COLUMN datatype, CONSTRAINT;

ALTER TABLE table


MODIFY/ALTER COLUMN column_name SET
DEFAULT
ALTER TABLEdefault-value
table
ADD
ALTER TABLE table
table_constraint
DROP COLUMN column_name
ALTER TABLE table
MODIFY/ALTER COLUMN column_name DRO
ALTER Table
ALTER TABLE STR ADD CONSTRAINT FK_DEPT
FOREIGN KEY (DEPT_ID) REFERENCES dept (dept_id);
ALTER TABLE STR
MODIFY strength NOT NULL;
ALTER TABLE DEPT
MODIFY dept_name NOT NULL;

ALTER TABLE DEPT MODIFY dept_name NULL;


ALTER TABLE To Drop Column
Modify Column
ADD Column

DROP Column
Oracle ALTER TABLE
ALTER TABLE customers RENAME
COLUMN credit_limit TO credit_amount;
ALTER TABLE t1 DROP (c1); -- Do not
drop if used in contraints
ALTER TABLE t1 DROP (pk) CASCADE
CONSTRAINTS;-- Drop contraints and
column
ALTER TABLE Customer_1
ADD (Customer_Dept VARCHAR2 (20));
Oracle ALTER TABLE
ALTER TABLE Customer_Skill
DROP CONSTRAINT abc1;
ALTER TABLE Customer_1
DROP COLUMN Customer_Dept;
DROP Table
All data and structure of the table is
deleted from the data base
Cannot roll back this command
DROP TABLE table_name
TRUNCATE TABLE table_name (Only
Delete Table Data)
DROP Table
RENAME
Rename clause can be used to change
the name of an object
RENAME Dept TO Department;
Create & Delete Database
Following is the syntax of creating
database:
CREATE DATABASE database_name
If we want to Delete the database:
DROP DATABASE database_name
Naming Conventions
Must begin with a letter
Can be 1-30 character long
Must contain only A-Z, a-z , 0-9 , _ , $,
and #
Must not duplicate the name
Must not be a reserved word
DATA DEFINITION
LANGUAGE (DDL)
CREATE VIEW
Database Views
Base table (CREATE TABLE)
A table in the relational data model
containing the inserted raw data. Base
tables correspond to the relations that are
identified in the database’s conceptual
schema.
Database Views
Virtual table
A table constructed automatically as
needed by a DBMS. Virtual tables are
not maintained as real data.
Why to Use Views?
To restrict database access
To make complex queries easy
To allow data independence
To present different views of same data
Using and Defining Views
Dynamic View
A “virtual table” created dynamically upon request by a
user
No data actually stored; instead data from base table
made available to user
Based on SQL SELECT statement on base tables or
other views
Materialized View
Copy or replication of data
Data actually stored
Must be refreshed periodically to match the
corresponding base tables
468
Using and Defining Views
Basis View Materialized View
Basic A view is never stored. It is only A Materialized view is stored on the
displayed disk
Define View is the Virtual table formed Materialized view is a physical copy
from one or more base tables or of base table
views
Update View is updated each time the Materialized view must be updated
virtual table(view) is used manually or using trigger
Speed Slow processing Fast processing
Memor View do not require memory Materialized view used memory
y space space.
Usage

Syntax Create View V as Create materialized view V


build[clause] refresh [clause] on
trigger as
469
Views
Syntax of CREATE VIEW:
CREATE VIEW view-name AS
SELECT (that provides the rows and
columns of the view)
Example:
CREATE VIEW ORDER_TOTALS_V AS
SELECT PRODUCT_ID PRODUCT,
SUM(STANDARD_PRICE*QUANTITY) TOTAL
FROM INVOICE_V
GROUP BY PRODUCT_ID;
Types of Views (Complexity)
Simple Views
Complex Views
Simple Views
CREATE VIEW PhysicianView
AS
SELECT EmployeeID, Name
FROM PHYSICIAN
WHERE dept=2;
Querying Views
SELECT * FROM physicianview;
Aggregate Function in Views
Complex Views (More than one Table)
CREATE VIEW AnnulaSalary
AS
SELECT EmployeeID, Name, Grade AS "Pay Grade", Sal AS
Salary, Sal*12 AS "Anual Salary"
FROM physician p JOIN SALARY s ON
(p.GRADE=s.gradeID);
Complex Views
Complex Views
Views created on Views
A view may join together multiple tables
or views and may contain derived (or
virtual)columns
Updateable Views

/+
/+
Updating Through View
CREATE VIEW PhysicianView2
AS
SELECT *
FROM PHYSICIAN
WHERE dept>2;

UPDATE physicianview2
SET GRADE=4
WHERE EMPLOYEEID=9;
Using WITH CHECK OPTION
Sample CREATE VIEW

484
No DML
1. The SELECT clause includes the keyword
DISTINCT.
2. The SELECT clause contains expressions,
including derived columns, aggregates, statistical
functions, and so on.
3. The FROM clause, a subquery, or a UNION clause
references more than one table.
4. The FROM clause or a subquery references
another view that is not updateable.
5. The CREATE VIEW command contains a GROUP
BY or HAVING clause.
No DML Operations on Views
No DML Operations on Views
Removing View
SEQUENCES & IDENTITY
COLUMN
Identity Columns
In many cases, we want to generate a
unique primary identifier or primary key
every time a row is added to a table. of
SQL:200n had added a new feature,
identity columns
Removes the previous need to create a
procedure to generate a sequence and
then apply it to the insertion of data
Identity Columns (SQL Server)
IDENTITY(Start Value, Increment)

CREATE TABLE Student_T (


ID int IDENTITY(1,1) PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
INSERT INTO Student_T VALUES('Ali','Ahmad',23);
INSERT INTO Student_T VALUES('Maqbool','Ahmad',24);
INSERT INTO Student_T VALUES('Mansoor','Ahmad',25);
Sequences (SQL Server)
CREATE SEQUENCE sequence_name [ AS datatype ]
[ START WITH value ]
[ INCREMENT BY value ]
[ MINVALUE value | NO MINVALUE ]
[ MAXVALUE value | NO MAXVALUE ]
[ CYCLE | NO CYCLE ]
[ CACHE value | NO CACHE ];
Sequences (SQL Server)
CREATE SEQUENCE contacts_seq AS BIGINT
START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 99999
NO CYCLE
CACHE 10;
INSERT INTO Contacts_T
VALUES(NEXT VALUE FOR Contacts_seq,'Ali','Ahmad',23);
INSERT INTO Contacts_T
VALUES(NEXT VALUE FOR
Contacts_seq,'Maqbool','Ahmad',24);
Sequences (SQL Server)
CREATE SEQUENCE abc
START WITH 1
INCREMENT BY 1;

Select NEXT VALUE FOR Contacts_seq;

DROP SEQUENCE Contacts_seq


Sequences (Oracle)
CREATE SEQUENCE seq_person
MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 10;
INSERT INTO Persons (ID,FirstName,LastName)
VALUES (seq_person.nextval,'Lars','Monsen');
Identity Columns (Oracle)
Last Week Review
• ALTER Table
1. ADD new Column\Constraint
2. ALTER\MODIFY existing Column\Constraint
3. DROP existing Column\Constraint

VIEWS
1. How to Create
2. Dynamic & Materialized
3. Simple & Complex Views
4. Benefits
Types of Views (Complexity)
Simple Views

Complex Views
Simple Views
CREATE VIEW PhysicianView
AS
SELECT EmployeeID, Name
FROM PHYSICIAN
WHERE dept=2;
Querying Views
SELECT * FROM physicianview;
Complex Views
Complex Views
Views created on Views
A view may join together multiple tables
or views and may contain derived (or
virtual)columns
Updateable Views
Updating Through View
CREATE VIEW PhysicianView2
AS
SELECT *
FROM PHYSICIAN
WHERE dept>2;

UPDATE physicianview2
SET GRADE=4
WHERE EMPLOYEEID=9;
Using WITH CHECK OPTION
Sample CREATE VIEW
No DML
1. The SELECT clause includes the keyword
DISTINCT.
2. The SELECT clause contains expressions,
including derived columns, aggregates, statistical
functions, and so on.
3. The FROM clause, a subquery, or a UNION clause
references more than one table.
4. The FROM clause or a subquery references
another view that is not updateable.
5. The CREATE VIEW command contains a GROUP
BY or HAVING clause.
No DML Operations on Views
No DML Operations on Views
Removing View
SEQUENCES & IDENTITY
COLUMN
Identity Columns
In many cases, we want to generate a
unique primary identifier or primary key
every time a row is added to a table. of
SQL:200n had added a new feature,
identity columns
Removes the previous need to create a
procedure to generate a sequence and
then apply it to the insertion of data
Identity Columns (SQL Server)
IDENTITY(Start Value, Increment)

CREATE TABLE Student_T (


ID int IDENTITY(1,1) PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
INSERT INTO Student_T VALUES('Ali','Ahmad',23);
INSERT INTO Student_T VALUES('Maqbool','Ahmad',24);
INSERT INTO Student_T VALUES('Mansoor','Ahmad',25);
Sequences (SQL Server)
CREATE SEQUENCE sequence_name [ AS datatype ]
[ START WITH value ]
[ INCREMENT BY value ]
[ MINVALUE value | NO MINVALUE ]
[ MAXVALUE value | NO MAXVALUE ]
[ CYCLE | NO CYCLE ]
[ CACHE value | NO CACHE ];
Sequences (SQL Server)
CREATE SEQUENCE contacts_seq AS BIGINT
START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 99999
NO CYCLE
CACHE 10;
INSERT INTO Contacts_T
VALUES(NEXT VALUE FOR Contacts_seq,'Ali','Ahmad',23);
INSERT INTO Contacts_T
VALUES(NEXT VALUE FOR
Contacts_seq,'Maqbool','Ahmad',24);
Sequences (SQL Server)
CREATE SEQUENCE abc
START WITH 1
INCREMENT BY 1;

Select NEXT VALUE FOR Contacts_seq;

DROP SEQUENCE Contacts_seq


Sequences (Oracle)
CREATE SEQUENCE seq_person
MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 10;
INSERT INTO Persons (ID,FirstName,LastName)
VALUES (seq_person.nextval,'Lars','Monsen');
Identity Columns (Oracle)
PROCEDURES
Procedures
A stored procedure code can be reused
over and over again.
So if you have an SQL query that you
write over and over again, save it as a
stored procedure, and then just call it
to execute it.
Pass parameters to a stored procedure
Procedures (SQL Server)
CREATE PROCEDURE SelectAllStudents_1
AS
SELECT * FROM Student_T
GO;
EXEC SelectAllStudents_1
Procedures (SQL Server)
Alter Procedures (SQL Server)
EMPLOYEE ASG
ENO PNO Resp
PAY
ENO Ename Title
E1 J.Doe Elect.Eng E1 P1 Manager Title Sal
E2 M.Smith Analyst E2 P1 Analyst Elect.Eng 58,000

E2 P2 Analyst Analyst 48,000


E3 A.Lee Engineer
Mech.Eng 20,000
E3 P3 Consultant
E4 J.Miller Programmer
Programmer 55,000
E3 P4 Engineer
E5 A.Lee Manager
E6 P2 Programm
ROJECT er

PNO Pname Budget


P1 Surveys 150000
Write a procedure which join
P2 Tex_Acc 135000 EMPLOYEE and PAY?
P3 C++ 250000
P4 Database 310000
Drop Procedures (SQL Server)
Parameter to Procedures
(SQL Server)
Procedures (SQL Server)
EMPLOYEE ASG
ENO PNO Resp
PAY
ENO Ename Title
E1 J.Doe Elect.Eng E1 P1 Manager Title Sal
E2 M.Smith Analyst E2 P1 Analyst Elect.Eng 58,000

E2 P2 Analyst Analyst 48,000


E3 A.Lee Engineer
Mech.Eng 20,000
E3 P3 Consultant
E4 J.Miller Programmer
Programmer 55,000
E3 P4 Engineer
E5 A.Lee Manager
E6 P2 Programm
ROJECT er

PNO Pname Budget


P1 Surveys 150000
Write a procedure which show
P2 Tex_Acc 135000 Ename, Title and Sal of passed
P3 C++ 250000 Ename after join EMPLOYEE
P4 Database 310000
and PAY?
Procedures (Multiple Named Parameters)
Procedures (Default Value)
Procedures (NULL Default Value)
Procedures (Variables)
DECLARE @model_year SMALLINT;
SET @model_year = 2018;
SELECT product_name, model_year, list_price
FROM production.products
WHERE model_year = @model_year
ORDER BY product_name;
Procedures (Variables)
Procedures (Return / Output
Value )

@@ROWCOUNT
system variable. This
variable returns the
CURSORS
CURSORS
A database cursor can be thought of as
a pointer to a specific row within a
query result. The pointer can be moved
from one row to the next. Depending
on the type of cursor, you may be even
able to move it to the previous row.
CURSORS
Think of it this way: a SQL result is
like a bag, you get to hold a whole
bunch of rows at once, but not any of
them individually; whereas, a cursor is
like a pair of tweezers. With it, you
can reach into the bag and grab a row,
and then move onto the next.
CURSORS
Cursor is a Temporary Memory or
Temporary Work Station. It is Allocated
by Database Server at the Time of
Performing DML operations on Table by
User. Cursors are used to store
Database Tables. There are 2 types of
Cursors: Implicit Cursors, and Explicit
Cursors.
CURSORS
Implicit Cursors:
Implicit Cursors are also known as Default
Cursors of SQL SERVER. These Cursors are
allocated by SQL SERVER when the user
performs DML operations.
Explicit Cursors :
Explicit Cursors are Created by Users
whenever the user requires them.
Explicit Cursors are used for Fetching data
from Table in Row-By-Row Manner.
Using CURSORS
Using CURSORS
DECLARE cursor_product CURSOR
FOR SELECT *
FROM production.products;
OPEN cursor_product;
FETCH NEXT FROM cursor_product
CLOSE cursor_product;
DEALLOCATE cursor_product;
Fetch Data from cursor
There are total 6 methods to access data
from cursor. They are as follows :
FIRST is used to fetch only the first row from
cursor table.
LAST is used to fetch only last row from
cursor table.
NEXT is used to fetch data in forward
direction from cursor table.
PRIOR is used to fetch data in backward
direction from cursor table.
Fetch Data from cursor
ABSOLUTE n is used to fetch the exact
nth row from cursor table.
RELATIVE n is used to fetch the data
in incremental way as well as
decremental way.
Syntax : FETCH
NEXT/FIRST/LAST/PRIOR/ABSOLUTE
n/RELATIVE n FROM cursor_name
Fetch Data from cursor
Using CURSORS
DECLARE @product_name VARCHAR(MAX),
@list_price DECIMAL;
DECLARE cursor_product CURSOR
FOR SELECT product_name, list_price
FROM production.products;
OPEN cursor_product;
FETCH NEXT FROM cursor_product INTO
@product_name,
@list_price;
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @product_name + CAST(@list_price AS varchar);
FETCH NEXT FROM cursor_product INTO
@product_name,
@list_price;
END;
CLOSE cursor_product;
DEALLOCATE cursor_product;
Last Week Review
• Sequences & Identity Column
Procedures
1. How to Create
2. Alter Procedure
3. Drop Procedure
4. Parameters to a Procedure
5. Default Values
6. Output Parameters
1. Variables
2. Cursors
Procedures (Default Value)
CURSORS
CURSORS
Cursor is a Temporary Memory
It is Allocated by Database Server at
the Time of Performing DML operations
on Table by User.
Cursors are used to store Database
Tables.
There are 2 types of Cursors:
Implicit Cursors,
and Explicit Cursors.
CURSORS
Implicit Cursors:
Implicit Cursors are also known as Default
Cursors of SQL SERVER. These Cursors are
allocated by SQL SERVER when the user
performs DML operations.
Explicit Cursors :
Explicit Cursors are Created by Users
whenever the user requires them. Explicit
Cursors are used for Fetching data from
Table in Row-By-Row Manner.
Using CURSORS
Using CURSORS
DECLARE cursor_product CURSOR FOR
SELECT *
FROM production.products;
OPEN cursor_product;
FETCH NEXT FROM cursor_product
CLOSE cursor_product;
DEALLOCATE cursor_product;
Fetch Data from cursor
There are total 6 methods to access data
from cursor. They are as follows :
FIRST is used to fetch only the first row from
cursor table.
LAST is used to fetch only last row from
cursor table.
NEXT is used to fetch data in forward
direction from cursor table.
PRIOR is used to fetch data in backward
direction from cursor table.
Fetch Data from cursor
ABSOLUTE n is used to fetch the exact
nth row from cursor table.
RELATIVE n is used to fetch the data
in incremental way as well as
decremental way.
Syntax : FETCH
NEXT/FIRST/LAST/PRIOR/ABSOLUTE
n/RELATIVE n FROM cursor_name
Fetch Data from cursor
DECLARE @product_name VARCHAR(MAX),
@list_price DECIMAL;
DECLARE cursor_product CURSOR
FOR SELECT product_name, list_price

Using CURSORS
FROM production.products;
OPEN cursor_product;
FETCH NEXT FROM cursor_product INTO
@product_name,
@list_price;
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @product_name + CAST(@list_price AS varchar);
FETCH NEXT FROM cursor_product INTO
@product_name,
@list_price;
END;
CLOSE cursor_product;
DEALLOCATE cursor_product;
SYNONYMS
Synonyms
A synonym is an alias or alternative
name for a database object such as a
table, view, stored procedure,
user-defined function, and
sequence. A synonym provides you
with many benefits if you use it
properly
Benefits of Synonyms
Synonym provides the following benefit if
you use them properly:
•Provide a layer of abstraction over the
base objects.
•Shorten the lengthy name
•Allow backward compatibility for the
existing applications when you rename
database objects such as tables, views,
stored procedures, user-defined functions,
and sequences.
Synonyms
CREATE SYNONYM ord FOR
sales.orders;
SELECT * FROM orders;
INDEXES
Creating Indexes
Indexes are created in most RDBMSs to
provide rapid random and sequential
access to base-table data.
Because the ISO SQL standards do not
generally address performance
No standard syntax for creating indexes
is included.
Creating Indexes
Oracle syntax and
the DBMS recognizes which existing
indexes would improve query
performance.
Indexes can usually be created for both
primary and secondary keys For
example, an alphabetical index on
CustomerName in the Customer_T tab
Indexes
The index is itself a table with two
columns: the key and the address of
the record or records that contain that
key value.
For a primary key, there will be only
one entry in the index for each key
value.
Unique Key Index
The unique key index in Customer table
primary key CustomerID would be
created using the following SQL
command:
Unique Key Index
For composite unique key, you simply
list all the elements of the unique key in
the ON clause
Non-unique Key Index
Database users often want to retrieve
rows of a relation based on values for
various attributes other than the
primary key.
Term UNIQUE should not be used with
secondary (nonunique) key attributes
Creating Non Unique Indexes
When to Use Indexes
During physical database design, you must
choose which attributes to use to create
indexes.
There is a trade-off between improved
performance for retrievals through the use
of indexes and degraded performance
(because of the overhead for extensive
index maintenance) for inserting, deleting,
and updating the indexed records in a file.,
When to Use Indexes
Indexes should be used generously for
databases intended primarily to support
data retrievals such as for decision
support and data warehouse
applications.
Indexes should be used judiciously for
databases that support transaction
processing
Rules for Using Indexes
1. Use on larger tables
2. Index the primary key of each table
3. Index search fields (fields frequently
in WHERE clause)
4. Fields in SQL ORDER BY and GROUP
BY commands
5. When there are >100 values but not
when there are <30 values
Rules for Using Indexes (cont.)
6. Avoid use of indexes for fields with long
values; perhaps compress values first
7. DBMS may have limit on number of indexes
per table and number of bytes per indexed
field(s)
8. Null values will not be referenced from an
index
9. Use indexes heavily for non-volatile
databases; limit the use of indexes for
volatile databases
Why? Because modifications (e.g. inserts, deletes) require
updates to occur in index files
SET OPERATIONS:
MINUS, UNION, INTERSECTION
SET Operations
SET Operations are used to combine
Multiple queries
MINUS/EXCEPT
UNION
UNION ALL
INTERSECT
MINUS/EXCEPT
The MINUS operator will retrieve all
records from the first table and then
remove from the results all records
from the second dataset.
SET operation: minus
Exclude the designated records
Example: Find instructors who do not
have the same last name as students
SELECT instructor_name AS Name
FROM instructor
MINUS
SELECT student_lname AS Name
From student
MINUS
ORACLE SQL Server
EMPLOYEE
ENO Ename Title City
ENO PNO Resp
E1 Ali Engineer Lahore ASG E1 P1 Manager
E2 Ahmad Analyst Lahore
E3 Waqas Engineer Faisalabad E2 P1 Analyst

E4 Abdullah Programmer Multan


E2 P2 Analyst
E5 Mansoor Programmer Lahore
E3 P3 Consultant
E6 Shehraz Analyst Lahore
E7 Khubab Engineer Faisalabad E3 P4 Engineer

E8 Faraz Engineer Faisalabad


E6 P2 Programmer

Show ENOs of employees who are PAY Title Sal


not working on any project? Elect.Eng 58,000
Analyst 48,000
Mech.Eng 20,000
Programmer 55,000
UNION / UNION ALL
UNION operator is used to combine the result
sets of 2 or more SELECT statements.
Each SELECT statement within the UNION
operator must have:
the same number of columns
similar data types
UNION OPERATOR removes duplicate rows
between the various SELECT statements.
UNION ALL OPERATOR removes duplicate
rows between the various SELECT
statements.
UNION
SELECT expression1,... expression_n
FROM tables
[WHERE conditions]
UNION
SELECT expression1,... expression_n
FROM tables
[WHERE conditions];
UNION
SELECT supplier_id, supplier_name
FROM suppliers
WHERE supplier_id <= 500
UNION
SELECT company_id, company_name
FROM companies
WHERE company_name = 'Apple'
ORDER BY 2;
Union Queries
Combine the output (union of multiple queries)
together into a single result table

First query
Combine

Second query
Combining queries using UNION

Note: with
UNION queries,
the quantity and
data types of the
attributes in the
SELECT clauses
of both queries
must be identical
UNION ALL
SELECT supplier_id, supplier_name
FROM suppliers
WHERE state = 'California'
UNION ALL
SELECT company_id, company_name
FROM companies
WHERE company_id > 1000
ORDER BY 2;
INTERSECT Operator
INTERSECT operator is used to return
the records that are in common
between two SELECT statements or
data sets.
INTERSECT Operator
SELECT supplier_id, supplier_name
FROM suppliers
WHERE supplier_id > 500
INTERSECT
SELECT company_id, company_name
FROM companies
WHERE company_name in ( 'Apple',
'Microsoft', 'SQL Server' )
ORDER BY 2;
SELECT TOP \ DELETE TOP
SELECT TOP
SELECT TOP(5) SELECT TOP(5) WITH TIES
employee_id, last_name, employee_id, last_name,
first_name
first_name
FROM employees
FROM employees
WHERE last_name =
'Anderson' WHERE last_name =
ORDER BY employee_id; 'Anderson'
ORDER BY employee_id;
SELECT TOP PERCENT
SELECT TOP(5) PERCENT SELECT TOP(5) PERCENT
employee_id, last_name, WITH TIES
first_name employee_id, last_name,
FROM employees first_name
WHERE last_name =
FROM employees
'Anderson'
ORDER BY employee_id; WHERE last_name =
'Anderson'
ORDER BY employee_id;
DELETE TOP/PERCENT
DELETE TOP(10) DELETE TOP(25) PERCENT
FROM employees FROM employees
WHERE last_name = WHERE first_name = 'Sarah'
'Anderson';
OTHER TOPICS IN SQL
- Self Join
- Transactions
- SYSTEM TABLES
- Order Of Execution
- Tips For Developing
Queries
596

Self-Join Example

Self-joins are often used on tables with unary relationships


Example of a Self-Join

597
Ensuring Transaction Integrity
Transaction = A discrete unit of work that
must be completely processed or not
processed at all
May involve multiple updates
If any update fails, then all other updates must be
cancelled
SQL commands for transactions
BEGIN TRANSACTION/END TRANSACTION
Marks boundaries of a transaction
COMMIT
Makes all updates permanent
ROLLBACK
Cancels updates since the last COMMIT
An SQL Transaction sequence (in pseudocode)
Data Dictionary Facilities
System tables that store metadata
Users usually can view some of these tables
Users are restricted from updating them
Some examples in Oracle 11g
DBA_TABLES – descriptions of tables
DBA_CONSTRAINTS – description of constraints
DBA_USERS – information about the users of the system
Examples in Microsoft SQL Server 2008
sys.columns – table and column definitions
sys.indexes – table index information
sys.foreign_key_columns – details about columns in
foreign key constraints
Tips for Developing Queries
Be familiar with the data model (entities and
relationships)
Understand the desired results
Know the attributes desired in result
Identify the entities that contain desired
attributes
Review ERD
Construct a WHERE equality for each link
Fine tune with GROUP BY and HAVING
clauses if needed
Query Efficiency Considerations
Instead of SELECT *, identify the specific
attributes in the SELECT clause; this helps
reduce network traffic of result set
Limit the number of subqueries; try to
make everything done in a single query if
possible
If data is to be used many times, make a
separate query and store its results rather
than performing the query repeatedly
Guidelines for Better Query Design
Write simple queries
Break complex queries into multiple simple parts
Understand how indexes are used in query
processing
Keep optimizer statistics up-to-date
Use compatible data types for fields and literals
Don’t nest one query inside another query
Don’t combine a query with itself (if possible
avoid self-joins)

You might also like