Professional Documents
Culture Documents
Unit II
Unit II
DBMS
th
4 sem Notes
Unit II:
Relational database
A relational database is a type of database that organizes
data into rows and columns, which collectively form a table
where the data points are related to each other.
Data is typically structured across multiple tables, which can be joined
together via a primary key or a foreign key. These unique identifiers
demonstrate the different relationships which exist between tables, and these
relationships are usually illustrated through different types of data models.
Analysts use SQL queries to combine different data points and summarize
business performance, allowing organizations to gain insights, optimize
workflows, and identify new opportunities.
The columns (or fields) for the customer table might be Customer
ID, Company Name, Company Address, Industry etc.; the columns for a
transaction table might be Transaction Date, Customer ID, Transaction
Amount, Payment Method, etc. The tables can be joined together with the
common Customer ID field. You can, therefore, query the table to produce
valuable reports, such as a sales reports by industry or company, which can
inform messaging to prospective clients.
Atomicity:
By this, we mean that either the entire transaction takes place at
once or doesn’t happen at all. There is no midway i.e.
transactions do not occur partially. Each transaction is
considered as one unit and either runs to completion or is not
executed at all. It involves the following two operations.
—Abort: If a transaction aborts, changes made to the database
are not visible.
—Commit: If a transaction commits, changes made are visible.
Atomicity is also known as the ‘All or nothing rule’.
Consistency:
Isolation:
This property ensures that multiple transactions can occur
concurrently without leading to the inconsistency of the database
state. Transactions occur independently without interference.
Changes occurring in a particular transaction will not be visible
to any other transaction until that particular change in that
transaction is written to memory or has been committed. This
property ensures that the execution of transactions concurrently
will result in a state that is equivalent to a state achieved these
were executed serially in some order.
Let X= 500, Y = 500.
Consider two transactions T and T”.
Suppose T has been executed till Read (Y) and then T’’ starts.
As a result, interleaving of operations takes place due to
which T’’ reads the correct value of X but the incorrect value
of Y and sum computed by
T’’: (X+Y = 50, 000+500=50, 500)
is thus not consistent with the sum at end of the transaction:
T: (X+Y = 50, 000 + 450 = 50, 450).
This results in database inconsistency, due to a loss of 50 units.
Hence, transactions must take place in isolation and changes
should be visible only after they have been made to the main
memory.
Durability:
ACID properties are the four key characteristics that define the
reliability and consistency of a transaction in a Database
Management System (DBMS). The acronym ACID stands for
Atomicity, Consistency, Isolation, and Durability. Here is a brief
description of each of these properties:
1. Atomicity: Atomicity ensures that a transaction is treated as a
single, indivisible unit of work. Either all the operations within
the transaction are completed successfully, or none of them
are. If any part of the transaction fails, the entire transaction
is rolled back to its original state, ensuring data consistency
and integrity.
2. Consistency: Consistency ensures that a transaction takes
the database from one consistent state to another consistent
state. The database is in a consistent state both before and
after the transaction is executed. Constraints, such as unique
keys and foreign keys, must be maintained to ensure data
consistency.
3. Isolation: Isolation ensures that multiple transactions can
execute concurrently without interfering with each other.
Each transaction must be isolated from other transactions
until it is completed. This isolation prevents dirty reads, non-
repeatable reads, and phantom reads.
4. Durability: Durability ensures that once a transaction is
committed, its changes are permanent and will survive any
subsequent system failures. The transaction’s changes are
saved to the database permanently, and even if the system
crashes, the changes remain intact and can be recovered.
Overall, ACID properties provide a framework for ensuring data
consistency, integrity, and reliability in DBMS. They ensure that
transactions are executed in a reliable and consistent manner,
even in the presence of system failures, network issues, or other
problems. These properties make DBMS a reliable and efficient
tool for managing data in modern organizations.
1. Select Operation:
o The select operation selects tuples that satisfy a given predicate.
o It is denoted by sigma (σ).
1. Notation: σ p(r)
Where:
Input:
1. σ BRANCH_NAME="perryride" (LOAN)
Output:
2. Project Operation:
o This operation shows the list of those attributes that we wish to
appear in the result. Rest of the attributes are eliminated from
the table.
o It is denoted by ∏.
Where
Input:
Output:
NAME CITY
Jones Harrison
Smith Rye
Hays Harrison
Curry Rye
Johnson Brooklyn
Brooks Brooklyn
3. Union Operation:
o Suppose there are two tuples R and S. The union operation
contains all the tuples that are either in R or S or both in R & S.
o It eliminates the duplicate tuples. It is denoted by ∪.
1. Notation: R ∪ S
Example:
DEPOSITOR RELATION
CUSTOMER_NAME ACCOUNT_NO
Johnson A-101
Smith A-121
Mayes A-321
Turner A-176
Johnson A-273
Jones A-472
Lindsay A-284
BORROW RELATION
CUSTOMER_NAME LOAN_NO
Jones L-17
Smith L-23
Hayes L-15
Jackson L-14
Curry L-93
Smith L-11
Williams L-17
Input:
Output:
CUSTOMER_NAME
Johnson
Smith
Hayes
Turner
Jones
Lindsay
Jackson
Curry
Williams
Mayes
4. Set Intersection:
o Suppose there are two tuples R and S. The set intersection
operation contains all tuples that are in both R & S.
o It is denoted by intersection ∩.
1. Notation: R ∩ S
Input:
Output:
CUSTOMER_NAME
Smith
Jones
5. Set Difference:
o Suppose there are two tuples R and S. The set intersection
operation contains all tuples that are in R but not in S.
o It is denoted by intersection minus (-).
1. Notation: R - S
Input:
CUSTOMER_NAME
Jackson
Hayes
Willians
Curry
6. Cartesian product
o The Cartesian product is used to combine each row in one table
with each row in the other table. It is also known as a cross
product.
o It is denoted by X.
1. 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:
1. EMPLOYEE X DEPARTMENT
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
7. Rename Operation:
The rename operation is used to rename the output relation. It is
denoted by rho (ρ).
1. ρ(STUDENT1, STUDENT)
Relational Calculus
There is an alternate way of formulating queries known as Relational
Calculus. Relational calculus is a non-procedural query language. In
the non-procedural query language, the user is concerned with the
details of how to obtain the end results. The relational calculus tells
what to do but never explains how to do. Most commercial relational
languages are based on aspects of relational calculus including SQL-
QBE and QUEL.
ADVERTISEMENT
Free and bound variables may be compared with global and local
variable of programming languages.
Types of Relational calculus:
Salary
Department ID
Saurabh A7 Patiala
Customer
name Street City
Mehak B6 Jalandhar
Sumiti D9 Ludhiana
Ria A5 Patiala
Table Branch
Branch
name Branch City
ABC Patiala
DEF Ludhiana
GHI Jalandhar
Table Account
Branch
Account number name Balance
Table Loan
Loan
number Branch name Amount
Table Borrower
Customer
name Loan number
Saurabh L33
Mehak L49
Ria L98
Table Depositor
Customer
name Account number
Saurabh 1111
Mehak 1113
Suniti 1114
Resulting relation:
Loan
number Branch name Amount
Resulting relation:
Loan number
L33
L35
L98
Resulting relation:
Customer name
Saurabh
Mehak
Resulting relation:
Customer name
Saurabh
A domain is equivalent to
A tuple is a single element
column data type and any
3. Tuple/ Domain of relation. In database
constraints on the value of
terms, it is a row.
data.
Relational Calculus is a
Language Type It is a Procedural language. Declarative (non-procedural)
1. language.
8. Query The evaluation of the query The order of operations does not
Basis of
S.NO Comparison Relational Algebra Relational Calculus
SQL:
DDL:
DDL (Data Definition Language)
DDL or Data Definition Language actually consists of the SQL
commands that can be used to define the database schema. It
simply deals with descriptions of the database schema and is
used to create and modify the structure of database objects in
the database. DDL is a set of SQL commands used to create,
modify, and delete database structures but not data. These
commands are normally not used by a general user, who should
be accessing the database via an application.
List of DDL commands:
CREATE: This command is used to create the database or
its objects (like table, index, function, views, store procedure,
and triggers).
DROP: This command is used to delete objects from the
database.
ALTER: This is used to alter the structure of the database.
TRUNCATE: This is used to remove all records from a table,
including all spaces allocated for the records are removed.
COMMENT: This is used to add comments to the data
dictionary.
RENAME: This is used to rename an object existing in the
database.
DQL (Data Query Language)
DQL statements are used for performing queries on the data
within schema objects. The purpose of the DQL Command is to
get some schema relation based on the query passed to it.
DDL Commands :
In this section, We will cover the following DDL commands as
follows.
1. Create
2. Alter
3. truncate
4. drop
5. Rename
Let’s discuss it one by one.
Command-1 :
CREATE :
This command is used to create a new table in SQL. The user
has to give information like table name, column names, and their
datatypes.
Syntax –
CREATE TABLE table_name
(
column_1 datatype,
column_2 datatype,
column_3 datatype,
....
);
Example –
We need to create a table for storing Student information of a
particular College. Create syntax would be as below.
CREATE TABLE Student_info
(
College_Id number(2),
College_name varchar(30),
Branch varchar(10)
);
Command-2 :
ALTER :
This command is used to add, delete or change columns in the
existing table. The user needs to know the existing table name
and can do add, delete or modify tasks easily.
Syntax –
Syntax to add a column to an existing table.
ALTER TABLE table_name
ADD column_name datatype;
Example –
In our Student_info table, we want to add a new column for
CGPA. The syntax would be as below as follows.
ALTER TABLE Student_info
ADD CGPA number;
Command-3 :
TRUNCATE :
This command is used to remove all rows from the table, but the
structure of the table still exists.
Syntax –
Syntax to remove an existing table.
TRUNCATE TABLE table_name;
Example –
The College Authority wants to remove the details of all students
for new batches but wants to keep the table structure. The
command they can use is as follows.
TRUNCATE TABLE Student_info;
Command-4 :
DROP :
This command is used to remove an existing table along with its
structure from the Database.
Syntax –
Syntax to drop an existing table.
DROP TABLE table_name;
Example –
If the College Authority wants to change their Database by
deleting the Student_info Table.
DROP TABLE Student_info;
Command -5
RENAME:
It is possible to change name of table with or without data in it
using simple RENAME command.
We can rename any table object at any point of time.
Syntax –
RENAME TABLE <Table Name> To <New_Table_Name>;
Example:
If you want to change the name of the table from Employee to
Emp we can use rename command as
RENAME TABLE Employee To EMP;
Characteristics of DML
It performs interpret-only data queries. It is used in a database
schema to recall and manipulate the information. DML It is a
dialect which is used to select, insert, delete and update data in
a database. Data Manipulation Language (DML) commands are
as follows:
1. SELECT Command
2. INSERT Command
3. UPDATE Command
4. DELETE Command
SELECT DML Command
SELECT is the most important data manipulation command in
Structured Query Language. The SELECT command shows the records
of the specified table. It also shows the particular record of a particular
column by using the WHERE clause.
If we want to retrieve the data from all the columns of the table, we
have to use the following SELECT command:
This SQL statement displays the following values of the student table:
BCA1002 Anuj 75
BCA1003 Bheem 60
BCA1004 Ram 79
BCA1005 Sumit 80
Emp_Id Emp_Salary
201 25000
202 45000
203 30000
204 29000
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:
BCA1001 Abhay 80
BCA1003 Bheem 80
BCA1005 Sumit 80
Let's take the following student table, which consists of only 2 records
of the student.
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.
P101 Chips 20 20
P102 Chocolates 60 40
P103 Maggi 75 5
P201 Biscuits 80 20
P203 Namkeen 40 50
201 Jatin 83 19
202 Anuj 85 19
203 Monty 95 21
102 Saket 65 21
103 Sumit 78 19
104 Ashish 98 20
P101 Chips 20 20
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
203 Monty 95 21
102 Saket 65 21
103 Sumit 78 19
104 Ashish 98 20
Syntax of Trigger
We can create a trigger in SQL Server by using the CREATE
TRIGGER statement as follows:
NOT FOR REPLICATION: This option tells that SQL Server does not
execute the trigger when data is modified as part of a replication
process.
SQL_Statements: It contains one or more SQL statements that are
used to perform actions in response to an event that occurs.
After creating a trigger, we will try to add the following record into the
table:
DDL Triggers
DDL triggers are fired in response to the DDL events, such as CREATE,
ALTER, and DROP statements. We can create these triggers at the
database level or server level, depending on the type of DDL events. It
can also be executed in response to certain system-defined stored
procedures that do DDL-like operations.
DML Triggers
DML triggers are fired in response to DML events like INSERT,
UPDATE, and DELETE statements in the user's table or view. It can also
be executed in response to DML-like operations performed by system-
defined stored procedures.
o After Triggers
o Instead Of Triggers
After Triggers
After trigger fires, when SQL Server completes the triggering action
successfully, that fired it. Generally, this trigger is executed when a
table completes an insert, update or delete operations. It is not
supported in views. Sometimes it is known as FOR triggers.
Instead of Triggers
Instead of Trigger fires before SQL Server begins to execute the
triggering operation that triggered it. It means that no condition
constraint check is needed before the trigger runs. As a result, even if
the constraint check fails, this trigger will fire. It is the opposite of the
AFTER trigger. We can create the INSTEAD OF triggers on a table that
executes successfully but doesn't contain the table's actual insert,
update, or delete operations.
Example: When we insert data into a table, the trigger associated with
the insert operation on that table will fire before the data has passed
all constraints, such as the primary key constraint. SQL Server also fires
the Instead of Trigger if the data insertion fails.
Logon Triggers
Logon triggers are fires in response to a LOGON event. The LOGON
event occurs when a user session is generated with an SQL Server
instance, which is made after the authentication process of logging is
completed but before establishing a user session. As a result, the SQL
Server error log will display all messages created by the trigger,
including error messages and the PRINT statement messages. If
authentication fails, logon triggers do not execute. These triggers may
be used to audit and control server sessions, such as tracking login
activity or limiting the number of sessions for a particular login.
Advantages of Triggers
The following are the advantages of using triggers in SQL Server:
o Triggers set database object rules and roll back if any change
does not satisfy those rules. The trigger will inspect the data and
make changes if necessary.
o Triggers help us to enforce data integrity.
o Triggers help us to validate data before inserted or updated.
o Triggers help us to keep a log of records.
o Triggers increase SQL queries' performance because they do not
need to compile each time they are executed.
o Triggers reduce the client-side code that saves time and effort.
o Triggers are easy to maintain.
Disadvantages of Triggers
The following are the disadvantages of using triggers in SQL Server:
Properties of Cursors
Syntax
Following is the syntax to declare a cursor in MySQL database −
Syntax
Following is the syntax to open a cursor in MySQL database −
OPEN cursor_name;
Fetch Cursor Statement
Then, we can use the FETCH statement to retrieve the current row
pointed by the cursor, and with each FETCH, the cursor moves to
the next row in the result set. This allows us to process each row
one by one.
Syntax
Following is the syntax to fetch a cursor in MySQL database −
Once all the rows are fetched, we must close the cursor to release
the memory associated with it. We can do this using the CLOSE
statement.
Syntax
Following is the syntax to close a cursor in MySQL database −
CLOSE cursor_name;
Example
In this example, let us see how to manage a cursor in a stored
procedure.
);
Now, let us insert some records into the CUSTOMERS table using
the INSERT statement as follows −
INSERT INTO CUSTOMERS VALUES
(1, 'Ramesh', 32, 'Ahmedabad', 2000.00 ),
);
Here, we are creating a stored procedure named FetchCustomers to
fetch customer names from the CUSTOMERS table and inserting
them one by one into the BACKUP table. We are using a cursor to
iterate through the rows and a handler to detect the end of the
result-set, ensuring all names are processed −
DELIMITER //
CREATE PROCEDURE FetchCustomers()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE customer_id INT;
DECLARE customer_name VARCHAR(255);
DECLARE auto_id INT;
-- Declare cursor
DECLARE MY_CURSOR CURSOR FOR
SELECT id, name FROM CUSTOMERS;
-- Open cursor
OPEN MY_CURSOR;
END LOOP;
-- Close cursor
CLOSE MY_CURSOR;
END //
DELIMITER ;
CALL FetchCustomers();
Verification
You can verify the contents of the CUSTOMERS_BACKUP table using
the SELECT statement as shown below −
ID NAME
1 Ramesh
2 Khilan
3 Kaushik
4 Chaitali