Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

RELATION

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 14

DBMS

UNIT -3
RELATIONAL MODEL

The relational model in DBMS is an abstract model used to organize and


manage the data stored in a database. It stores data in two-dimensional
inter-related tables, also known as relations in which each row represents
an entity and each column represents the properties of the entity.

The relational model for database management is an approach to logically


represent and manage the data stored in a database. In this model, the
data is organized into a collection of two-dimensional inter-related
tables, also known as relations. Each relation is a collection of columns
and rows, where the column represents the attributes of an entity and the
rows (or tuples) represents the records.

As we can notice from the above relation:


Any given row of the relation indicates a student i.e., the row of the table
describes a real-world entity.
The columns of the table indicate the attributes related to the entity. In
this case, the roll number, CGPA, and the name of the student.

Dr. Vidya Pawar, Vedanta Degree College


1
DBMS

Relational Model Concepts


As discussed earlier, a relational database is based on the relational
model. This database consists of various components based on the
relational model. These include:
Relation : Two-dimensional table used to store a collection of data
elements.
Tuple : Row of the relation, depicting a real-world entity.
Attribute/Field : Column of the relation, depicting properties that define
the relation.
Attribute Domain : Set of pre-defined atomic values that an attribute
can take i.e., it describes the legal values that an attribute can take.
Degree : It is the total number of attributes present in the relation.
Cardinality : It specifies the number of entities involved in the relation
i.e., it is the total number of rows present in the relation. Read more
about Cardinality in DBMS.

Relational Schema : It is the logical blueprint of the relation i.e., it


describes the design and the structure of the relation. It contains the table
name, its attributes, and their types:
TABLE_NAME(ATTRIBUTE_1 TYPE_1, ATTRIBUTE_2 TYPE_2, ...)
TABLE_NAME(ATTRIBUTE_1 TYPE_1, ATTRIBUTE_2 TYPE_2, ...)

For our Student relation example, the relational schema will be:
STUDENT(ROLL_NUMBER INTEGER, NAME VARCHAR(20), CGPA FLOAT)

Relational Instance : It is the collection of records present in the


relation at a given time.

Relation Key : It is an attribute or a group of attributes that can be used


to uniquely identify an entity in a table or to determine the relationship
between two tables.

Relation keys can be of 6 different types:


Candidate Key
Super Key
Composite Key
Primary Key
Alternate Key
Foreign Key
A foreign key is a column or group of columns in a relational database
table that provides a link between data in two tables. It acts as a cross-

Dr. Vidya Pawar, Vedanta Degree College


2
DBMS

reference between tables because it references the primary key of


another table, thereby establishing a link between them

Primary key is a column of a table or a set of columns that helps to


identify every record present in that table uniquely
A primary key has the following properties
A primary key column must contain unique values
Null values not allowed for the primary key column
Only one primary key is allowed for a table.

A candidate key is one attribute used to identify each table record


uniquely. The Candidate key is a key which has only one non-null value in
every candidate key list
A super key is a subset of the candidate keys present in a table. The
Super Key is a composite, a combination of more than one attribute.
For example, the customer-id attribute of the entity set customer is
sufficient to distinguish one customer entity from another. Thus,customer-
id is a superkey

EMPLOYEE table, for(EMPLOEE_ID, EMPLOYEE_NAME), the name of two


employees can be the same, but their EMPLYEE_ID can't be the same.
Hence, this combination can also be a key. The super key would be
EMPLOYEE-ID (EMPLOYEE_ID, EMPLOYEE-NAME), etc.
Dr. Vidya Pawar, Vedanta Degree College
3
DBMS

Characteristics of the Relational Model


Data is represented in rows and columns called relations.
Data is stored in tables having relationships between them called the
Relational model.
The relational model supports the operations like Data definition, Data
manipulation, and Transaction management.
Each column has a distinct name and they are representing attributes.
Each row represents a single entity.

Database Constraints can be categorized into 3 main categories:


Constraints that are applied in the data model are called Implicit
Constraints.
Constraints that are directly applied in the schemas of the data model,
by specifying them in the DDL(Data Definition Language) . These are
called Schema-Based Constraints or Explicit Constraints.
Constraints that cannot be directly applied in the schemas of the data
model. We call these Application-based or Semantic Constraints.

Relational Constraints
These are the restrictions or sets of rules imposed on the database
contents. It validates the quality of the database. It validates the various
operations like data insertion, updation, and other processes that have to
be performed without affecting the integrity of the data. It protects us
against threats/damages to the database.

Mainly Constraints on the relational database are of 4 types


Domain constraints
Key constraints or Uniqueness Constraints
Entity Integrity constraints
Referential integrity constraints

Dr. Vidya Pawar, Vedanta Degree College


4
DBMS

1. Domain Constraints
Every domain must contain atomic values(smallest indivisible units)
which means composite and multi-valued attributes are not allowed.
We perform a datatype check here, which means when we assign a data
type to a column we limit the values that it can contain. Eg. If we assign
the datatype of attribute age as int, we can’t give it values other than int
datatype.
Example:
EID Name Phone

123456789
01 Bikash Dutta
234456678

Explanation: In the above relation, Name is a composite attribute and


Phone is a multi-values attribute, so it is violating domain constraint.

2. Key Constraints or Uniqueness Constraints


These are called uniqueness constraints since it ensures that every tuple
in the relation should be unique.
A relation can have multiple keys or candidate keys(minimal superkey),
out of which we choose one of the keys as the primary key, we don’t
have any restriction on choosing the primary key out of candidate keys,
but it is suggested to go with the candidate key with less number of
attributes.
Null values are not allowed in the primary key, hence Not Null constraint
is also part of the key constraint.

Example:

Dr. Vidya Pawar, Vedanta Degree College


5
DBMS

EID Name Phone

01 Bikash 6000000009

02 Paul 9000090009

01 Tuhin 9234567892

Explanation: In the above table, EID is the primary key, and the first
and the last tuple have the same value in EID ie 01, so it is violating the
key constraint.

3. Entity Integrity Constraints


Entity Integrity constraints say that no primary key can take a NULL
value, since using the primary key we identify each tuple uniquely in a
relation.
Example:
EID Name Phone

01 Bikash 9000900099

02 Paul 600000009

NULL Sony 9234567892

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

4. Referential Integrity Constraints


The Referential integrity constraint is specified between two relations or
tables and used to maintain the consistency among the tuples in two
relations.
This constraint is enforced through a foreign key, when an attribute in
the foreign key of relation R1 has the same domain(s) as the primary key
of relation R2, then the foreign key of R1 is said to reference or refer to
the primary key of relation R2.

Dr. Vidya Pawar, Vedanta Degree College


6
DBMS

The values of the foreign key in a tuple of relation R1 can either take the
values of the primary key for some tuple in relation R2, or can take NULL
values, but can’t be empty.
Example:
EID Name DNO

01 Divine 12

2 Dino 22

04 Vivian 14

DNO Place

12 Jaipur

13 Mumbai

14 Delhi

Explanation: In the above tables, the DNO of Table 1 is the foreign key,
and DNO in Table 2 is the primary key. DNO = 22 in the foreign key of
Table 1 is not allowed because DNO = 22 is not defined in the primary
key of table 2. Therefore, Referential integrity constraints are violated
here.

Relational Algebra in DBMS


Relational algebra refers to a procedural query language that takes
relation instances as input and returns relation instances as output. It
performs queries with the help of operators. A binary or unary operator
can be used
Relational Algebra Operations

The following are the fundamental operations present in a


relational algebra:
Select Operation
Project Operation

Dr. Vidya Pawar, Vedanta Degree College


7
DBMS

Union Operation
Set Different Operation
Cartesian Product Operation
Rename Operation

Select Operation (or σ)


It selects tuples from a relation that satisfy the provided predicate.
The notation is − σp(r)
Here σ stands for the selection predicate while r stands for the
relation. p refers to the prepositional logic formula that may use
connectors such as or, and, and not. Also, these terms may make use of
relational operators such as − =, ≠, ≥, < , >, ≤.
Example
σsubject = “information”(Novels)
The output would be − Selecting tuples from the novels wherever the
subject happens to be ‘information’.
σsubject = “information” and cost = “150”(Novels)

Project Operation (or ∏)


It projects those column(s) that satisfy any given predicate.
Here B1, B2 , An refer to the attribute names of the relation r.
The notation is − ∏B1, B2, Bn (r)
Remember that duplicate rows are eliminated automatically, since
relation is a set.
Example
∏subject, writer (Novels)
The output would be − Selecting and projecting columns named as
writer as well as the subject from the relation Novels.

Union Operation (or ∪)


It would perform binary union between two relations.
The notation is − r U s
Set Different Operation (or −)
Tuples refers to the result of the set difference operation. These are
present in just one of the relations but not at all in the second one.
The notation is − r − s

Set Theory Operations in Relational Algebra

Dr. Vidya Pawar, Vedanta Degree College


8
DBMS

Set Theory operations are the standard mathematical operations on


set. These operations are Binary operations that are, operated on 2
relations unlike PROJECT, SELECT and RENAME operations. These
operations are used to merge 2 sets in various ways.

The set operation is mainly categorized into the following:


Union operation
Intersection operation
Set difference or Minus operation

A∪S
UNION Operation: Notation:

operator. The result of Union operation, which is denoted by A ∪ S, is a


where, A and S are the relations, symbol ‘∪’ is used to denote the Union

relation that basically includes all the tuples that are present in A or in S,
or in both, eliminating the duplicate tuples.

INTERSECTION Operation:
Notations:
A∩S
where, A and S are the relations,
symbol ‘∩’ is used to denote the Intersection operator.
The result of Intersection operation, which is denoted by A ∩ S, is a
relation that basically includes all the tuples that are present in both A
an S.

3. MINUS (or SET DIFFERENCE) Operation:


Notations:
A-S
where, A and S are the relations,
symbol ‘ – ’ is used to denote the Minus operator.
The result of Intersection operation, which is denoted by A – S, is a
relation that basically includes all the tuples that are present in A but not
in S.

SQL Aggregate Functions


Here's a quick overview of the most common SQL aggregate functions:

Dr. Vidya Pawar, Vedanta Degree College


9
DBMS

PURPOS
FUNCTION EXAMPLE
E

Returns
SELECT
the
MIN(column)
MIN smallest
FROM
value in a
table_name
column.

Returns
SELECT
the
MAX(column)
MAX largest
FROM
value in a
table_name
column

Calculate
s the sum SELECT
of all SUM(column)
SUM
numeric FROM
values in table_name
a column

Returns
SELECT
the
AVG(column)
AVG average
FROM
value for
table_name
a column

Counts
the
SELECT
number
COUNT(colum COUNT(column
of non-
n) ) FROM
null
table_name
values in
a column

COUNT(*) Counts SELECT


the total COUNT(*)
number FROM
of rows table_name
(including

Dr. Vidya Pawar, Vedanta Degree College


10
DBMS

PURPOS
FUNCTION EXAMPLE
E

NULLs) in
a column

Nested Subqueries in SQL?


Nested subqueries in SQL, also known as inner queries or subselects,
are queries embedded within another query, usually in the form of an SQL
statement. A subquery returns a temporary table, which the outer main
SQL query then utilizes to further refine the results. Nested subqueries are
frequently used when you need to filter or manipulate data from multiple
tables and when the outcome of one query is based on the results of
another.

Nested Subqueries in SQL explained


Subqueries can be used in various sections of an SQL statement, such as:
WHERE clause
FROM clause
SELECT clause

When a subquery is used in a WHERE clause, it is often to filter the


results based on a comparison to an expression or column value from the
main query

Example:SELECT product_name, priceFROM productsWHERE price >


(SELECT AVG(price) FROM products);
Subqueries within the FROM clause are used when filtering based on
columns from multiple tables. The subquery essentially generates a virtual
table that the main query can join to extract the needed data.

A subquery within a SELECT clause is usually used to perform


calculations where the final result is included in the main query's result
set. One common use case is calculating derived columns that depend on
the value of another column.
Subquery: A query enclosed within another SQL statement, referred to as
the outer or main query.

PL/SQL Introduction

Dr. Vidya Pawar, Vedanta Degree College


11
DBMS

L/SQL is a block structured language that enables developers to combine


the power of SQL with procedural statements.All the statements of a
block are passed to oracle engine all at once which increases processing
speed and decreases the traffic.

Basics of PL/SQL
•PL/SQL stands for Procedural Language extensions to the Structured
Query Language (SQL).
PL/SQL is a combination of SQL along with the procedural features of
programming languages.
Oracle uses a PL/SQL engine to processes the PL/SQL statements.
PL/SQL includes procedural language elements like conditions and loops.
It allows declaration of constants and variables, procedures and
functions, types and variable of those types and triggers.

Disadvantages of SQL:
SQL doesn’t provide the programmers with a technique of condition
checking, looping and branching.
SQL statements are passed to Oracle engine one at a time which
increases traffic and decreases speed.
SQL has no facility of error checking during manipulation of data.

Features of PL/SQL:
1. PL/SQL is basically a procedural language, which provides the
functionality of decision making, iteration and many more features of
procedural programming languages.
2. PL/SQL can execute a number of queries in one block using single
command.
3. One can create a PL/SQL unit such as procedures, functions, packages,
triggers, and types, which are stored in the database for reuse by
applications.
4. PL/SQL provides a feature to handle the exception which occurs in
PL/SQL block known as exception handling block.
5. Applications written in PL/SQL are portable to computer hardware or
operating system where Oracle is operational.
6. PL/SQL Offers extensive error checking

Structure of PL/SQL Block:


PL/SQL extends SQL by adding constructs found in procedural languages,
resulting in a structural language that is more powerful than SQL. The
basic unit in PL/SQL is a block. All PL/SQL programs are made up of

Dr. Vidya Pawar, Vedanta Degree College


12
DBMS

blocks, which can be nested within each other.

Typically, each block performs a logical action in the program. A block


has the following structure:
DECLARE
declaration statements;

BEGIN
executable statements

EXCEPTIONS
exception handling statements

END;
Declare section starts with DECLARE keyword in which variables,
constants, records as cursors can be declared which stores data
temporarily. It basically consists definition of PL/SQL identifiers. This part
of the code is optional.

Execution section starts with BEGIN and ends with END keyword.This is
a mandatory section and here the program logic is written to perform
any task like loops and conditional statements. It supports
all DML commands, DDL commands and SQL*PLUS built-in functions as
well.

Exception section starts with EXCEPTION keyword.This section is


optional which contains statements that are executed when a run-time
error occurs. Any exceptions can be handled in this section.

Dr. Vidya Pawar, Vedanta Degree College


13
DBMS

PL/SQL identifiers
There are several PL/SQL identifiers such as variables, constants,
procedures, cursors, triggers etc.
Variables: Like several other programming languages, variables in
PL/SQL must be declared prior to its use. They should have a valid name
and data type as well. Syntax for declaration of variables:
variable_name datatype [NOT NULL := value ];
Example to show how to declare variables in PL/SQL :
C

SQL> SET SERVEROUTPUT ON;

SQL> DECLARE
var1 INTEGER;
var2 REAL;
var3 varchar2(20) ;

BEGIN
null;
END;
/

Output:
PL/SQL procedure successfully completed.

***************************************************************************
**********

Dr. Vidya Pawar, Vedanta Degree College


14

You might also like