0% found this document useful (0 votes)
27 views27 pages

BCA III DBMS Notes Chapter 3

Uploaded by

Subrahmanya
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)
27 views27 pages

BCA III DBMS Notes Chapter 3

Uploaded by

Subrahmanya
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/ 27

DATABASE MANAGEMENT SYSTEM

CHAPTER 3
Relational Data Model

Relational Model

Relational Model represents how data is stored in Relational Databases. A


relational database stores data in the form of relations (tables). Consider a
relation STUDENT with attributes ROLL_NO, NAME, ADDRESS, PHONE and AGE
shown in Table 1.

ROLL_NO NAME ADDRESS PHONE AGE


1 RAM DELHI 9455123451 18
2 RAMESH GURGAON 9652431543 18
3 SUJIT ROHTAK 9156253131 20
4 SURESH DELHI 18

Terminologies to know

 Attribute:
Attributes are the properties that define a relation. e.g.; ROLL_NO, NAME

 Relation Schema:
A relation schema represents name of the relation with its attributes. e.g.;
STUDENT (ROLL_NO, NAME, ADDRESS, PHONE and AGE) is relation schema
for STUDENT. If a schema has more than 1 relation, it is called Relational
Schema.

 Tuple:
Each row in the relation is known as tuple. The above relation contains 4
tuples, one of which is shown as:
1 RAM DELHI 9455123451 18
 Relation Instance:
The set of tuples of a relation at a particular instance of time is called as
relation instance. Table 1 shows the relation instance of STUDENT at a
particular time. It can change whenever there is insertion, deletion or
updating in the database.

 Degree:

1|Page
DATABASE MANAGEMENT SYSTEM

The number of attributes in the relation is known as degree of the relation.


The STUDENT relation defined above has degree 5.

 Cardinality:
The number of tuples in a relation is known as cardinality.
The STUDENT relation defined above has cardinality 4.

 Column:
Column represents the set of values for a particular attribute. The
column ROLL_NO is extracted from relation STUDENT.

ROLL_NO
1
2
3
4

 NULL Values:
The value which is not known or unavailable is called NULL value. It is
represented by blank space. e.g.; PHONE of STUDENT having ROLL_NO 4 is
NULL.

Characteristics of Relation

1. Each relation in a database must have a distinct or unique name which


would separate it from the other relations in a database.

2. A relation must not have two attributes with the same name. Each
attribute must have a distinct name.

3. Duplicate tuples must not be present in a relation.

4. Each tuple must have exactly one data value for an attribute.
2|Page
DATABASE MANAGEMENT SYSTEM

5. Tuples in a relation do not have to follow a significant order as the relation


is not order-sensitive.

6. Similarly, the attributes of a relation also do not have to follow certain


ordering, it’s up to the developer to decide the ordering of attributes.

Relational Model Constraints


Domain Constraints:
These are attribute level constraints. An attribute can only take values
which lie inside the domain range.
For Example, if a constrains AGE>0 is applied on STUDENT relation, inserting
negative value of AGE will result in failure.

Key Constraints:
Every relation in the database should have at least one set of attributes
which defines a tuple uniquely. Those set of attributes is called key. e.g.;
ROLL_NO in STUDENT is a key. No two students can have same roll number. So
a key has two properties:
 It should be unique for all tuples.
 It can’t have NULL values.

Primary Key Constraints:


A primary key constraint depicts a key comprising one or more columns
that will help uniquely identify every tuple/record in a table.

Properties:

1. No duplicate values are allowed, i.e. Column assigned as primary key


should have UNIQUE values only.
3|Page
DATABASE MANAGEMENT SYSTEM

2. NO NULL values are present in column with Primary key. Hence there is
Mandatory value in column having Primary key.
3. Only one primary key per table exist although Primary key may have
multiple columns.
4. No new row can be inserted with the already existing primary key.
5. Classified as
a) Simple primary key that has a Single column
b) Composite primary key has multiple column.
6. Defined in Create table / Alter table statement.

The primary key can be created in a table using PRIMARY KEY constraint. It
can be created at two levels.
1. Column
2. Table.

Syntax:
Create Table Person
(
Id int NOT NULL PRIMARY KEY,
Name varchar2(20),
Address varchar2(50)
);

Foreign Key Constraints


Foreign key is a column that refers to the primary key/unique key of other
table. So it demonstrates relationship between tables and act as cross
reference among them. Table in which foreign key is defined is called Foreign
table/Referencing table. Table that defines primary/unique key and is
referenced by foreign key is called primary table/master table/ Referenced
Table. It is defined in Create table/Alter table statement.
For the table that contains foreign key, it should match the primary key in
referenced table for every row. This is called Referential Integrity. Foreign key
ensures referential integrity.
Properties:
 Parent that is being referenced has to be unique/Primary Key.
 Child may have duplicates and nulls.
 Parent record can be deleted if no child exists.
4|Page
DATABASE MANAGEMENT SYSTEM

 Master table cannot be updated if child exists.


 Must reference PRIMARY KEY in primary table.
 Foreign key column and constraint column should have matching data
types.
 Records cannot be inserted in child table if corresponding record in
master table do not exist.
 Records of master table cannot be deleted if corresponding records in
child table exits.

Syntax: Foreign key at attribute level


Create table people (no int references person, Fname varchar2(20));
OR
Create table people (no int references person(id), Fname
varchar2(20));

Syntax: Foreign key at table level


create table people(no varchar2(10), fname varchar2(20), foreign
key(no) references person);
OR
create table people(no varchar2(10), fname varchar2(20), foreign
key(no) references person(id));

Entity Integrity Constraints:


Entity Integrity constraints says that no primary key can take NULL value,
since using primary key we identify each tuple uniquely in a relation.

Example: Explanation:
In the above relation, EID is made
primary key, and the primary key can’t
take NULL values but in the third tuple,
the primary key is null, so it is a violating
Entity Integrity constraints.

Relational Algebra:
Basic Relational Algebra Operations and Set Theoretical Operations

5|Page
DATABASE MANAGEMENT SYSTEM

Relational algebra is a procedural query language. It gives a step by step process to obtain
the result of the query. It uses operators to perform queries.

Select Operation:
o The select operation selects tuples that satisfy a given predicate.
o It is denoted by sigma (σ).
Notation: σ p(r)
Where:
σ is used for selection prediction
r is used for relation
p is used as a propositional logic formula which may use connectors like: AND
OR and NOT. These relational can use as relational operators like =, ≠, ≥, <, >, ≤.

For example: LOAN Relation


BRANCH_NAME LOAN_NO AMOUNT

Downtown L-17 1000

Redwood L-23 2000

Perryride L-15 1500

Downtown L-14 1500

Mianus L-13 500

Roundhill L-11 900

Perryride L-16 1300

Input Query: σ BRANCH_NAME="perryride" (LOAN)

Output:

6|Page
DATABASE MANAGEMENT SYSTEM

BRANCH_NAME LOAN_NO AMOUNT

Perryride L-15 1500

Perryride L-16 1300

Project Operation:
o This operation shows the list of those attributes that we wish to appear in
the result. Rest of the attributes are eliminated from the table.
o It is denoted by ∏.

Notation: ∏ A1, A2, An (r)

Where
A1, A2, A3 is used as an attribute name of relation r.

Example: CUSTOMER RELATION

NAME STREET CITY

Jones Main Harrison

Smith North Rye

Hays Main Harrison

Curry North Rye

Johnson Alma Brooklyn

Brooks Senator Brooklyn

Input:

∏ NAME, CITY (CUSTOMER)

Output:

NAME CITY

Jones Harrison

Smith Rye

Hays Harrison

7|Page
DATABASE MANAGEMENT SYSTEM

Curry Rye

Johnson Brooklyn

Brooks Brooklyn

Union Operation:
o Suppose there are two tuples R and S. The union operation contains all
the tuples that are either in R or S or both in R & S.
o It eliminates the duplicate tuples. It is denoted by ∪.
Notation: R ∪ S

A union operation must hold the following condition:


o R and S must have the attribute of the same number.
o Duplicate tuples are eliminated automatically.

Example: DEPOSITOR RELATION

CUSTOMER_NAME ACCOUNT_NO

Johnson A-101

Smith A-121

Mayes A-321

Turner A-176

Johnson A-273

Jones A-472

Lindsay A-284

BORROW RELATION

8|Page
DATABASE MANAGEMENT SYSTEM

CUSTOMER_NAME LOAN_NO

Jones L-17

Smith L-23

Hayes L-15

Jackson L-14

Curry L-93

Smith L-11

Williams L-17

Input:

1. ∏ CUSTOMER_NAME (BORROW) ∪ ∏ CUSTOMER_NAME (DEPOSITOR)

Output:

CUSTOMER_NAME

Johnson

Smith

Hayes

Turner

Jones

Lindsay

Jackson

9|Page
DATABASE MANAGEMENT SYSTEM

Curry

Williams

Mayes

Set Intersection:
o Suppose there are two tuples R and S. The set intersection operation
contains all tuples that are in both R & S.
o It is denoted by intersection ∩.

Notation: R ∩ S

Example: Using the above DEPOSITOR table and BORROW table

Input:
∏ CUSTOMER_NAME (BORROW) ∩ ∏ CUSTOMER_NAME (DEPOSITOR)
Output:

CUSTOMER_NAME

Smith

Jones

Set Difference:
o Suppose there are two tuples R and S. The set intersection operation
contains all tuples that are in R but not in S.
o It is denoted by intersection minus (-).

Notation: R - S

Example: Using the above DEPOSITOR table and BORROW table

Input:

∏ CUSTOMER_NAME (BORROW) - ∏ CUSTOMER_NAME (DEPOSITOR)

Output:

10 | P a g e
DATABASE MANAGEMENT SYSTEM

CUSTOMER_NAME

Jackson

Hayes

Willians

Curry

Cartesian product

The Cartesian product is used to combine each row in one table with each
o
row in the other table. It is also known as a cross product.
o It is denoted by X.
Notation: E X D
Example:
EMPLOYEE
EMP_ID EMP_NAME EMP_DEPT

1 Smith A

2 Harry C

3 John B
DEPARTMENT
DEPT_NO DEPT_NAME

A Marketing

B Sales

C Legal
Input:
EMPLOYEE X DEPARTMENT
Output:

11 | P a g e
DATABASE MANAGEMENT SYSTEM

EMP_ID EMP_NAME EMP_DEPT DEPT_NO DEPT_NAME

1 Smith A A Marketing

1 Smith A B Sales

1 Smith A C Legal

2 Harry C A Marketing

2 Harry C B Sales

2 Harry C C Legal

3 John B A Marketing

3 John B B Sales

3 John B C Legal

Rename Operation:
The rename operation is used to rename the output relation. It is denoted
by rho (ρ).
Example: We can use the rename operator to rename STUDENT relation to
STUDENT1.
ρ(STUDENT1, STUDENT)

JOIN Operations

A Join operation combines related tuples from different relations, if and only if
a given join condition is satisfied. It is denoted by ⋈.

Example:

EMPLOYEE

EMP_CODE EMP_NAME

12 | P a g e
DATABASE MANAGEMENT SYSTEM

101 Stephan

102 Jack

103 Harry

SALARY

EMP_CODE SALARY

101 50000

102 30000

103 25000

Operation: (EMPLOYEE ⋈ SALARY)

Result:
EMP_CODE EMP_NAME SALARY

101 Stephan 50000

102 Jack 30000

103 Harry 25000

13 | P a g e
DATABASE MANAGEMENT SYSTEM

Natural Join:
o A natural join is the set of tuples of all combinations in R and S that are
equal on their common attribute names.
o It is denoted by ⋈.

Example: Let's use the above EMPLOYEE table and SALARY table:
Input:
∏EMP_NAME, SALARY (EMPLOYEE ⋈ SALARY)
Output:
EMP_NAME SALARY

Stephan 50000

Jack 30000

Harry 25000

Outer Join:

The outer join operation is an extension of the join operation. It is used to deal
with missing information.

Example:

14 | P a g e
DATABASE MANAGEMENT SYSTEM

EMPLOYEE

EMP_NAME STREET CITY

Ram Civil line Mumbai

Shyam Park street Kolkata

Ravi M.G. Street Delhi

Hari Nehru nagar Hyderabad

FACT_WORKERS

EMP_NAME BRANCH SALARY

Ram Infosys 10000

Shyam Wipro 20000

Kuber HCL 30000

Hari TCS 50000

Input:
(EMPLOYEE ⋈ FACT_WORKERS)

Output:

15 | P a g e
DATABASE MANAGEMENT SYSTEM

EMP_NAME STREET CITY BRANCH SALARY

Ram Civil line Mumbai Infosys 10000

Shyam Park street Kolkata Wipro 20000

Hari Nehru nagar Hyderabad TCS 50000

An outer join is basically of three types:

a. Left outer join


b. Right outer join
c. Full outer join

a. Left outer join:

o Left outer join contains the set of tuples of all combinations in R and S that
are equal on their common attribute names.
o In the left outer join, tuples in R have no matching tuples in S.
o It is denoted by ⟕.

Example: Using the above EMPLOYEE table and FACT_WORKERS table


Input:
EMPLOYEE ⟕ FACT_WORKERS
EMP_NAME STREET CITY BRANCH SALARY

Ram Civil line Mumbai Infosys 10000

Shyam Park street Kolkata Wipro 20000

Hari Nehru street Hyderabad TCS 50000

Ravi M.G. Street Delhi NULL NULL

16 | P a g e
DATABASE MANAGEMENT SYSTEM

b. Right outer join:

o Right outer join contains the set of tuples of all combinations in R and S
that are equal on their common attribute names.
o In right outer join, tuples in S have no matching tuples in R.
o It is denoted by ⟖.

Example: Using the above EMPLOYEE table and FACT_WORKERS Relation

Input:
EMPLOYEE ⟖ FACT_WORKERS
Output:

EMP_NAME BRANCH SALARY STREET CITY

Ram Infosys 10000 Civil line Mumbai

Shyam Wipro 20000 Park street Kolkata

Hari TCS 50000 Nehru street Hyderabad

Kuber HCL 30000 NULL NULL

c. Full outer join:


o Full outer join is like a left or right join except that it contains all rows from
both tables.
o In full outer join, tuples in R that have no matching tuples in S and tuples
in S that have no matching tuples in R in their common attribute name.
o It is denoted by ⟗.

Example: Using the above EMPLOYEE table and FACT_WORKERS table

Input:

EMPLOYEE ⟗ FACT_WORKERS

17 | P a g e
DATABASE MANAGEMENT SYSTEM

Output:

EMP_NAME STREET CITY BRANCH SALARY

Ram Civil line Mumbai Infosys 10000

Shyam Park street Kolkata Wipro 20000

Hari Nehru street Hyderabad TCS 50000

Ravi M.G. Street Delhi NULL NULL

Kuber NULL NULL HCL 30000

3. Equi join:

It is also known as an inner join. It is the most common join. It is based on


matched data as per the equality condition. The equi join uses the comparison
operator(=).
Example:
CUSTOMER RELATION
CLASS_ID NAME

1 John

2 Harry

3 Jackson

PRODUCT
PRODUCT_ID CITY

1 Delhi

18 | P a g e
DATABASE MANAGEMENT SYSTEM

2 Mumbai

3 Noida

Input:
CUSTOMER ⋈ PRODUCT
Output:
CLASS_ID NAME PRODUCT_ID CITY

1 John 1 Delhi

2 Harry 2 Mumbai

3 Harry 3 Noida

Aggregate Functions
In database management an aggregate function is a function where the
values of multiple rows are grouped together as input on certain criteria to
form a single value of more significant meaning.

1) Count()
2) Sum()
3) Avg()
4) Min()
5) Max()
Now let us understand each Aggregate function with a example:
Id Name Salary
-----------------------
1 A 80
2 B 40
3 C 60
4 D 70
5 E 60
6 F Null
Count():

19 | P a g e
DATABASE MANAGEMENT SYSTEM

Count(*): Returns total number of records .i.e 6.


Count(salary): Return number of Non Null values over the column salary. i.e
5.
Count(Distinct Salary): Return number of distinct Non Null values over the
column salary .i.e 4

Sum():
sum(salary): Sum all Non Null values of Column salary i.e., 310
sum(Distinct salary): Sum of all distinct Non-Null values i.e., 250.

Avg():
Avg(salary) = Sum(salary) / count(salary) = 310/5
Avg(Distinct salary) = sum(Distinct salary) / Count(Distinct Salary) = 250/4

Min () and Max ():


Min (salary): Minimum value in the salary column except NULL i.e., 40.
Max (salary): Maximum value in the salary i.e., 80.

Grouping:

In SQL, The Group By statement is used for organizing similar data into groups.
The data is further organized with the help of equivalent function. It means, if
different rows in a precise column have the same values, it will arrange those
rows in a group.

o The SELECT statement is used with the GROUP BY clause in the SQL
query.
o WHERE clause is placed before the GROUP BY clause in SQL.
o ORDER BY clause is placed after the GROUP BY clause in SQL.

Syntax:

SELECT column1, function_name(column2)


FROM table_name
WHERE condition Syntax
GROUP BY column1, column2
ORDER BY column1, column2;
20 | P a g e
DATABASE MANAGEMENT SYSTEM

function_name: Table name.


Condition: which we used.

Employee

S.no Name AGE Salary

1 John 24 25000

2 Nick 22 22000

3 Amara 25 15000

4 Nick 22 22000

5 John 24 25000

Student

SUBJECT YEAR NAME

C language 2 John

C language 2 Ginny

C language 2 Jasmeen

C language 3 Nick

C language 3 Amara

Java 1 Sifa

Java 1 dolly

21 | P a g e
DATABASE MANAGEMENT SYSTEM

Group By single column: Group By single column is used to place all the rows
with the same value. These values are of that specified column in one group. It
signifies that all rows will put an equal amount through a single column, which
is of one appropriate column in one group.
SELECT NAME, SUM (SALARY) FROM Employee GROUP BY NAME;
NAME SALARY

John 50000

Nick 44000

Amara 15000

In the output, the rows which hold duplicate NAME are grouped under a similar
NAME, and their corresponding SALARY is the sum of the SALARY of the
duplicate rows.

Groups based on several columns: A group of some columns are GROUP


BY column 1, column2, etc. Here, we are placing all rows in a group with the
similar values of both column 1 and column 2.

SELECT SUBJECT, YEAR, Count (*) FROM Student Group BY SUBJECT, YEAR;

SUBJECT YEAR Count

C language 2 3

C language 3 2

Java 1 2

In the above output, the student with similar SUBJECT and YEAR are grouped in
the same place. The students who have only one thing in common belongs to
different groups. For example, if the NAME is same and the YEAR is different.

Now, we have to group the table according to more than one column or two
columns.

HAVING Clause
22 | P a g e
DATABASE MANAGEMENT SYSTEM

WHERE clause is used for deciding purpose. It is used to place conditions on the
columns to determine the part of the last result-set of the group. Here, we are
not required to use the combined functions like COUNT (), SUM (), etc. with
the WHERE clause. After that, we need to use a HAVING clause.

SELECT column1, function_name(column2)


FROM table_name
WHERE condition Syntax
GROUP BY column1, column2
HAVING condition
ORDER BY column1, column2;

function_name: Mainly used for name of the function, SUM(), AVG().


table_name: Used for name of the table.
condition: Condition used.
SELECT NAME, SUM(SALARY) FROM EmployeeGROUP BY NAME HAVING SUM
(SALARY)>23000;

Name SUM(SALARY)

John 50000

According to the above output, only one name in the NAME column has been
listed in the result because there is only one data in the database whose sum of
salary is more than 50000.
It should be placed on groups, not on the columns.
Points:
o The GROUP BY Clause is used to group the rows, which have the same
values.
o The SELECT statement in SQL is used with the GROUP BY clause.
o In the Group BY clause, the SELECT statement can
use constants, aggregate functions, expressions, and column names.
o The GROUP BY Clause is called when the HAVING clause is used to reduce
the results.

Nested Sub-Queries – Views


A nested query is a query that has another query embedded within it. The
embedded query is called a subquery.

23 | P a g e
DATABASE MANAGEMENT SYSTEM

A subquery typically appears within the WHERE clause of a query. It can


sometimes appear in the FROM clause or HAVING clause.
Example
Let’s learn about nested queries with the help of an example.
Find the names of employee who have regno=103
The query is as follows –
Student Relation:
Id Name classID Marks

1 Pinky 3 2.4

2 Bob 3 1.44

3 Jam 1 3.24

4 Lucky 2 2.67

5 Ram 2 4.56

Teacher Relation:
Id Name Subject classID Salary

1 Bhanu Computer 3 5000

2 Rekha Science 1 5000

3 Siri Social NULL 4500

4 Kittu Maths 2 5500

Class Relation:
Id Grade teacherID No.ofstudents

1 8 2 20

2 9 3 40

3 10 1 38

Select AVG(noofstudents) from class where teacherID IN(


Select id from teacher
Where subject=’science’ OR subject=’maths’);

24 | P a g e
DATABASE MANAGEMENT SYSTEM

Output: 20.0

VIEWS:
o Views in SQL are considered as a virtual table. A view also contains rows
and columns.
o To create the view, we can select the fields from one or more tables
present in the database.
o A view can either have specific rows based on certain condition or all the
rows of a table.

Student_Detail

STU_ID NAME ADDRESS

1 Stephan Delhi

2 Kathrin Noida

3 David Ghaziabad

4 Alina Gurugram

Student_Marks

STU_ID NAME MARKS AGE

1 Stephan 97 19

2 Kathrin 86 21

3 David 74 18

4 Alina 90 20

5 John 96 18

Creating view

A view can be created using the CREATE VIEW statement. We can create a view
from a single table or multiple tables.

CREATE VIEW view_name AS


SELECT column1, column2.....
25 | P a g e
DATABASE MANAGEMENT SYSTEM

FROM table_name
WHERE condition;

Introduction to PL/SQL

PL/SQL is a block structured language. The programs of PL/SQL are logical


blocks that can contain any number of nested sub-blocks. PL/SQL stands for
"Procedural Language extension of SQL" that is used in Oracle. PL/SQL is
integrated with Oracle database (since version 7). The functionalities of PL/SQL
usually extended after each release of Oracle database. Although PL/SQL is
closely integrated with SQL language, yet it adds some programming constraints
that are not available in SQL.

PL/SQL is not case sensitive so you are free to use lower case letters or upper
case letters except within string and character literals. A line of PL/SQL text
contains groups of characters known as lexical units. It can be classified as
follows:

o Delimeters
o Identifiers
o Literals
o Comments

Prerequisite
Before learning PL/SQL, you must have the basic knowledge of SQL and
programming language like C.
Audience
Our PL/SQL tutorial is designed to help beginners and professionals.

26 | P a g e
DATABASE MANAGEMENT SYSTEM

27 | P a g e

You might also like