Rdbms Js Book
Rdbms Js Book
With
Lab Manual
2 Mark (Q & A)
5 Mark and 10 Mark
(Assessment Questions)
Sample Programs
ideas.
- Authors
ACKNOWLEDGEMENT
My Heartful Thanks to God who has given his blessings to
write this book on“The Art of RDBMS”.
My sincere thanks and gratitude to Dharmamurthi Rao
Bahadur Calavala Cunnan Chetty Hindu Charities, Trust members,
Secretary, Principal, and Director of DRBCCC Hindu College.
As Author, I (Mrs. V. Jayalakshmi) thank my husband Mr. S.
Sundar for his unwavering support and continuous encouragement
has helped me in writing this book.
My Sincere thanks to our Secretary Shri.Venkatesa perumal,
Principal Dr. G. Kalvikkarasi, Director Dr. N. RajendraNaidu, andour
HOD Dr. N. Venkataramanan of DRBCCC Hindu College for their
constant guidance.
I am proud of the work that accomplished together, and I am
grateful for the opportunity to have collaborated with my co-author
and friend Prof. R. Suresh who is talented and committed in the
work.
Special thanks to my friends, fellow colleagues and my
students for their constant support.
UNIT II
2.1. Relational Model 39
2.1.1. Properties of Relations 39
2.2. Codd's Rules 41
2.3. Relational Algebra 45
2.3.1. Types of Relational operation 46
2.4. Advantages of Relational Algebra 64
2.5. Integrity Constraints 65
2.5.1. Domain constraints 66
2.5.2. Entityintegrityconstraints 67
2.5.3. Referential Integrity Constraints 67
2.5.4. Key constraints 68
2.6. Relational Calculus 70
2.6.1. Types of Relational calculus 70
2.6.2 Tuple Relational Calculus (TRC) 70
2.6.3. Domain Relational Calculus (DRC) 72
2.7. Query By Example (QBE): 73
UNIT III
3.0 Relational Database(RDBMS) 78
3.1. The relational model 79
3.2. ACID properties and RDBMS 80
3.3. Database locking and concurrency 81
3.4. Brief History of RDBMS 81
3.4.1. What is Table/Relation? 82
3.4.2. What is a row or record? 83
3.4.3. What is a column/attribute? 84
3.4.5. What is data item/Cells? 85
3.4.6. Cardinality 87
3.4.7. Data Integrity 88
3.5. RDBMS Architecture 89
3.6. RDBMS Tools 91
3.7. Anomalies in DBMS 94
3.7.1. Types of an anomaly in the database 96
3.8. Redundancy in DBMS 98
3.9. Functional Dependency 103
3.9.1. Types of Functional dependency 106
3.10. Normalization 112
3.10.1. Types of Normal Forms 114
3.10.2. First Normal Form (1NF) 116
3.10.3. Second Normal Form (2NF) 119
3.10.4. Third Normal Form (3NF) 122
3.11. Transactions 133
3.12. Database Security 139
3.12.1. Why Database Security is Important? 140
3.12.2. Common Threats and Challenges 142
3.12.3. Best use of Database Security 145
3.12.4. Data protection tools and platforms 147
3.12.5. Computer Based Controls 149
3.12.6. Access Controls 150
UNIT IV
4.1. SQL 156
4.1.1. Why SQL 156
4.1.2. History of SQL 157
4.1.3. Process of SQL 158
4.1.4. SQL vs NO-SQL 160
4.1.5. Advantages of SQL 162
4.1.6. Disadvantages of SQL 163
4.1.7. Most Important SQL Commands and
164
Statements
4.2. SQL Data types 179
4.2.1. My SQL String Data types 180
4.2.2. My SQL Numeric Data types 181
4.2.3. My SQL Date and Time Data types 183
4.2.4. SQL Server String Data types 184
4.2.5. SQL Server Numeric Data types 185
4.2.6. SQL Server Date and Time Data types 186
4.2.7. SQL Server Other Data types 187
4.3. DDL Commands in SQL 188
4.3.1. Create Command 188
4.3.2. Drop Command 192
4.3.3. Alter Command 193
4.3.4. Truncate Command 194
4.3.5. Rename Command 195
4.4. DML Commands in SQL 197
4.4.1. Select Command 197
4.4.2. Insert Command 201
4.4.3. Update Command 202
4.4.4. Delete Command 205
4.5. SQL Join 207
4.5.1. Inner Join 209
4.5.2. Left Join 210
4.5.3. Right Join 212
4.5.4. Full Join 214
4.5.5. Natural Join 217
4.6. SQL Set Operations 219
4.6.1. Types of Set Operations 219
4.7. SQL Sub Queries 226
4.7.1. Sub Queries with Select Statement 227
4.7.2. Sub Queries with Insert Statement 229
4.7.3. Sub Queries with Update Statement 230
4.7.4. Sub Queries with Delete Statement 232
UNIT V
5.1. PL/SQL Introduction 235
5.1.1. Features and Advantages PL/SQL 235
5.2. Structure of PL/SQL 237
5.3. PL/SQL Variables 239
5.4. PL/SQL Constant 248
5.5. PL/SQL Literals 250
5.6. PL/SQL Operators 251
5.6.1. Arithmetic Operators 251
5.6.2. Relational Operators 252
5.6.3. Comparison Operators 253
5.6.4. Logical Operators 255
5.6.5. PL/SQL Operator Precedence 256
5.7. PL/SQL Control Statements 257
5.7.1. Conditional Statements 257
5.7.2. PL/SQL Case Statement 260
5.7.3. PL/SQL Looping Statements 262
5.7.4. Continue Statement 268
5.7.5. PL/SQL GOTO Statement 270
5.8. PL/SQL Procedure 273
5.9. PL/SQL Function 276
5.10. PL/SQL Cursor 282
5.11. PL/SQL Exception Handling 290
5.12. PL/SQL Trigger 300
Relational Database Management System
UNIT 1
1.1 Introduction to Database:
What is data?:
The terms ―data‖ and ―information‖ are used interchangeably.
However, there is a subtle difference between the two.
The term Data is defined as a raw and unstructured fact that needs to
be processed to make it meaningful. Data can be simple and
unstructured at the same time until it is structured. Usually data
contains facts, numbers, symbols, image, observations, perceptions,
characters, etc.
What is Information?
1
Relational Database Management System
What is Database?
2
Relational Database Management System
Data Updation: It is used for the insertion, modification, and
deletion of the actual data in the database.
Data Retrieval: It is used to retrieve the data from the database
which can be used by applications for various purposes.
User Administration: It is used for registering and monitoring
users, maintain data integrity, enforcing data security, dealing with
concurrency control, monitoring performance and recovering
information corrupted by unexpected failure.
Characteristics of DBMS
3
Relational Database Management System
1.3 Advantages of DBMS
4
Relational Database Management System
Complexity: Database system creates additional complexity and
requirements.
Higher impact of failure: Failure is highly impacted the database
because in most of the organization, all the data stored in a
single database and if the database is damaged due to electric
failure or database corruption then the data may be lost forever.
Fig.1.1.DB Types
5
Relational Database Management System
6
Relational Database Management System
Fig.1.2.Distributed DB
Homogeneous DDB: Those database systems which execute on the
same operating system and use the same application process and
carry the same hardware devices.
Heterogeneous DDB: Those database systems which execute on
different operating systems under different application procedures,
and carries different hardware devices.
7
Relational Database Management System
1.5.3. Relational Database
8
Relational Database Management System
transactions occur at the same time, one transaction effects
should not be visible to the other transactions in the database.
D means Durability: It ensures that once it completes the
operation and commits the data, data changes should remain
permanent.
Fig.1.3.NoSQL DB Types
9
Relational Database Management System
Key-value storage: It is the simplest type of database storage where
it stores every single item as a key (or attribute name) holding its
value, together.
Document-oriented Database: A type of database used to store
data as JSON-like document. It helps developers in storing data by
using the same document-model format as used in the application
code.
Graph Databases: It is used for storing vast amounts of data in a
graph-like structure. Most commonly, social networking websites
use the graph database.
Wide-column stores: It is similar to the data represented in
relational databases. Here, data is stored in large columns together,
instead of storing in rows.
10
Relational Database Management System
1.5.5. Cloud Database
The type of database that uses the object-based data model approach
for storing data in the database system. The data is represented and
stored as objects which are similar to the objects used in the object-
oriented programming language.
11
Relational Database Management System
1.5.7. Hierarchical Databases
Fig1.4.Hierarchial DB
Data get stored in the form of records that are connected via links.
Each child record in the tree will contain only one parent. On the
other hand, each parent record can have multiple child records.
It is the database that typically follows the network data model. Here,
the representation of data is in the form of nodes connected via links
between them. Unlike the hierarchical database, it allows each
record to have multiple children and parent nodes to form a
generalized graph structure.
12
Relational Database Management System
13
Relational Database Management System
Fig1.5.DBMS Architectures
1-Tier Architecture
14
Relational Database Management System
2-Tier Architecture
15
Relational Database Management System
application on the client side establishes a connection with the server
side in order to communicate with the DBMS.
16
Relational Database Management System
Easy Deployment: 2-Tier Architecture is easy to deploy than 3-
Tier Architecture.
Simple: 2-Tier Architecture is easily understandable as well as
simple because of only two components.
3-Tier Architecture
17
Relational Database Management System
18
Relational Database Management System
Disadvantages of 3-Tier Architecture:
More Complex: 3-Tier Architecture is more complex in
comparison to 2-Tier Architecture. Communication Points are
also doubled in 3-Tier Architecture.
Difficult to Interact: It becomes difficult for this sort of
interaction to take place due to the presence of middle layers.
19
Relational Database Management System
1.7.1. Why Use ER Diagrams In DBMS?
ER diagrams are used to represent the E-R model in a database,
which makes them easy to be converted into relations (tables).
ER diagrams provide the purpose of real-world modeling of
objects which makes them intently useful.
ER diagrams require no technical knowledge and no hardware
support.
These diagrams are very easy to understand and easy to create
even for a naive user.
It gives a standard solution for visualizing the data logically.
20
Relational Database Management System
Fig.1.6.Symbols in ER Diagram
21
Relational Database Management System
A). Entity:
Fig.1.8a.Entity
Fig.1.8b.Weak Entity
For example, id, age, contact number, name, etc. can be attributes of
a student.
22
Relational Database Management System
Fig.1.8c.Attribute
Fig.1.8d.Key Attribute
23
Relational Database Management System
For example, a student can have more than one phone number.
Fig.1.8f.Multivalued Atribute
For example, A person's age changes over time and can be derived
from another attribute like Date of birth.
24
Relational Database Management System
Fig.1.8g.Derived Attribute
C). Relationship
Fig.1.9.Relationship
For example, A female can marry to one male, and a male can marry
to one female.
25
Relational Database Management System
Fig1.9.1.One-one Relationship
For example, Scientist can invent many inventions, but the invention
is done by the only specific scientist.
For example, Student enrolls for only one course, but a course can
have many students.
26
Relational Database Management System
Fig.1.9.3.Many to one Relationship
For example, Employee can assign by many projects and project can
have many employees.
There are various points for the conversion of the ER diagram to the
table:
27
Relational Database Management System
Every attribute of a single value converts into a column for the
table
In the entity of the STUDENT, the STUDENT _ID and
STUDENT_NAME form the columns of the table of the
STUDENT.
In the same way, COURSE_ID and COURSE_NAME structure
the columns of the COURSE table and so on.
28
Relational Database Management System
Fig.1.10.Multivalued Variable
29
Relational Database Management System
The derived attributes are not included in the table
By applying these rules, you can easily assign mapping in the tables
and change the ER diagram to columns and tables.
30
Relational Database Management System
1.7.5. Degree of a relationship :
This is used to demonstrate the number of entities which are a part of
the given relationship. Degree 2 is called binary relationship and it
means that 2 entities are participating in the relationship. It is the
most commonly used relationship.
Types of Cardinality:
One-to-one (1:1)
31
Relational Database Management System
One-to-many (1: N)
Many-to-one (N:1)
Many-to-many (N: N)
Fig.1.12.Types of Cardinality
One-to-one (1:1) – When one entity in each entity set takes part at
most once in the relationship, the cardinality is one-to-one.
One-to-many (1: N) – If entities in the first entity set take part in the
relationship set at most once and entities in the second entity set take
32
Relational Database Management System
part many times (at least twice), the cardinality is said to be one-to-
many.
Many-to-one (N:1) – If entities in the first entity set take part in the
relationship set many times (at least twice), while entities in the
second entity set take part at most once, the cardinality is said to be
many-to-one.
Fig1.13.Participation Constrains
33
Relational Database Management System
Participation. However, when all entities in the given entity set do
not participate in a relation, it is called Partial
Participation. Structural Constraints : Structural Constraints are also
called Structural properties of a database management system
(DBMS). Cardinality Ratios and Participation Constraints taken
together are called Structural Constraints. The name constraints refer
to the fact that such limitations must be imposed on the data, for the
DBMS system to be consistent with the requirements. The Structural
constraints are represented by Min-Max notation. This is a pair of
numbers(m, n) that appear on the connecting line between the entities
and their relationships.
34
Relational Database Management System
1.8 Aggregation in DBMS:
35
Relational Database Management System
It ensures all the entities in the database management system are
utilized according to their full potential.
The data aggregation can be done according to date that let the
characteristics display over a period of months, years, etc. Check out
the major kinds of data aggregation in detail below:
Sum: This tool is used for combining the various specified data
for creating a total value.
Average: The average value of the particular data is fully
computed by this command.
Max: It is used for showing the highest value for every category
in the database management system.
Min: It is used for providing the lowest value for every category
in the database management system.
Count: The total number of data entries is counted for all the
categories available in the database management system.
1. In-Network Aggregation
It is a general procedure where the information is gathered and
routed using a multi-hop network. This impressive technique is the
cornerstone of the database management system.
36
Relational Database Management System
2. Tree-Based Approach
The Aggregation from developing an aggregation tree is defined with
the help of a tree-based approach. It is a very important technique for
performing database management procedures brilliantly.
3. Multi-Path Approach
The partially aggregated data is transferred to a particular parent
mode during the multi-path approach. All the nodes are sent to many
different inputs in this type of Aggregation.
4. Cluster-Based Approach
This technique is utilized for collating a great sort of data on the
complete network. The cluster-based approach is equipped with a
cluster head chosen from various cluster members.
Examples of Aggregation:
37
Relational Database Management System
MIN() – returns the minimum value in a set
SUM() – returns the sum of all or distinct values in a set
Questions
2 Mark Questions:
1. Define Database.
2. What is DBMS?
3. Write a short note on RDBMS.
4. Define cardinality.
5. Define relationship.
6. What is aggregation?
7. Define E-R diagram.
8. What is entity?
9. Write a note on Attributes.
10. Define constraints.
38
Relational Database Management System
UNIT II
2.1. Relational Model
Relational key: In the relational key, each row has one or more
attributes. It can identify the row in the relation uniquely.
Constraints
39
Relational Database Management System
Key constraints
Domain constraints
Referential integrity constraints
Key Constraints
Domain Constraints
40
Relational Database Management System
41
Relational Database Management System
has vast research knowledge on the Relational Model of database
Systems. Codd presents his 13 rules for a database to test the concept
of DBMS against his relational model, and if a database follows the
rule, it is called a true relational database (RDBMS). These 13
rules are popular in RDBMS, known as Codd's 12 rules.
42
Relational Database Management System
missing the data, no value in a cell, inappropriate information,
unknown data and the primary key should not be null.
43
Relational Database Management System
Rule 7: Relational Level Operation (High-Level Insert, Update
and delete) Rule
44
Relational Database Management System
A database must maintain integrity independence when inserting data
into table's cells using the SQL query language. All entered values
should not be changed or rely on any external factor or application to
maintain integrity. It is also helpful in making the database-
independent for each front-end application.
45
Relational 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.
I. Select Operation:
Notation: σ p(r)
Where:
46
Relational Database Management System
σ 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 =, ≠, ≥, <, >, ≤.
Input:
σ BRANCH_NAME="perryride" (LOAN)
Output:
47
Relational Database Management System
Perryride L-15 1500
Where
48
Relational Database Management System
Input:
Output:
NAME CITY
Jones Harrison
Smith Rye
Hays Harrison
Curry Rye
Johnson Brooklyn
Brooks Brooklyn
Notation: R ∪ S
49
Relational Database Management System
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
BORROW RELATION
CUSTOMER_NAME LOAN_NO
Jones L-17
Smith L-23
Hayes L-15
Jackson L-14
50
Relational Database Management System
Curry L-93
Smith L-11
Williams L-17
Input:
Output:
CUSTOMER_NAME
Johnson
Smith
Hayes
Turner
Jones
Lindsay
Jackson
Curry
Williams
Mayes
51
Relational Database Management System
Notation: R ∩ S
Input:
Output:
CUSTOMER_NAME
Smith
Jones
V. Set Difference:
52
Relational Database Management System
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
Input:
∏ CUSTOMER_NAME (BORROW) -
∏ CUSTOMER_NAME (DEPOSITOR)
Output:
CUSTOMER_NAME
Jackson
Hayes
Willians
Curry
53
Relational Database Management System
Notation: E X D
Example:
EMPLOYEE
1 Smith A
2 Harry C
3 John B
DEPARTMENT
DEPT_NO DEPT_NAME
A Marketing
B Sales
C Legal
Input:
EMPLOYEE X DEPARTMENT
54
Relational Database Management System
Output:
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
VII.Rename Operation:
55
Relational Database Management System
ρ(STUDENT1, STUDENT)
Example:
EMPLOYEE
EMP_CODE EMP_NAME
101 Stephan
102 Jack
103 Harry
SALARY
EMP_CODE SALARY
101 50000
102 30000
103 25000
56
Relational Database Management System
Result:
57
Relational Database Management System
Fig.2.2. Join Operations
1. Natural Join:
Example: Let's use the above EMPLOYEE table and SALARY table:
Input:
Output:
EMP_NAME SALARY
Stephan 50000
Jack 30000
Harry 25000
2. Outer Join:
58
Relational Database Management System
Example:
EMPLOYEE
FACT_WORKERS
Input:
(EMPLOYEE ⋈ FACT_WORKERS)
59
Relational Database Management System
Output:
60
Relational Database Management System
Input:
EMPLOYEE ⟕FACT_WORKERS
Input:
EMPLOYEE ⟖FACT_WORKERS
61
Relational Database Management System
Output:
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 ⟗.
Input:
62
Relational Database Management System
EMPLOYEE ⟗FACT_WORKERS
Output:
3. Equi join:
Example:
CUSTOMER RELATION
CLASS_ID NAME
1 John
63
Relational Database Management System
2 Harry
3 Jackson
PRODUCT
PRODUCT_ID CITY
1 Delhi
2 Mumbai
3 Noida
Input:
CUSTOMER ⋈ PRODUCT
Output:
1 John 1 Delhi
2 Harry 2 Mumbai
3 Harry 3 Noida
64
Relational Database Management System
Efficient execution: Relational algebra queries can be efficiently
executed using a variety of optimization techniques, including
indexing and query planning.
Formal foundation: Relational algebra provides a formal
foundation for the design and implementation of relational
databases and query languages.
Portable: Relational algebra queries can be easily translated and
executed on different database systems, as long as they support
the same set of operations.
Disadvantages:
65
Relational Database Management System
Integrity constraints are a set of rules. It is used to maintain the
quality of information.
Integrity constraints ensure that the data insertion, updating, and
other processes have to be performed in such a way that data
integrity is not affected.
Thus, integrity constraint is used to guard against accidental
damage to the database.
Example:
66
Relational Database Management System
Example:
67
Relational Database Management System
In the Referential integrity constraints, if a foreign key in Table
1 refers to the Primary Key of Table 2, then every value of the
Foreign Key in Table 1 must be null or be available in Table 2.
Example:
Example:
68
Relational Database Management System
69
Relational Database Management System
o Universal Quantifiers: The universal quantifier denoted by
∀ is read as for all which means that in a given set of tuples
exactly all tuples satisfy a given condition.
o Existential Quantifiers: The existential quantifier denoted
by ∃ is read as for all which means that in a given set of
tuples there is at least one occurrences whose value satisfy a
given condition.
Free and bound variables may be compared with global and local
variable of programming languages.
70
Relational Database Management System
It is a non-procedural query language which is based on finding a
number of tuple variables also known as range variable for which
predicate holds true. It describes the desired information without
giving a specific procedure for obtaining that information. The tuple
relational calculus is specified to select the tuples in a relation. In
TRC, filtering variable uses the tuples of a relation. The result of the
relation can have one or more tuples.
Notation:
Where
For example:
Output: This query selects the tuples from the AUTHOR relation. It
returns a tuple with 'name' from Author who has written an article o
n 'database'.
71
Relational Database Management System
TRC (tuple relation calculus) can be quantified. In TRC, we can use
Existential (∃ ) and Universal Quantifiers (∀ ).
For example:
Output: This query will yield the same result as the previous one.
Notation:
Where
For example:
Output: This query will yield the article, page, and subject from the
relational javatpoint, where the subject is a database.
72
Relational Database Management System
In the tuple relational calculus, you have use variables that have a
series of tuples in a relation. In the domain relational calculus, you
will also use variables, but in this case, the variables take their values
from domains of attributes rather than tuples of relations. A domain
relational calculus expression has the following general format:
It is to be noted that these queries are safe. The use domain relational
calculus is restricted to safe expressions; moreover, it is equivalent to
73
Relational Database Management System
the tuple relational calculus, which in turn is similar to the relational
algebra.
74
Relational Database Management System
A user writes queries by creating example tables. QBE uses domain
variables, as in the DRC, to create example tables. The domain of a
variable is determined by the column in which it appears, and
variable symbols are prefixed with underscore ( ) to distinguish them
from constants. Constants, including strings, appear unquoted, in
contrast to SQL. The fields that should appear in the answer are
specified by using the command P., which stands for print. The fields
containing this command are analogous to the target-list in the
SELECT clause of an SQL query.
75
Relational Database Management System
notation is like the SELECT * convention in SQL. It is equivalent to
placing a P. in every field:
Questions:
2 Mark Questions
1. Define relational model.
2. List down CODD‘s rule.
76
Relational Database Management System
3. Define keys.
4. What is integrity?
5. List down the types of integrity.
6. Define relational algebra.
7. What is mean by relational calculus?
8. Define QBE.
77
Relational Database Management System
UNIT III
3. The Relational Database (RDBMS)
These two tables have only one thing in common: the ID column (the
key). But because of that common column, the relational database
78
Relational Database Management System
can create a relationship between the two tables. Then, when the
company‘s order processing application submits an order to the
database, the database can go to the customer order table, pull the
correct information about the product order, and use the customer ID
from that table to look up the customer‘s billing and shipping
information in the customer info table. The warehouse can then pull
the correct product, the customer can receive timely delivery of the
order, and the company can get paid.
79
Relational Database Management System
80
Relational Database Management System
3.3. Database locking and concurrency
81
Relational Database Management System
Following are the various terminologies of RDBMS:
Properties of a Relation:
82
Relational Database Management System
o Relation does not contain duplicate tuples.
o The tuples of a relation have no specific order.
o All attributes in a relation are atomic, i.e., each cell of a
relation contains exactly one value.
1 Ajeet 24 B.Tech
2 aryan 20 C.A
3 Mahesh 21 BCA
4 Ratan 22 MCA
5 Vimal 26 BSC
83
Relational Database Management System
Properties of a row:
1 Ajeet 24 B.Tech
Properties of an Attribute:
84
Relational Database Management System
o Default values can be specified for an attribute automatically
inserted if no other value is specified for an attribute.
o Attributes that uniquely identify each tuple of a relation are
the primary key.
Name
Ajeet
Aryan
Mahesh
Ratan
Vimal
The smallest unit of data in the table is the individual data item. It is
stored at the intersection of tuples and attributes.
85
Relational Database Management System
In the below example, the data item in the student table consists of
Ajeet, 24 and Btech, etc.
1 Ajeet 24 B.Tech
Degree:
For example, the student table has 4 attributes, and its degree is
4.
1 Ajeet 24 B.Tech
2 aryan 20 C.A
3 Mahesh 21 BCA
4 Ratan 22 MCA
5 Vimal 26 BSC
86
Relational Database Management System
3.4.6. Cardinality:
For example, the student table has 5 rows, and its cardinality is 5.
1 Ajeet 24 B.Tech
2 aryan 20 C.A
3 Mahesh 21 BCA
4 Ratan 22 MCA
5 Vimal 26 BSC
Domain:
The domain refers to the possible values each attribute can contain. It
can be specified using standard data types such as integers, floating
numbers, etc. For example, An attribute entitled Marital_Status may
be limited to married or unmarried values.
87
Relational Database Management System
NULL Values
The NULL value of the table specifies that the field has been left
blank during record creation. It is different from the value filled with
zero or a field that contains space
There are the following categories of data integrity exist with each
RDBMS:
88
Relational Database Management System
3.5. RDBMS Architecture
Fig.3.2.RDBMS Architecture
1) All data, data about data (metadata) and logs are stored in the
Secondary Storage devices (SSD), such as Disks and Tapes.The
programs that are used to do the day-to-day tasks of an
enterprise are called Application programs. These programs
provide the functionality for the day-to-day operations of the
enterprise. They are written in high level languages (HLL) like
Java, C etc, which along with the SQL, are used to communicate
with the databases.
2) RDBMS has a compiler that converts the SQL commands to
lower level language, processes it and stores it into the
secondary storage device.
89
Relational Database Management System
3) It is the job of Database Administrator (DBA) to set up the
structure of the database using command processor. The DDL
stands for Data Definition Language and is used by the DBA to
create or drop tables, add columns etc. The DBA also uses other
commands which are used to set constraints and access controls.
4) Application Programmers compile the applications using a
compiler and create executable files (compiled application
programs) and then store the data on the secondary storage
device.
5) Job of Data Analyst is to use the Query Compiler and Query
Optimizer (uses relational properties for executing queries) to
manipulate the data in the database.
6) RDBMS Run Time System executes the compiled queries and
application programs and also interacts with the transaction
manager and buffer manager.
7) Buffer Manager temporarily stores the data of the database in the
main memory and uses paging algorithm so that operations can
be performed faster and the disk space can be managed.
8) Transaction Manager deals with the principle of either
completely doing a task or not doing it at all (Atomicity
property). E.g. Suppose a person named Geeks, wants to send
money to his sister. He sends the money and system crashes in
between. In no case should it happen that he has sent money but
his sister has not received it. This is handled by the transaction
90
Relational Database Management System
manager. The transaction manager would either refund the
money to Geeks or transfer it to his sister.
9) Log is a system, which records the information about all the
transactions, so that whenever a system failure (disk failure,
system shut down due to no power etc.) arises, the partial
transactions can be undone.
10) Recovery Manager takes control of the system so that it reaches
a steady state after failure. The Recovery Manager takes into
account the log files and undoes the partial transactions and
reflects the complete transaction in the database.
What are our data accuracy requirements? Will data storage and
accuracy rely on business logic? Does our data have stringent
91
Relational Database Management System
requirements for accuracy (for example, financial data and
government reports)?
Do we need scalability? What is the scale of the data to be
managed, and what is its anticipated growth? Will the database
model need to support mirrored database copies (as separate
instances) for scalability? If so, can it maintain data consistency
across those instances?
How important is concurrency? Will multiple users and
applications need simultaneous data access? Does the database
software support concurrency while protecting the data?
What are our performance and reliability needs? Do we need a
high-performance, high-reliability product? What are the
requirements for query-response performance? What are the
vendor‘s commitments for service level agreements (SLAs) or
unplanned downtime?
92
Relational Database Management System
administrators to streamline tasks such as data modeling, schema
design, querying, data manipulation, and database maintenance.
There are various RDBMS tools available, and their selection often
depends on the specific needs and preferences of the users. Some
popular RDBMS tools include:
93
Relational Database Management System
6. Toad for Oracle: A popular tool for Oracle database
development and administration. It provides features for
coding, debugging, and performance tuning.
7. SQLiteStudio: A cross-platform SQLite database manager
that allows you to create, modify, and manage SQLite
databases.
8. DBVisualizer: A universal database tool that supports
multiple database management systems, including Oracle,
MySQL, PostgreSQL, and more. It offers a single interface
for various databases.
9. Navicat: A database management and development tool that
supports a wide range of databases, including MySQL,
PostgreSQL, Oracle, and SQL Server.
10. SQLyog: A graphical MySQL management and development
tool for database administrators and developers.
What is Anomaly?
94
Relational Database Management System
There can be various reasons for anomalies to occur in the database.
For example, if there is a lot of redundant data present in our
database then DBMS anomalies can occur. If a table is constructed in
a very poor manner then there is a chance of database anomaly. Due
to database anomalies, the integrity of the database suffers.
The other reason for the database anomalies is that all the data is
stored in a single table. So, to remove the anomalies of the database,
normalization is the process which is done where the splitting of the
table and joining of the table (different types of join) occurs.
Example 1:
95
Relational Database Management System
In the above table, we have four columns which describe the details
about the workers like their name, address, department and their id.
The above table is not normalized, and there is definitely a chance of
96
Relational Database Management System
C). Deletion Anomaly
If we delete some rows from the table and if any other information or
data which is required is also deleted from the database, this is called
the deletion anomaly in the database. For example, in the above table,
if we want to delete the department number ECT669 then the details
of Rajesh will also be deleted since Rajesh's details are dependent on
the row of ECT669. So, there will be deletion anomalies in the table.
To remove this type of anomalies, we will normalize the table or split
the table or join the tables. There can be various normalized forms of
a table like 1NF, 2NF, 3NF, BCNF etc. we will apply the different
normalization schemes according to the current form of the table.
Example 2:
In the above table, we have listed students with their name, id,
branch and their respective clubs.
97
Relational Database Management System
Updation / Update Anomaly
Insertion Anomaly
If we add a new row for student Ankit who is not a part of any club,
we cannot insert the row into the table as we cannot insert null in the
column of stu_club. This is called insertion anomaly.
Deletion Anomaly
98
Relational Database Management System
What is Data redundancy in the database management system?
99
Relational Database Management System
105 Amisha B. Tech 2022 90,000 CS
100
Relational Database Management System
1. Insertion Anomaly:
Insertion anomaly arises when you are trying to insert some data into
the database, but you are not able to insert it.
Example: If you want to add the details of the student in the above
table, then you must know the details of the department; otherwise,
you will not be able to add the details because student details are
dependent on department details.
2. Deletion Anomaly:
Deletion anomaly arises when you delete some data from the
database, but some unrelated data is also deleted; that is, there will be
a loss of data due to deletion anomaly.
3. Updating Anomaly:
101
Relational Database Management System
Example: If we want to update the details of dept_head from
Jaspreet Kaur to Ankit Goyal for Dept_id 104, then we have to
update it everywhere else; otherwise, the data will get partially
updated, which causes data inconsistency.
102
Relational Database Management System
How to reduce data redundancy in DBMS?
X → Y
103
Relational Database Management System
The left side of FD is known as a determinant, the right side of the
production is known as a dependent.
For example:
Emp_Id → Emp_Name
We can say that Emp_Name is functionally dependent on Emp_Id.
Example:
42 abc CO A4
43 pqr IT A3
44 xyz CO A4
45 xyz IT A3
104
Relational Database Management System
roll_no name dept_name dept_building
46 mno EC B2
47 jkl ME B2
105
Relational Database Management System
dept_building → dept_name There can be multiple
departments in the same building. Example, in the above table
departments ME and EC are in the same building B2, hence
dept_building → dept_name is an invalid functional
dependency.
More invalid functional dependencies: name → roll_no, {name,
dept_name} → roll_no, dept_building → roll_no, etc.
Armstrong’s axioms/properties of functional dependencies:
106
Relational Database Management System
Multivalued functional dependency
Transitive functional dependency
Example:
42 Abc 17
43 Pqr 18
44 xyz 18
107
Relational Database Management System
2. Non-trivial Functional Dependency
Example:
42 abc 17
43 pqr 18
44 xyz 18
108
Relational Database Management System
exists no functional dependency between b and c, then it is called
a multivalued functional dependency.
For example,
42 abc 17
43 pqr 18
44 xyz 18
45 abc 19
109
Relational Database Management System
For example,
42 abc CO 4
43 pqr EC 2
44 xyz IT 1
45 abc EC 2
110
Relational Database Management System
has attributes X, Y, Z where X and Y are the composite key and Z
is non key attribute. Then X->Z is a partial functional dependency
in RBDMS.
1. Data Normalization
2. Query Optimization
111
Relational Database Management System
3. Consistency of Data
3.10. Normalization
112
Relational Database Management System
The likelihood of errors and inconsistencies increases.
What is Normalization:
113
Relational Database Management System
3.10.1. Types of Normal Forms
Normal Description
Form
Advantages of Normalization
114
Relational Database Management System
Disadvantages of Normalization
You cannot start building the database before knowing what the
user needs.
The performance degrades when normalizing the relations to
higher normal forms, i.e., 4NF, 5NF.
It is very time-consuming and difficult to normalize relations of
a higher degree.
Careless decomposition may lead to a bad database design,
leading to serious problems.
115
Relational Database Management System
What is a Primary Key?
116
Relational Database Management System
A table is in 1 NF if:
Example-1:
Relation STUDENT in table 1 is not in 1NF because of multi-valued
attribute STUD_PHONE. Its decomposition into 1NF has been
shown in table 2.
117
Relational Database Management System
Example-2:
ID Name Courses
------------------
1 A c1, c2
2 E c3
3 M C2, c3
ID Name Course
------------------
1 A c1
1 A c2
2 E c3
3 M c2
3 M c3
118
Relational Database Management System
3.10.3. Second Normal Form (2NF)
First Normal Form (1NF) does not eliminate redundancy, but rather,
it‘s that it eliminates repeating groups. Instead of having multiple
columns of the same kind of data in a record, (0NF or Unnormalized
form) you remove the repeated information into a separate relation
and represent them as rows. This is what constitutes 1NF.
119
Relational Database Management System
relations to 2NF involves the removal of partial dependencies. If a
partial dependency exists, we remove the partially dependent
attribute(s) from the relation by placing them in a new relation along
with a copy of their determinant. Consider the examples given below.
Example-1: Consider table as following below.
120
Relational Database Management System
candidate key. Non-prime attribute COURSE_FEE is dependent on a
proper subset of the candidate key, which is a partial dependency and
so this relation is not in 2NF.
To convert the above relation to 2NF, we need to split the table into
two tables such as : Table 1: STUD_NO, COURSE_NO
Table 1 Table 2
STUD_NO COURSE_NO COURSE_NO COURSE_FEE
1 C1 C1 1000
2 C2 C2 1500
1 C4 C3 1000
4 C3 C4 2000
4 C1 C5 2000
2 C5
Note – 2NF tries to reduce the redundant data getting stored in
memory. For instance, if there are 100 students taking C1 course, we
dont need to store its Fee as 1000 for all the 100 records, instead
once we can store it in the second table as the course fee for C1 is
1000.
121
Relational Database Management System
AB ->C [A and B together determine C]
BC ->D [B and C together determine D]
In this case, we can see that the relation R has a composite candidate
key {A,B} as AB->C. Therefore, A and B together uniquely
determine the value of C. Similarly, BC -> D shows that B and C
together uniquely determine the value of D.
1. X is a super key.
2. Y is a prime attribute (each element of Y is part of some
candidate key).
122
Relational Database Management System
In other words,
Note – If A->B and B->C are two FDs then A->C is called transitive
dependency.
Example-1:
In relation STUDENT given in Table ,
FD set:
{STUD_NO -> STUD_NAME, STUD_NO -> STUD_STATE,
STUD_STATE -> STUD_COUNTRY, STUD_NO -> STUD_AGE}
123
Relational Database Management System
Candidate Key:
{STUD_NO}
Example-2:
Consider relation R(A, B, C, D, E)
A -> BC,
CD -> E,
B -> D,
E -> A
All possible candidate keys in above relation are {A, E, CD, BC} All
attribute are on right sides of all functional dependencies are prime.
124
Relational Database Management System
Note –
Third Normal Form (3NF) is considered adequate for normal
relational database design because most of the 3NF tables are free of
insertion, update, and deletion anomalies. Moreover, 3NF always
ensures functional dependency preserving and lossless.
125
Relational Database Management System
Rules for BCNF
Rule 1: The table should be in the 3rd Normal Form.
126
Relational Database Management System
deduced that the relation is also in 3NF, 2NF, and 1NF as the
hierarchy shows. The 1NF has the least restrictive constraint – it
only requires a relation R to have atomic values in each tuple. The
2NF has a slightly more restrictive constraint.
The 3NF has a more restrictive constraint than the first two normal
forms but is less restrictive than the BCNF. In this manner, the
restriction increases as we traverse down the hierarchy.
Examples
Here, we are going to discuss some basic examples which let you
understand the properties of BCNF. We will discuss multiple
examples here.
Example 1
127
Relational Database Management System
Stu_ID Stu_Branch Stu_Course Branch_Number Stu_Course_No
Electronics &
VLSI
102 Communication B_003 401
Technology
Engineering
Electronics &
Mobile
102 Communication B_003 402
Communication
Engineering
128
Relational Database Management System
How to Satisfy BCNF?
Stu_Branch Table
Stu_ID Stu_Branch
Stu_Course Table
129
Relational Database Management System
Stu_ID to Stu_Course_No Table
Stu_ID Stu_Course_No
101 201
101 202
102 401
102 402
Example 2
130
Relational Database Management System
Explanation:
131
Relational Database Management System
Note: A prime attribute cannot be transitively dependent on a key
in BCNF relation.
AB ->C
C ->B
AB ->B
Example 3
A -> BC,
B -> A
132
Relational Database Management System
Note: BCNF decomposition may always not be possible
with dependency preserving, however, it always satisfies
the lossless join condition. For example, relation R (V, W, X, Y, Z),
with functional dependencies:
V, W -> X
Y, Z -> X
W -> Y
There are also some higher-order normal forms, like the 4th Normal
Form and the 5th Normal Form.
3.11. Transactions
A’s Account
Open_Account(A)
Old_Balance = A.balance
133
Relational Database Management System
New_Balance = Old_Balance - 500
A.balance = New_Balance
Close_Account(A)
B’s Account
Open_Account(B)
Old_Balance = B.balance
New_Balance = Old_Balance + 500
B.balance = New_Balance
Close_Account(B)
ACID Properties
134
Relational Database Management System
Consistency − The database must remain in a consistent state after
any transaction. No transaction should have any adverse effect on the
data residing in the database. If the database was in a consistent state
before the execution of a transaction, it must remain consistent after
the execution of the transaction as well.
Serializability
135
Relational Database Management System
Schedule − A chronological execution sequence of a transaction
is called a schedule. A schedule can have many transactions in it,
each comprising of a number of instructions/tasks.
Serial Schedule − It is a schedule in which transactions are
aligned in such a way that one transaction is executed first.
When the first transaction completes its cycle, then the next
transaction is executed. Transactions are ordered one after the
other. This type of schedule is called a serial schedule, as
transactions are executed in a serial manner.
Equivalence Schedules
136
Relational Database Management System
Result Equivalence
If two schedules produce the same result after execution, they are
said to be result equivalent. They may yield the same result for some
value and different results for another set of values. That's why this
equivalence is not generally considered significant.
View Equivalence
For example −
If T reads the initial data in S1, then it also reads the initial data
in S2.
If T reads the value written by J in S1, then it also reads the
value written by J in S2.
If T performs the final write on the data value in S1, then it also
performs the final write on the data value in S2.
Conflict Equivalence
137
Relational Database Management System
Two schedules having multiple transactions with conflicting
operations are said to be conflict equivalent if and only if −
States of Transactions
138
Relational Database Management System
Failed − A transaction is said to be in a failed state if any of the
checks made by the database recovery system fails. A failed
transaction can no longer proceed further.
Aborted − If any of the checks fails and the transaction has
reached a failed state, then the recovery manager rolls back all
its write operations on the database to bring the database back to
its original state where it was prior to the execution of the
transaction. Transactions in this state are called aborted. The
database recovery module can select one of the two operations
after a transaction aborts −
Re-start the transaction
Kill the transaction
139
Relational Database Management System
Security for databases must cover and safeguard the following
aspects:
140
Relational Database Management System
Intellectual property that is compromised: Our intellectual
property--trade secrets, inventions, or proprietary methods --
could be vital for our ability to maintain an advantage in our
industry. If our intellectual property has been stolen or disclosed
and our competitive advantage is lost, it could be difficult to
keep or recover.
The damage to our brand's reputation: Customers or partners
may not want to purchase goods or services from us (or deal
with our business) If they do not feel they can trust our company
to protect their data or their own.
The concept of business continuity (or lack of it): Some
businesses cannot continue to function until a breach has been
resolved.
Penalties or fines to be paid for not complying: The cost of
not complying with international regulations like the Sarbanes-
Oxley Act (SAO) or Payment Card Industry Data Security
Standard (PCI DSS) specific to industry regulations on data
privacy, like HIPAA or regional privacy laws like the European
Union's General Data Protection Regulation (GDPR) could be a
major problem with fines in worst cases in excess of many
million dollars for each violation.
Costs for repairing breaches and notifying consumers about
them: Alongside notifying customers of a breach, the company
that has been breached is required to cover the investigation and
141
Relational Database Management System
forensic services such as crisis management, triage repairs to the
affected systems, and much more.
Insider Dangers
142
Relational Database Management System
Human Error
143
Relational Database Management System
The attackers may make use of the extra data, which is stored in
adjacent memory addresses, to establish a basis for they can begin
attacks.
Malware
Attacks on Backups
Companies that do not protect backup data using the same rigorous
controls employed to protect databases themselves are at risk of
cyberattacks on backups.
144
Relational Database Management System
Data volumes are growing: Data capture, storage, and
processing continue to increase exponentially in almost all
organizations. Any tools or methods must be highly flexible to
meet current as well as far-off needs.
The infrastructure is sprawling: Network environments are
becoming more complicated, especially as companies shift their
workloads into multiple clouds and hybrid cloud architectures
and make the selection of deployment, management, and
administration of security solutions more difficult.
More stringent requirements for regulatory compliance: The
worldwide regulatory compliance landscape continues to
increase by complexity. This makes the compliance of every
mandate more challenging.
145
Relational Database Management System
Security for physical security: If the database servers are on-
premises or the cloud data centre, they should be placed in a
secure, controlled climate. (If our server for database is located
in a cloud-based data centre, the cloud provider will handle the
security on our behalf.)
Access to the network and administrative restrictions: The
practical minimum number of users granted access to the
database and their access rights should be restricted to the
minimum level required to fulfil their tasks. Additionally, access
to the network is limited to the minimum permissions needed.
End security of the user account or device: Be aware of who
has access to the database and when and how data is used.
Monitoring tools for data can notify you of data-related activities
that are uncommon or seem to be dangerous. Any device that
connects to the network hosting the database must be physically
secured (in the sole control of the appropriate person) and be
subject to security checks throughout the day.
Security: ALL data--including data stored in databases, as well
as credential information should be secured using the highest-
quality encryption when in storage and while in transport. All
encryption keys must be used in accordance with the best
practices guidelines.
146
Relational Database Management System
Security of databases using software: Always use the most
current version of our software to manage databases and apply
any patches immediately after they're released.
Security for web server applications and websites: Any
application or web server that connects to the database could be
a target and should be subjected to periodic security testing and
best practices management.
Security of backups: All backups, images, or copies of the
database should have the identical (or equally rigorous) security
procedures as the database itself.
Auditing: Audits of security standards for databases should be
conducted every few months. Record all the logins on the server
as well as the operating system. Also, record any operations that
are made on sensitive data, too.
147
Relational Database Management System
recommendations to address any vulnerabilities that are
discovered.
Monitoring of Data Activity: The solution should be capable of
monitoring and analysing the entire data activity in all databases,
whether our application is on-premises, in the cloud, or inside a
container. It will alert us to suspicious activity in real-time to
allow us to respond more quickly to threats. It also provides
visibility into the state of our information through an integrated
and comprehensive user interface. It is also important to choose
a system that enforces rules that govern policies, procedures, and
the separation of duties. Be sure that the solution we select is
able to generate the reports we need to comply with the
regulations.
The ability to Tokenize and Encrypt Data: In case of an
incident, encryption is an additional line of protection against
any compromise. Any software we choose to use must have the
flexibility to protect data cloud, on-premises hybrid, or multi-
cloud environments. Find a tool with volume, file, and
application encryption features that meet our company's
regulations for compliance. This could require tokenization (data
concealing) or advanced key management of security keys.
Optimization of Data Security and Risk Analysis: An
application that will provide contextual insights through the
combination of security data with advanced analytics will allow
148
Relational Database Management System
users to perform optimizing, risk assessment, and reporting in a
breeze. Select a tool that is able to keep and combine large
amounts of recent and historical data about the security and state
of your databases. Also, choose a solution that provides data
exploration, auditing, and reporting capabilities via an extensive
but user-friendly self-service dashboard.
Access authorization.
Access controls.
Views.
Backup and recovery of data.
Data integrity.
Encryption of data.
RAID technology
149
Relational Database Management System
3.12.6. Access Controls
Database Access Control Systems work on three sides: the user, the
administrator, and the infrastructure.
150
Relational Database Management System
The System Infrastructure: An access control system‘s
infrastructure includes electric locks, card readers, door status
for traffic monitoring, and requests to exit devices, all of which
report to the control panel and the server.
1. DAC :
DAC is identity-based access control. DAC mechanisms will be
controlled by user identification such as username and password.
DAC is discretionary because the owners can transfer objects or any
authenticated information to other users. In simple words, the owner
can determine the access privileges.
Attributes of DAC –
2. MAC :
The operating system in MAC will provide access to the user based
on their identities and data. For gaining access, the user has to submit
their personal information. It is very secure because the rules and
151
Relational Database Management System
restrictions are imposed by the admin and will be strictly followed.
MAC settings and policy management will be established in a secure
network and are limited to system administrators.
Attributes of MAC –
DAC MAC
152
Relational Database Management System
153
Relational Database Management System
Questions:
2 Mark Questions
154
Relational Database Management System
9. Define transaction processing.
10. What is database security?
155
Relational Database Management System
UNIT IV
4.1 SQL
You can easily create and manipulate the database, access and
modify the table rows and columns, etc. This query language became
the standard of ANSI in the year of 1986 and ISO in the year of
1987.
If you want to get a job in the field of data science, then it is the most
important query language to learn. Big enterprises like Facebook,
Instagram, and LinkedIn, use SQL for storing the data in the back-
end.
156
Relational Database Management System
The basic use of SQL for data professionals and SQL
users is to insert, update, and delete the data from the
relational database.
"A Relational Model of Data for Large Shared Data Banks" was a
paper which was published by the great computer scientist "E.F.
Codd" in 1970.
157
Relational Database Management System
The IBM researchers Raymond Boyce and Donald Chamberlin
originally developed the SEQUEL (Structured English Query
Language) after learning from the paper given by E.F. Codd. They
both developed the SQL at the San Jose Research laboratory of IBM
Corporation in 1970.
At the end of the 1970s, relational software Inc. developed their own
first SQL using the concepts of E.F. Codd, Raymond Boyce, and
Donald Chamberlin. This SQL was totally based on RDBMS.
Relational Software Inc., which is now known as Oracle
Corporation, introduced the Oracle V2 in June 1979, which is the
first implementation of SQL language. This Oracle V2 version
operates on VAX computers.
o Query Dispatcher
o Optimization Engines
158
Relational Database Management System
o Classic Query Engine
o SQL Query Engine, etc.
159
Relational Database Management System
4.1.4 SQL vs No-SQL
SQL No-SQL
160
Relational Database Management System
in the form of tables, i.e., in the in the form of documents, key-
form of rows and columns. value, and graphs.
161
Relational Database Management System
4.1.5 Advantages of SQL
1. No programming needed
SQL does not require a large number of coding lines for managing
the database systems. We can easily access and maintain the database
by using simple SQL syntactical rules. These simple rules make the
SQL user-friendly.
3. Standardized Language
4. Portability
162
Relational Database Management System
5. Interactive language
We can easily learn and understand the SQL language. We can also
use this language for communicating with the database because it is a
simple query language. This language is also used for receiving the
answers to complex queries in a few seconds.
The SQL language also helps in making the multiple views of the
database structure for the different database users.
1. Cost
The operation cost of some SQL versions is high. That's why some
programmers cannot use the Structured Query Language.
2. Interface is Complex
163
Relational Database Management System
3. Partial Database control
The business rules are hidden. So, the data professionals and users
who are using this query language cannot have full database control.
1. Select Statement
2. Update Statement
3. Delete Statement
4. Create Table Statement
5. Alter Table Statement
6. Drop Table Statement
7. Create Database Statement
8. Drop Database Statement
9. Insert Into Statement
10. Truncate Table Statement
11. Describe Statement
12. Distinct Clause
13. Commit Statement
14. Rollback Statement
15. Create Index Statement
16. Drop Index Statement
164
Relational Database Management System
17. Use Statement
Let's discuss each statement in short one by one with syntax and
one example:
1. SELECT Statement
This SQL statement reads the data from the SQL database and shows
it as the output to the database user.
165
Relational Database Management System
shows all the specified details according to the ascending
alphabetical order of Last_Name.
2. UPDATE Statement
This SQL statement changes or modifies the stored data in the SQL
database.
UPDATE table_name
SET column_name1 = new_value_1, column_name2 = new_valu
e_2, ...., column_nameN = new_value_N
[ WHERE CONDITION ];
UPDATE Employee_details
SET Salary = 100000
WHERE Emp_ID = 10;
3. DELETE Statement
This SQL statement deletes the stored data from the SQL database.
166
Relational Database Management System
Syntax of DELETE Statement:
This SQL statement creates the new table in the SQL database.
167
Relational Database Management System
PRIMARY KEY(one or more col)
);
This SQL statement adds, deletes, and modifies the columns of the
table in the SQL database.
168
Relational Database Management System
Syntax of ALTER TABLE Statement:
The above SQL alter statement adds the column with its datatype in
the existing database table.
The above 'SQL alter statement' renames the old column name to the
new column name of the existing database table.
The above SQL alter statement deletes the column of the existing
database table.
This example adds the new field whose name is Designation with
size 18 in the Employee_details table of the SQL database.
169
Relational Database Management System
6. DROP TABLE Statement
This SQL statement deletes or removes the table and the structure,
views, permissions, and triggers associated with that table.
170
Relational Database Management System
Syntax of CREATE DATABASE Statement:
This SQL statement deletes the existing database with all the data
tables and views from the database management system.
The above example deletes the company database from the system.
171
Relational Database Management System
9. INSERT INTO Statement
This SQL statement inserts the data or records in the existing table of
the SQL database. This statement can easily insert single and
multiple records in a single query statement.
172
Relational Database Management System
Last_name,
Salary,
City
)
VALUES
(101,
Akhil,
Sharma,
40000,
Bangalore
);
This example inserts 101 in the first column, Akhil in the second
column, Sharma in the third column, 40000 in the fourth column,
and Bangalore in the last column of the table Employee_details.
173
Relational Database Management System
( Emp_ID, First_name, Last_name, Salary, City )
VALUES (101, Amit, Gupta, 50000, Mumbai), (101, John, Agg
arwal, 45000, Calcutta), (101, Sidhu, Arora, 55000, Mumbai);
This SQL statement deletes all the stored records from the table of
the SQL database.
This SQL statement tells something about the specified table or view
in the query.
174
Relational Database Management System
Syntax of DESCRIBE Statement:
DESCRIBE Employee_details;
This SQL statement shows the distinct values from the specified
columns of the database table. This statement is used with
the SELECT keyword.
175
Relational Database Management System
This example shows the distinct values of
the City and Salary column from the Employee_details table.
This SQL statement saves the changes permanently, which are done
in the transaction of the SQL database.
COMMIT
This SQL statement undo the transactions and operations which are
not yet saved to the SQL database.
176
Relational Database Management System
Syntax of ROLLBACK Statement:
ROLLBACK
This SQL statement creates the new index in the SQL database table.
177
Relational Database Management System
This example creates an index idx_First_Name on
the First_Name column of the Employee_details table.
This SQL statement deletes the existing index of the SQL database
table.
USE database_name;
178
Relational Database Management System
Example of USE DATABASE Statement:
USE Company;
Data types are used to represent the nature of the data that can be
stored in the database table. For example, in a particular column of a
table, if we want to store a string type of data then we will have to
declare a string data type of this column.
Data types mainly classified into three categories for every database.
179
Relational Database Management System
4.2.1 MySQL String Data Types
180
Relational Database Management System
MEDIUMTEXT It holds a string with a maximum length of
16,777,215.
181
Relational Database Management System
INT(size) It is used for the integer value. Its signed range
varies from -2147483648 to 2147483647 and
unsigned range varies from 0 to 4294967295.
The size parameter specifies the max display
width that is 255.
182
Relational Database Management System
DECIMAL(size, It is used to specify a fixed point number. Its size
d) parameter specifies the total number of digits.
The number of digits after the decimal parameter
is specified by d parameter. The maximum value
for the size is 65, and the default value is 10. The
maximum value for d is 30, and the default value
is 0.
183
Relational Database Management System
TIMESTAMP(fsp) It is used to specify the timestamp. Its value is
stored as the number of seconds since the
Unix epoch('1970-01-01 00:00:00' UTC). Its
format is YYYY-MM-DD hh:mm:ss. Its
supported range is from '1970-01-01 00:00:01'
UTC to '2038-01-09 03:14:07' UTC.
184
Relational Database Management System
text It is a variable width character string data type. Its
size can be up to 2GB of text data.
185
Relational Database Management System
Smallint It allows whole numbers between -32,768 and 32,767.
186
Relational Database Management System
datetime2 It is used to specify date and time combination. It
supports range from January 1, 0001 to December 31,
9999 with an accuracy of 100 nanoseconds
187
Relational Database Management System
uniqueidentifier It stores GUID (Globally unique identifier).
1. CREATE Command
2. DROP Command
3. ALTER Command
4. TRUNCATE Command
5. RENAME Command
188
Relational Database Management System
Examples of CREATE Command in SQL
189
Relational Database Management System
Suppose, you want to create a Student table with five columns in the
SQL database. To do this, you have to write the following DDL
command:
190
Relational Database Management System
101 Sushil 75 Jaipur Rajasthan
191
Relational Database Management System
4.3.2 DROP Command
Suppose, you want to delete the Books database from the SQL
database. To do this, you have to write the following DDL command:
Suppose, you want to delete the Student table from the SQL
database. To do this, you have to write the following DDL command:
192
Relational Database Management System
1. DROP TABLE Student;
Suppose, you want to delete the index_city from the SQL database.
To do this, you have to write the following DDL command:
We can also add and drop constraints of the table using the ALTER
command.
193
Relational Database Management System
Syntax to add a newfield in the table:
Suppose, you want to remove the Age and Marks column from the
existing Student table. To do this, you have to write the following
DDL command:
194
Relational Database Management System
Example 3: This example describes how to modify the existing
column of the existing table.
This command also removes the space allocated for storing the table
records.
195
Relational Database Management System
Example
The above query successfully removed all the records from the
student table. Let's verify it by using the following SELECT
statement:
Example
196
Relational Database Management System
This query changes the name of the table from Student to
Student_Details.
1. SELECT Command
2. INSERT Command
3. UPDATE Command
4. DELETE Command
197
Relational Database Management System
Syntax of SELECT DML command
If we want to retrieve the data from all the columns of the table, we
have to use the following SELECT command:
198
Relational Database Management System
BCA1001 Abhay 85
BCA1002 Anuj 75
BCA1003 Bheem 60
BCA1004 Ram 79
BCA1005 Sumit 80
Emp_Id Emp_Salary
201 25000
202 45000
203 30000
204 29000
199
Relational Database Management System
205 40000
BCA1001 Abhay 80
BCA1002 Ankit 75
BCA1003 Bheem 80
BCA1004 Ram 79
BCA1005 Sumit 80
If you want to access all the records of those students whose marks is
80 from the above table, then you have to write the following DML
command in SQL:
200
Relational Database Management System
BCA1001 Abhay 80
BCA1003 Bheem 80
BCA1005 Sumit 80
201
Relational Database Management System
101 Ramesh 92 20
201 Jatin 83 19
Suppose, you want to insert a new record into the student table. For
this, you have to write the following DML INSERT command:
Here, 'UPDATE', 'SET', and 'WHERE' are the SQL keywords, and
'Table_name' is the name of the table whose values you want to
update.
202
Relational Database Management System
Examples of the UPDATE command
P101 Chips 20 20
P102 Chocolates 60 40
P103 Maggi 75 5
P201 Biscuits 80 20
P203 Namkeen 40 50
203
Relational Database Management System
Example 2: This example describes how to update the value of
multiple fields of the database table.
101 Ramesh 92 20
201 Jatin 83 19
202 Anuj 85 19
203 Monty 95 21
102 Saket 65 21
103 Sumit 78 19
104 Ashish 98 20
204
Relational Database Management System
4.4.4 DELETE Command
P101 Chips 20 20
205
Relational Database Management System
P102 Chocolates 60 40
P103 Maggi 75 5
P201 Biscuits 80 20
P203 Namkeen 40 50
Suppose, you want to delete that product from the Product table
whose Product_Id is P203. To do this, you have to write the
following DML DELETE command:
101 Ramesh 92 20
201 Jatin 83 19
202 Anuj 85 19
206
Relational Database Management System
203 Monty 95 21
102 Saket 65 21
103 Sumit 78 19
104 Ashish 98 20
207
Relational Database Management System
Student
StudentCourse
208
Relational Database Management System
4.5.1. INNER JOIN
The INNER JOIN keyword selects all rows from both the tables as
long as the condition is satisfied. This keyword will create the result-
set by combining all rows from both the tables where the condition
satisfies i.e value of the common field will be the same.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
ON table1.matching_column = table2.matching_column;
209
Relational Database Management System
Example Queries(INNER JOIN)
This query will show the names and age of students enrolled in
different courses.
ON Student.ROLL_NO = StudentCourse.ROLL_NO;
Output:
210
Relational Database Management System
FROM table1
ON table1.matching_column = table2.matching_column;
Note: We can also use LEFT OUTER JOIN instead of LEFT JOIN,
both are the same.
FROM Student
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
211
Relational Database Management System
Output:
FROM table1
212
Relational Database Management System
ON table1.matching_column = table2.matching_column;
FROM Student
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
213
Relational Database Management System
Output:
214
Relational Database Management System
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
ON table1.matching_column = table2.matching_column;
FROM Student
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
215
Relational Database Management System
Output:
NAME COURSE_ID
HARSH 1
PRATIK 2
RIYANKA 2
DEEP 3
SAPTARHI 1
DHANRAJ NULL
ROHIT NULL
NIRAJ NULL
NULL 4
216
Relational Database Management System
NAME COURSE_ID
NULL 5
NULL 4
Natural join can join tables based on the common columns in the
tables being joined. A natural join returns all rows by matching
values in common columns having same name and data type of
columns and that column should be present in both tables.
Both table must have at list one common column with same column
name and same data type.
DBMS will look for a common column with same name and data
type Tuples having exactly same values in common columns are kept
in result.
217
Relational Database Management System
Example:
Employee
1 Ram 10
2 Jon 30
3 Bob 50
Department
Dept_id Dept_name
10 IT
30 HR
40 TIS
Query: Find all Employees and their respective departments.
1 Ram 10 10 IT
2 Jon 30 30 HR
218
Relational Database Management System
Emp_id Emp_name Dept_idDept_idDept_name
1 Ram 10 10 IT
The SQL Set operation is used to combine the two or more SQL
SELECT statements.
1. Union
2. UnionAll
3. Intersect
4. Minus
219
Relational Database Management System
1. Union
Syntax
220
Relational Database Management System
2. UNION
3. SELECT column_name FROM table2;
Example:
ID NAME
1 Jack
2 Harry
3 Jackson
ID NAME
3 Jackson
4 Stephan
5 David
221
Relational Database Management System
1. SELECT * FROM First
2. UNION
3. SELECT * FROM Second;
ID NAME
1 Jack
2 Harry
3 Jackson
4 Stephan
5 David
2. Union All
Union All operation is equal to the Union operation. It returns the set
without removing duplication and sorting the data.
Syntax:
222
Relational Database Management System
3. SELECT column_name FROM table2;
ID NAME
1 Jack
2 Harry
3 Jackson
3 Jackson
4 Stephan
5 David
223
Relational Database Management System
3. Intersect
Syntax
Example:
224
Relational Database Management System
ID NAME
3 Jackson
4. Minus
Syntax:
Example
225
Relational Database Management System
3. SELECT * FROM Second;
ID NAME
1 Jack
2 Harry
226
Relational Database Management System
A subquery can have only one column in the SELECT clause,
unless multiple columns are in the main query for the
subquery to compare its selected columns.
An ORDER BY command cannot be used in a subquery,
although the main query can use an ORDER BY. The
GROUP BY command can be used to perform the same
function as the ORDER BY in a subquery.
Subqueries that return more than one row can only be used
with multiple value operators such as the IN operator.
The SELECT list cannot include any references to values that
evaluate to a BLOB, ARRAY, CLOB, or NCLOB.
A subquery cannot be immediately enclosed in a set function.
The BETWEEN operator cannot be used with a subquery.
However, the BETWEEN operator can be used within the
subquery.
227
Relational Database Management System
FROM table1 [, table2 ]
[WHERE])
Example
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
SQL> SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS
WHERE SALARY > 4500) ;
228
Relational Database Management System
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+
229
Relational Database Management System
Example
UPDATE table
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
230
Relational Database Management System
Example
This would impact two rows and finally CUSTOMERS table would
have the following records.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 125.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 2125.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
231
Relational Database Management System
4.7.4 Subqueries with the DELETE Statement
Example
This would impact two rows and finally the CUSTOMERS table
would have the following records.
232
Relational Database Management System
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+
Questions
2 Mark Questions
1. Define SQL.
2. What is datatype?
3. List down few SQL datatypes.
4. List down DDL Commands.
5. Write a note on joins.
6. What are set operations?
7. Define aggregate functions.
8. What DML command in SQL?
9. Distinguish the difference between truncate, drop and
delete.
10. Write a brief note on subquery.
233
Relational Database Management System
234
Relational Database Management System
UNIT V
5.1. PL/SQL Introduction
The PL/SQL programming language was developed by Oracle
Corporation in the late 1980s as procedural extension language for
SQL and the Oracle relational database. Following are certain
notable facts about PL/SQL −
235
Relational Database Management System
PL/SQL is tightly integrated with SQL.
It offers extensive error checking.
It offers numerous data types.
It offers a variety of programming structures.
It supports structured programming through functions and
procedures.
It supports object-oriented programming.
It supports the development of web applications and server
pages.
Advantages of PL/SQL
PL/SQL has the following advantages −
SQL is the standard database language and PL/SQL is strongly
integrated with SQL. PL/SQL supports both static and dynamic
SQL. Static SQL supports DML operations and transaction
control from PL/SQL block. In Dynamic SQL, SQL allows
embedding DDL statements in PL/SQL blocks.
PL/SQL allows sending an entire block of statements to the
database at one time. This reduces network traffic and provides
high performance for the applications.
PL/SQL gives high productivity to programmers as it can query,
transform, and update data in a database.
236
Relational Database Management System
PL/SQL saves time on design and debugging by strong features,
such as exception handling, encapsulation, data hiding, and
object-oriented data types.
Applications written in PL/SQL are fully portable.
PL/SQL provides high security level.
PL/SQL provides access to predefined SQL packages.
PL/SQL provides support for Object-Oriented Programming.
PL/SQL provides support for developing Web Applications and
Server Pages.
237
Relational Database Management System
PL/SQL is a block structured language. This means a PL/SQL
program is made up of blocks, where block is a smallest piece of
PL/SQL code having logically related statements and declarations. A
block consists of three section snamely: Declare, Begin and
Exception followed by an End statement. We will see the different
sections of PL/SQL block.
Declare Section
Declare section declares the variables, constants, processes, functions,
etc., to be used in the other parts of program. It is an optional section.
Begin Section
It is the executable section. It consists of a set of SQL and
PL/SQL statements, which is executed when PL/SQL block runs.
It is a compulsory section.
Exception Section
This section handles the errors, which occurs during execution of
the PL/SQL block. This section allows the user to define his/her
own error messages. This section executes only when an error
occurs. It is an optional section.
238
Relational Database Management System
DECLARE
Declarationsofvariables,constantset
c.tobeuseinPL/SQL.
BEGIN
PL/SQLandSQLExecutablest
atements
EXCEPTION
PL/SQLcodetohandleerrorsd
uringexecutionperiod.
END;
Fig.5.1.APL/SQLblock
End Section
This section indicates the end of PL/SQL block. Every PL/SQL
program must consist of atleast one block, which may consist of any
number of nested sub-blocks. Figure 5.1 shows a typical PL/SQL
block.
239
Relational Database Management System
A variable should not exceed 30 characters. Its letter optionally
followed by more letters, dollar signs, numerals, underscore etc.
Example:
Radius Number := 5;
Date_of_birth date;
Declaration Restrictions:
In PL/SQL while declaring the variable some restrictions hold.
o Forward references are not allowed i.e. you must declare a
constant or variable before referencing it in another statement
even if it is a declarative statement.
val number := Total - 200;
Total number := 1000;
240
Relational Database Management System
The first declaration is illegal because the TOTAL variable
must be declared before using it in an assignment expression.
o Variables belonging to the same datatype cannot be declared
in the same statement.
N1, N2, N3 Number;
It is an illegal declaration.
241
Relational Database Management System
Evertime you declare a variable, PL/SQL defines a default value
NULL to it. If you want to initialize a variable with other value than
NULL value, you can do so during the declaration, by using any one
of the following methods.
o The DEFAULT keyword
o The assignment operator
counter binary_integer := 0;
greetings varchar2(20) DEFAULT 'Hello';
You can also specify NOT NULL constraint to avoid NULL
value. If you specify the NOT NULL constraint, you must assign
an initial value for that variable.
You must have a good programming skill to initialize variable
properly otherwise, sometimes program would produce unexpected
result.
Example of initializing variable
Let's take a simple example to explain it well:
DECLARE
a integer := 30;
b integer := 40;
c integer;
f real;
BEGIN
c := a + b;
dbms_output.put_line('Value of c: ' || c);
242
Relational Database Management System
f := 100.0/3.0;
dbms_output.put_line('Value of f: ' || f);
END;
After the execution, this will produce the following result:
Value of c: 70
Value of f: 33.333333333333333333
243
Relational Database Management System
num1 number := 95;
num2 number := 85;
BEGIN
dbms_output.put_line('Outer Variable num1: ' || num1);
dbms_output.put_line('Outer Variable num2: ' || num2);
DECLARE
Local variables
num1 number := 195;
num2 number := 185;
BEGIN
dbms_output.put_line('Inner Variable num1: ' || num1);
dbms_output.put_line('Inner Variable num2: ' || num2);
END;
END;
/
After the execution, this will produce the following result:
Outer Variable num1: 95
Outer Variable num2: 85
Inner Variable num1: 195
Inner Variable num2: 185
Variable Attributes:
244
Relational Database Management System
When you declare a PL/SQL variable to hold the column values, it
must be of correct data types and precision, otherwise error will
occur on execution. Rather than hard coding the data type and
precision of a variable. PL/SQL provides the facility to declare a
variable without having to specify a particular data type
using %TYPE and %ROWTYPE attributes. These two attributes
allow us to specify a variable and have that variable data type be
defined by a table/view column or a PL/SQL package variable.
245
Relational Database Management System
the user. These are then prefixed with the variable name. If some
previously declared variable is referred then prefix that variable
name to the %TYPE attribute.
Consider a declaration.
SALARY EMP.SAL % TYPE;
This declaration will declare a variable SALARY that has the same
data type as column SAL of the EMP table.
Example:
DECLARE
SALARY EMP.SAL % TYPE;
ECODE EMP.empno % TYPE;
BEGIN
Ecode :=&Ecode;
Select SAL into SALARY from EMP where EMPNO = ECOD
E;
dbms_output.put_line('Salary of ' || ECODE || 'is = || salary');
END;
After the execution, this will produce the following result:
Enter value for ecode: 7499
246
Relational Database Management System
Salary of 7499 is = 1600
PL/SQL procedure successfully completed.
%ROWTYPE:
The %ROWTYPE attribute is used to declare a record type that
represents a row in a table. The record can store an entire row or
some specific data selected from the table. A column in a row and
corresponding fields in a record have the same name and data types.
247
Relational Database Management System
5 EMPLOYEE.ENAME := 'Sanju';
Insert into EMP where (EMPNO, ENAME) Values (employee.
empno, employee.ename);
dbms_output.put_line('Row Inserted');
END;
After the execution, this will produce the following result:
Row Inserted
PL/SQL procedure successfully completed.
Advantages:
o If you don‘t know the data type at the time of declaration.
The data type assigned to the associated variables will be
determined dynamically at run time.
o If the data type of the variable you are referencing changes
the %TYPE or %ROWTYPE variable changes at run time
without having to rewrite variable declarations. For example:
if the ENAME column of an EMP table is changed from a
VARCHAR2(10) to VRACHAR2(15) then you don‘t need to
modify the PL/SQL code.
248
Relational Database Management System
Suppose, you have to write a program which will increase the salary
of the employees upto 30%, you can declare a constant and use it
throughout the program. Next time if you want to increase the salary
again you can change the value of constant than the actual value
throughout the program.
Syntax to declare a constant:
constant_name CONSTANT datatype := VALUE;
o Constant_name:it is the name of constant just like variable
name. The constant word is a reserved word and its value
does not change.
o VALUE: it is a value which is assigned to a constant when it
is declared. It can not be assigned later.
Example of PL/SQL constant
Let's take an example to explain it well:
DECLARE
constant declaration
pi constant number := 3.141592654;
other declarations
radius number(5,2);
dia number(5,2);
circumference number(7, 2);
area number (10, 2);
BEGIN
processing
249
Relational Database Management System
radius := 9.5;
dia := radius * 2;
circumference := 2.0 * pi * radius;
area := pi * radius * radius;
output
dbms_output.put_line('Radius: ' || radius);
dbms_output.put_line('Diameter: ' || dia);
dbms_output.put_line('Circumference: ' || circumference);
dbms_output.put_line('Area: ' || area);
END;
/
After the execution of the above code at SQL prompt, it will produce
the following result:.
Radius: 9.5
Diameter: 19
Circumference: 59.69
Area: 283.53
Pl/SQL procedure successfully completed.
250
Relational Database Management System
o Numeric Literals
o Character Literals
o String Literals
o BOOLEAN Literals
o Date and Time Literals
Example of these different types of Literals:
Literals Examples
251
Relational Database Management System
Relational operators
Comparison operators
Logical operators
A + B will
+ Adds two operands
give 15
A - B will
- Subtracts second operand from the first
give 5
A * B will
* Multiplies both operands
give 50
A / B will
/ Divides numerator by de-numerator
give 2
252
Relational Database Management System
5.6.2 Relational Operators
Relational operators compare two expressions or values and return a
Boolean result. Following table shows all the relational operators
supported by PL/SQL.
253
Relational Database Management System
operand, if yes then condition becomes true.
true.
254
Relational Database Management System
a AND b means that x >= a between 5 and 10
and x <= b. returns true, but x
between 11 and 20
returns false.
If x = 'm' then, x in
The IN operator tests set ('a', 'b', 'c') returns
membership. x IN (set) means Boolean false but x
IN
that x is equal to any member in ('m', 'n', 'o')
of set. returns Boolean
true.
255
Relational Database Management System
Operator Description Examples
256
Relational Database Management System
Here, operators with the highest precedence appear at the top of the
table, those with the lowest appear at the bottom. Within an
expression, higher precedence operators will be evaluated first.
The precedence of operators goes as follows: =, <, >, <=, >=, <>, !=,
~=, ^=, IS NULL, LIKE, BETWEEN, IN.
Operator Operation
** exponentiation
+, - identity, negation
*, / multiplication, division
comparison
AND conjunction
OR inclusion
258
Relational Database Management System
Syntax: (IF-THEN-ELSIF statement):
IF condition1
THEN
{...statements to execute when condition1 is TRUE...}
ELSIF condition2
THEN
{...statements to execute when condition2 is TRUE...}
END IF;
This syntax is used when you want to execute one set of statements
when condition1 is TRUE or a different set of statements when
condition2 is TRUE.
Syntax: (IF-THEN-ELSIF-ELSE statement):
IF condition1
THEN
{...statements to execute when condition1 is TRUE...}
ELSIF condition2
THEN
{...statements to execute when condition2 is TRUE...}
ELSE
{...statements to execute when both condition1 and condition2 ar
e FALSE...}
END IF;
It is the most advance syntax and used if you want to execute one set
of statements when condition1 is TRUE, a different set of statement
259
Relational Database Management System
when condition2 is TRUE or a different set of statements when both
the condition1 and condition2 are FALSE.
260
Relational Database Management System
261
Relational Database Management System
when 'A' then dbms_output.put_line('Excellent');
when 'B' then dbms_output.put_line('Very good');
when 'C' then dbms_output.put_line('Good');
when 'D' then dbms_output.put_line('Average');
when 'F' then dbms_output.put_line('Passed with Grace');
else dbms_output.put_line('Failed');
END CASE;
END;
After the execution of above code, you will get the following result:
Excellent
PL/SQL procedure successfully completed.
262
Relational Database Management System
For Loop
Cursor For Loop
263
Relational Database Management System
LOOP
EXIT WHEN i>10;
DBMS_OUTPUT.PUT_LINE(i);
i := i+1;
END LOOP;
END;
After the execution of the above code, you will get the following
result:
1
2
3
4
5
6
7
8
9
10
Note: You must follow these steps while using PL/SQL Exit Loop.
o Initialize a variable before the loop body
o Increment the variable in the loop.
o You should use EXIT WHEN statement to exit from the
Loop. Otherwise the EXIT statement without WHEN
condition, the statements in the Loop is executed only once.
264
Relational Database Management System
265
Relational Database Management System
3
4
5
6
7
8
9
10
Note: You must follow these steps while using PL/SQL WHILE
Loop.
o Initialize a variable before the loop body.
o Increment the variable in the loop.
o You can use EXIT WHEN statements and EXIT statements
in While loop but it is not done often.
266
Relational Database Management System
END LOOP;
o initial_value : Start integer value
o final_value : End integer value
PL/SQL For Loop Example 1
Let's see a simple example of PL/SQL FOR loop.
BEGIN
FOR k IN 1..10 LOOP
note that k was not declared
DBMS_OUTPUT.PUT_LINE(k);
END LOOP;
END;
After the execution of the above code, you will get the following
result:
1
2
3
4
5
6
7
8
9
10
267
Relational Database Management System
Note: You must follow these steps while using PL/SQL WHILE
Loop.
o You don't need to declare the counter variable explicitly
because it is declared implicitly in the declaration section.
o The counter variable is incremented by 1 and does not need to
be incremented explicitly.
o You can use EXIT WHEN statements and EXIT statements
in FOR Loops but it is not done often.
268
Relational Database Management System
x NUMBER := 0;
BEGIN
LOOP -- After CONTINUE statement, control resumes here
DBMS_OUTPUT.PUT_LINE ('Inside loop: x = ' || TO_CHAR(x
));
x := x + 1;
IF x < 3 THEN
CONTINUE;
END IF;
DBMS_OUTPUT.PUT_LINE
('Inside loop, after CONTINUE: x = ' || TO_CHAR(x));
EXIT WHEN x = 5;
END LOOP;
269
Relational Database Management System
Inside loop, after CONTINUE: x = 4
Inside loop: x = 4
Inside loop, after CONTINUE: x = 5
After loop: x = 5
Syntax:
GOTO label_name;
Here the label declaration which contains the label_name
encapsulated within the << >> symbol and must be followed by
at least one statement to execute.
GOTO label_name;
..
..
<<label_name>>
Statement;
Example of PL/SQL GOTO statement
270
Relational Database Management System
Let's take an example of PL/SQL GOTO statement.
DECLARE
a number(2) := 30;
BEGIN
<<loopstart>>
-- while loop execution
WHILE a < 50 LOOP
dbms_output.put_line ('value of a: ' || a);
a := a + 1;
IF a = 35 THEN
a := a + 1;
GOTO loopstart;
END IF;
END LOOP;
END;
/
After the execution of above code, you will get the following result:
value of a: 30
value of a: 31
value of a: 32
value of a: 33
value of a: 34
value of a: 36
value of a: 37
271
Relational Database Management System
value of a: 38
value of a: 39
value of a: 40
value of a: 41
value of a: 42
value of a: 43
value of a: 44
value of a: 45
value of a: 46
value of a: 47
value of a: 48
value of a: 49
Statement processed.
Restriction on GOTO statement
Following is a list of some restrictions imposed on GOTO statement.
o Cannot transfer control into an IF statement, CASE statement,
LOOP statement or sub-block.
o Cannot transfer control from one IF statement clause to
another or from one CASE statement WHEN clause to
another.
o Cannot transfer control from an outer block into a sub-block.
o Cannot transfer control out of a subprogram.
o Cannot transfer control into an exception handler.
272
Relational Database Management System
273
Relational Database Management System
A procedure may or may not return any value.
274
Relational Database Management System
begin
insert into user values(id,name);
end;
/
Output:
Procedure created.
ID Name
101 Rahul
275
Relational Database Management System
5.9 PL/SQL Function
The PL/SQL Function is very similar to PL/SQL Procedure. The
main difference between procedure and a function is, a function must
always return a value, and on the other hand a procedure may or may
not return a value. Except this, all the other things of PL/SQL
procedure are true for PL/SQL function too.
276
Relational Database Management System
o IN represents that value will be passed from outside and OUT
represents that this parameter will be used to return a value
outside of the procedure.
The function must contain a return statement.
o RETURN clause specifies that data type you are going to
return from the function.
o Function_body contains the executable part.
o The AS keyword is used instead of the IS keyword for
creating a standalone function.
277
Relational Database Management System
BEGIN
n3 := adder(11,22);
dbms_output.put_line('Addition is: ' || n3);
END;
/
Output:
Addition is: 33
Statement processed.
0.05 seconds
Customers
278
Relational Database Management System
4 dilshad database manager 44000
Create Function:
CREATE OR REPLACE FUNCTION totalCustomers
RETURN number IS
total number(2) := 0;
BEGIN
SELECT count(*) into total
FROM customers;
RETURN total;
END;
/
After the execution of above code, you will get the following result.
Function created.
279
Relational Database Management System
returned value. Following program calls the function totalCustomers
from an anonymous block:
DECLARE
c number(2);
BEGIN
c := totalCustomers();
dbms_output.put_line('Total no. of Customers: ' || c);
END;
/
After the execution of above code in SQL prompt, you will get the
following result.
Total no. of Customers: 4
PL/SQL procedure successfully completed.
280
Relational Database Management System
FUNCTION fact(x number)
RETURN number
IS
f number;
BEGIN
IF x=0 THEN
f := 1;
ELSE
f := x * fact(x-1);
END IF;
RETURN f;
END;
BEGIN
num:= 6;
factorial := fact(num);
dbms_output.put_line(' Factorial '|| num || ' is ' || factorial);
END;
/
After the execution of above code at SQL prompt, it produces the
following result.
Factorial 6 is 720
PL/SQL procedure successfully completed.
PL/SQL Drop Function
281
Relational Database Management System
Syntax for removing your created function:
If you want to remove your created function from the database, you
should use the following syntax.
DROP FUNCTION function_name;
282
Relational Database Management System
attributes to check the status of DML operations. Some of them
are: %FOUND, %NOTFOUND, %ROWCOUNT and %ISOPEN.
For example: When you execute the SQL statements like INSERT,
UPDATE, DELETE then the cursor attributes tell whether any rows
are affected and how many have been affected. If you run a SELECT
INTO statement in PL/SQL block, the implicit cursor attribute can be
used to find out whether any row has been returned by the SELECT
statement. It will return an error if there no data is selected.
The following table soecifies the status of the cursor with each of its
attribute.
Attribute Description
283
Relational Database Management System
of %FOUND.
284
Relational Database Management System
Let's execute the following program to update the table and increase
salary of each customer by 5000. Here, SQL%ROWCOUNT
attribute is used to determine the number of rows affected:
Create procedure:
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 5000;
IF sql%notfound THEN
dbms_output.put_line('no customers updated');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers updated ');
END IF;
END;
/
Output:
6 customers updated
PL/SQL procedure successfully completed.
Now, if you check the records in customer table, you will find that
the rows are updated.
1. select * from customers;
285
Relational Database Management System
286
Relational Database Management System
1. Declare the cursor to initialize in the memory.
2. Open the cursor to allocate memory.
3. Fetch the cursor to retrieve data.
4. Close the cursor to release allocated memory.
1) Declare the cursor:
It defines the cursor with a name and the associated SELECT
statement.
Syntax for explicit cursor decleration
CURSOR name IS
SELECT statement;
2) Open the cursor:
It is used to allocate memory for the cursor and make it easy to fetch
the rows returned by the SQL statements into it.
Syntax for cursor open:
OPEN cursor_name;
3) Fetch the cursor:
It is used to access one row at a time. You can fetch rows from the
above-opened cursor as follows:
287
Relational Database Management System
288
Relational Database Management System
6 Sunita 20 Delhi 30000
Create procedure:
Execute the following program to retrieve the customer name and
address.
DECLARE
c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE c_customers;
END;
/
Output:
1 Ramesh Allahabad
2 Suresh Kanpur
289
Relational Database Management System
3 Mahesh Ghaziabad
4 Chandan Noida
5 Alex Paris
6 Sunita Delhi
PL/SQL procedure successfully completed.
290
Relational Database Management System
EXCEPTION
<exception handling goes here >
WHEN exception1 THEN
exception1-handling-statements
WHEN exception2 THEN
exception2-handling-statements
WHEN exception3 THEN
exception3-handling-statements
........
WHEN others THEN
exception3-handling-statements
END;
Example of exception handling
Let's take a simple example to demonstrate the concept of exception
handling. Here we are using the already created CUSTOMERS table.
SELECT* FROM COUSTOMERS;
291
Relational Database Management System
4 Chandan 25 Noida 26000
DECLARE
c_id customers.id%type := 8;
c_name customers.name%type;
c_addr customers.address%type;
BEGIN
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
292
Relational Database Management System
After the execution of above code at SQL Prompt, it produces the
following result:
No such customer!
PL/SQL procedure successfully completed.
The above program should show the name and address of a customer
as result whose ID is given. But there is no customer with ID value 8
in our database, so the program raises the run-time exception
NO_DATA_FOUND, which is captured in EXCEPTION block.
If you use the id defined in the above table (i.e. 1 to 6), you will get a
certain result. For a demo example: here, we are using the id 5.
DECLARE
c_id customers.id%type := 5;
c_name customers.name%type;
c_addr customers.address%type;
BEGIN
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
293
Relational Database Management System
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
After the execution of above code at SQL prompt, you will get the
following result:
Name: alex
Address: paris
PL/SQL procedure successfully completed.
Raising Exceptions
In the case of any internal database error, exceptions are raised by the
database server automatically. But it can also be raised explicitly by
programmer by using command RAISE.
Syntax for raising an exception:
DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
WHEN exception_name THEN
statement;
294
Relational Database Management System
END;
295
Relational Database Management System
CASE_NOT 06592 -6592 It is raised when
_FOUND none of the choices
in the "WHEN"
clauses of a CASE
statement is selected,
and there is no else
clause.
296
Relational Database Management System
attempted to be
stored in a column
with unique index.
297
Relational Database Management System
invalid username or
password.
298
Relational Database Management System
invoked, but the
instance of the
object type was not
initialized.
299
Relational Database Management System
zero.
Advantages of Triggers
These are the following advantages of Triggers:
o Trigger generates some derived column values automatically
o Enforces referential integrity
300
Relational Database Management System
o Event logging and storing information on table access
o Auditing
o Synchronous replication of tables
o Imposing security authorizations
o Preventing invalid transactions
Creating a trigger:
Syntax for creating trigger:
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
Here,
301
Relational Database Management System
o CREATE [OR REPLACE] TRIGGER trigger_name: It
creates or replaces an existing trigger with the trigger_name.
o {BEFORE | AFTER | INSTEAD OF} : This specifies when
the trigger would be executed. The INSTEAD OF clause is
used for creating trigger on a view.
o {INSERT [OR] | UPDATE [OR] | DELETE}: This specifies
the DML operation.
o [OF col_name]: This specifies the column name that would
be updated.
o [ON table_name]: This specifies the name of the table
associated with the trigger.
o [REFERENCING OLD AS o NEW AS n]: This allows you
to refer new and old values for various DML statements, like
INSERT, UPDATE, and DELETE.
o [FOR EACH ROW]: This specifies a row level trigger, i.e.,
the trigger would be executed for each row being affected.
Otherwise the trigger will execute just once when the SQL
statement is executed, which is called a table level trigger.
o WHEN (condition): This provides a condition for rows for
which the trigger would fire. This clause is valid only for row
level triggers.
PL/SQL Trigger Example
Let's take a simple example to demonstrate the trigger. In this
example, we are using the following CUSTOMERS table:
302
Relational Database Management System
Create trigger:
Let's take a program to create a row level trigger for the
CUSTOMERS table that would fire for INSERT or UPDATE or
DELETE operations performed on the CUSTOMERS table. This
trigger will display the salary difference between the old values and
new values:
CREATE OR REPLACE TRIGGER display_salary_changes
BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID > 0)
303
Relational Database Management System
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;
/
After the execution of the above code at SQL Prompt, it produces the
following result.
Trigger created.
Check the salary difference by procedure:
Use the following code to get the old salary, new salary and salary
difference after the trigger created.
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 5000;
IF sql%notfound THEN
dbms_output.put_line('no customers updated');
ELSIF sql%found THEN
total_rows := sql%rowcount;
304
Relational Database Management System
dbms_output.put_line( total_rows || ' customers updated ');
END IF;
END;
/
Output:
Old salary: 20000
New salary: 25000
Salary difference: 5000
Old salary: 22000
New salary: 27000
Salary difference: 5000
Old salary: 24000
New salary: 29000
Salary difference: 5000
Old salary: 26000
New salary: 31000
Salary difference: 5000
Old salary: 28000
New salary: 33000
Salary difference: 5000
Old salary: 30000
New salary: 35000
Salary difference: 5000
6 customers updated
305
Relational Database Management System
Note: As many times you executed this code, the old and new both
salary is incremented by 5000 and hence the salary difference is
always 5000.
After the execution of above code again, you will get the following
result.
Old salary: 25000
New salary: 30000
Salary difference: 5000
Old salary: 27000
New salary: 32000
Salary difference: 5000
Old salary: 29000
New salary: 34000
Salary difference: 5000
Old salary: 31000
New salary: 36000
Salary difference: 5000
Old salary: 33000
New salary: 38000
Salary difference: 5000
Old salary: 35000
New salary: 40000
Salary difference: 5000
6 customers updated
306
Relational Database Management System
Important Points
Following are the two very important point and should be noted
carefully.
o OLD and NEW references are used for record level triggers
these are not available for table level triggers.
o If you want to query the table in the same trigger, then you
should use the AFTER keyword, because triggers can query
the table or change it again only after the initial changes are
applied and the table is back in a consistent state.
Questions:
2 Mark Questions:
1. Define PL/SQL.
2. List down the advantages of PL/SQL.
3. Define PL/SQL Operators.
4. Define function.
5. Define package.
6. What is mean by procedure and procedure call?
7. Define exception handling.
8. List down some built in exceptions.
9. Define triggers.
10. What is cursor? What are the types of cursor?
307
Relational Database Management System
5 Mark / 10 Mark Questions:
11. Illustrate the structure of PL/SQL.
12. What are the PL/SQL Elements?
13. Explain about Datatypes.
14. What is operator precedence? Explain.
15. Explain IF control with suitable example.
16. Explain Loops in PL/SQL with suitable examples.
17. What is cursor? Explain in detail.
18. Elucidate the Functions in PL/SQL.
19. How PL/SQL handles the user defined exceptions?
20. Explain Triggers in detail.
308
Relational Database Management System
309
Relational Database Management System
-- Truncate the table
TRUNCATE TABLE customers;
-- Drop the table
DROP TABLE customers;
OUTPUT:
The table is dropped
310
Relational Database Management System
INSERT INTO products (name, price) VALUES ('Product 1', 100),
('Product 2', 200), ('Product 3', 300);
OUTPUT:
+----+-----------+--------+
| id | name | price |
+----+-----------+--------+
| 2 | Product 2 | 200.00 |
311
Relational Database Management System
+----+-----------+--------+
1 row in set (0.000 sec)
Source code:
-- Create a table
CREATE TABLE `users` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
`age` INT NOT NULL,
PRIMARY KEY (`id`)
);
-- Insert some data into the table
INSERT INTO `users` (`name`, `age`) VALUES
('John Doe', 30),
('Jane Doe', 25),
('Peter Parker', 20),
('Mary Jane Watson', 19);
-- Simple query
SELECT * FROM `users`;
-- Query with a subquery
SELECT * FROM `users` WHERE `age` > (SELECT AVG(`age`)
FROM `users`);
312
Relational Database Management System
-- Query with an aggregate function
SELECT COUNT(`id`) AS `total_users` FROM `users`;
OUTPUT:
MariaDB [my_database]> -- Simple query
MariaDB [my_database]> SELECT * FROM `users`;
+----+------------------+-----+
| id | name | age |
+----+------------------+-----+
| 1 | John Doe | 30 |
| 2 | Jane Doe | 25 |
| 3 | Peter Parker | 20 |
| 4 | Mary Jane Watson | 19 |
+----+------------------+-----+
4 rows in set (0.001 sec)
MariaDB [my_database]> -- Query with a subquery
MariaDB [my_database]> SELECT * FROM `users` WHERE `age` >
(SELECT AVG(`age`) FROM `users`);
+----+----------+-----+
| id | name | age |
+----+----------+-----+
| 1 | John Doe | 30 |
| 2 | Jane Doe | 25 |
+----+----------+-----+
313
Relational Database Management System
2 rows in set (0.004 sec)
MariaDB [my_database]> -- Query with an aggregate function
MariaDB [my_database]> SELECT COUNT(`id`) AS `total_users`
FROM `users`;
+-------------+
| total_users |
+-------------+
| 4|
+-------------+
1 row in set (0.000 sec)
314
Relational Database Management System
ISBN VARCHAR(13) NOT NULL UNIQUE,
CopiesAvailable INT NOT NULL,
TotalCopies INT NOT NULL
);
315
Relational Database Management System
FOREIGN KEY (BorrowerID) REFERENCES
Borrowers(BorrowerID)
);
316
Relational Database Management System
OUTPUT:
+---------------------+-----------------+------------+
| Title | TransactionDate | DueDate |
+---------------------+-----------------+------------+
| Introduction to SQL | 2023-09-21 | 2023-10-21 |
317
Relational Database Management System
+---------------------+-----------------+------------+
1 row in set (0.016 sec)
+--------+---------------------+------------+------------+-----------------+---
----------+
| BookID | Title | Author | ISBN | CopiesAvailable |
TotalCopies |
+--------+---------------------+------------+------------+-----------------+---
----------+
| 1 | Introduction to SQL | John Smith | 1234567890 | 5|
5|
| 2 | Python Programming | Jane Doe | 9876543210 | 3|
3|
+--------+---------------------+------------+------------+-----------------+---
----------+
2 rows in set (0.000 sec)
318
Relational Database Management System
FirstName VARCHAR(50),
LastName VARCHAR(50),
DateOfBirth DATE,
Email VARCHAR(100)
);
319
Relational Database Management System
(1, 'Math', 90),
(1, 'Science', 85),
(2, 'Math', 92),
(2, 'Science', 88),
(3, 'Math', 78),
(3, 'Science', 80);
-- Retrieve all students and their marks
SELECT Students.FirstName, Students.LastName, Marks.Subject,
Marks.Mark
FROM Students
INNER JOIN Marks ON Students.StudentID = Marks.StudentID;
320
Relational Database Management System
OUTPUT:
+-----------+----------+---------+------+
| FirstName | LastName | Subject | Mark |
+-----------+----------+---------+------+
| John | Doe | Math | 90 |
| John | Doe | Science | 85 |
| Jane | Smith | Math | 92 |
| Jane | Smith | Science | 88 |
| Bob | Johnson | Math | 78 |
| Bob | Johnson | Science | 80 |
+-----------+----------+---------+------+
6 rows in set (0.019 sec)
+-----------+----------+-------------+
| FirstName | LastName | AverageMark |
+-----------+----------+-------------+
| John | Doe | 87.5000 |
| Jane | Smith | 90.0000 |
| Bob | Johnson | 79.0000 |
+-----------+----------+-------------+
3 rows in set (0.000 sec)
+-----------+----------+
| FirstName | LastName |
+-----------+----------+
321
Relational Database Management System
| John | Doe |
| Jane | Smith |
+-----------+----------+
2 rows in set (0.001 sec)
322
Relational Database Management System
EmployeeID INT,
Salary DECIMAL(10, 2),
HoursWorked DECIMAL(5, 2),
OvertimeHours DECIMAL(5, 2),
Deductions DECIMAL(10, 2),
GrossPay DECIMAL(10, 2),
NetPay DECIMAL(10, 2),
PayrollDate DATE,
FOREIGN KEY (EmployeeID) REFERENCES
Employees(EmployeeID)
);
323
Relational Database Management System
INSERT INTO Payroll (PayrollID, EmployeeID, Salary,
HoursWorked, OvertimeHours, Deductions, GrossPay, NetPay,
PayrollDate)
VALUES
(1, 1, 5000.00, 160.00, 10.00, 200.00, 7000.00, 6800.00, '2023-09-
15'),
(2, 2, 6000.00, 175.00, 15.00, 250.00, 8000.00, 7750.00, '2023-09-
15');
OUTPUT:
+-----------+----------+---------+-------------+---------------+------------+-
---------+---------+-------------+
| FirstName | LastName | Salary | HoursWorked | OvertimeHours |
Deductions | GrossPay | NetPay | PayrollDate |
+-----------+----------+---------+-------------+---------------+------------+-
---------+---------+-------------+
324
Relational Database Management System
| John | Doe | 5000.00 | 160.00 | 10.00 | 200.00 |
7000.00 | 6800.00 | 2023-09-15 |
| Jane | Smith | 6000.00 | 175.00 | 15.00 | 250.00 |
8000.00 | 7750.00 | 2023-09-15 |
+-----------+----------+---------+-------------+---------------+------------+-
---------+---------+-------------+
2 rows in set (0.015 sec)
*******************************************************
325
Relational Database Management System
References Books
1. Raghu Ramakrishnan - Database Management Systems-
WCB/McGrawHill
Web References
https://www.tutorialspoint.com
https://www.geeksforgeeks.org
https://artoftesting.com
https://www.w3schools.com
www.programiz.com
https://www.scaler.com
326