DBMS Lab_Manual (3)
DBMS Lab_Manual (3)
3. Relational Model 10
4. Write relational algebra queries for a given set of 12
relations
5. Perform the following : 16
a)creating a Database ,Viewing all databases, ,
Viewing all Tables in a database (with and
without Constraints), Backing up/Restoring a
Database.
1
14. Given the table EMPLOYEE (Emp No, Name, 55
Salary, Designation, Dept Id) write cursor to select
the five highest paid employees from the table.
TEXT BOOKS:
1. Database Management Systems, Raghurama Krishnan, Johannes Gehrke, Tata Mc
Graw Hill, 3rd Edition
2. Database System Concepts, Silberschatz, Korth, McGraw Hill, V edition.
REFERENCE BOOKS:
1. Database Systems design, Implementation, and Management, Peter Rob & Carlos
Coronel 7th Edition.
2. Fundamentals of Database Systems, Elmasri Navrate, Pearson Education
3. Introduction to Database Systems, C.J. Date, Pearson Education
4. Oracle for Professionals, The X Team, S. Shah and V. Shah, SPD.
5. Database Systems Using Oracle: A Simplified guide to SQL and PL/SQL, Shah, PHI.
6. Fundamentals of Database Management Systems, M. L. Gillenson, Wiley Student Edition.
E- RESOURCES:
https://www.youtube.com/watch?v=q1kQ1vgW7D8
2
EXPERIMENT 1
Outcomes
3
4
EXPERIMENT 2
Draw E-R diagram and convert entities and relationships to relation table for a given
scenario.
Two assignments shall be carried out i.e., consider two different scenarios (eg.bank,
college)
5
This bank ER diagram illustrates key information about bank, including entities such as
branches, customers, accounts, and loans. It allows us to understand the relationships
between entities.
Bank Entity : Attributes of Bank Entity are Bank Name, Code and Address.
Code is Primary Key for Bank Entity.
Customer Entity : Attributes of Customer Entity are Customer_id, Name, Phone
Number and Address.
Customer_id is Primary Key for Customer Entity.
Branch Entity : Attributes of Branch Entity are Branch_id, Name and Address.
Branch_id is Primary Key for Branch Entity.
Account Entity : Attributes of Account Entity are Account_number, Account_Type and
Balance.
Account_number is Primary Key for Account Entity.
Loan Entity : Attributes of Loan Entity are Loan_id, Loan_Type and Amount.
Loan_id is Primary Key for Loan Entity.
There are some points for converting the ER diagram to the table:
7
In the given ER diagram, LECTURE, STUDENT, SUBJECT and COURSE forms
individual tables.
In the given ER diagram, student address is a composite attribute. It contains CITY, PIN,
DOOR#, STREET, and STATE. In the STUDENT table, these attributes can merge as an
individual column.
In the STUDENT table, Age is the derived attribute. It can be calculated at any point of
time by calculating the difference between current date and Date of Birth.
Using these rules, you can convert the ER diagram to tables and columns and assign the
mapping between the tables. Table structure for the given ER diagram is as below:
8
Figure: Table structure
-- Student Table
CREATE TABLE Student ( Student_ID INT PRIMARY KEY, Student_Name
VARCHAR(255), Date_of_Birth DATE, City VARCHAR(100), Pin INT,
Door_Number VARCHAR(50),Street VARCHAR(100), State VARCHAR(100));
-- Course Table
CREATE TABLE Course ( Course_ID INT PRIMARY KEY,Course_Name
VARCHAR(255));
-- Subject Table
CREATE TABLE Subject ( Subject_ID INT PRIMARY KEY,Subject_Name
VARCHAR(255));
-- Lecture Table
CREATE TABLE Lecture ( Lecture_ID INT PRIMARY KEY, Lecture_Name
VARCHAR(255));
9
EXPERIMENT 3
Relational Model
AIM
Relation Model represents attributes as columns in tables and different types of attributes like
composite, Multi-valued and Derived.
Objectives
Student will be able to learn the structural components of the relational data model. Student will be able
to learn relational models(tables).
Outcomes:
Source varchar2(20)
Destination varchar2(20)
CoachType varchar2(20)
10
COLUMNNAME DATATYPE CONSTRAINT
TICKET RELATION
11
EXPERIMENT 4.
AIM: The goal of a relational algebra query language is to fetch data from database or to perform various
operations like delete, insert, update on the data.
Relational algebra in DBMS is a procedural query language and main foundation of Relational Algebra is
the Relational Database and SQL.
Select
Project
Union
Set different
Cartesian product
FRENCH GERMAN
Mohan 02 Geeta 17
Vivek 13 Shyam 21
Geeta 17 Rohan 25
For the above relation, we select the tuples where student name =’vivek’
Query: σ (Student_Name=’vivek’)FRENCH
OUTPUT:
Student_Name Roll_Number
Vivek 13
12
2. Projection(π): It is used to project required column data from a relation.
OUTPUT:
Student_Name
Ram
Mohan
Vivek
Geeta
3. Union(U): Union operation in relational algebra is the same as union operation in set theory.
Student_Name
Ram
Mohan
Vivek
Geeta
Shyam
Rohan
Note: The only constraint in the union of two relations is that both relations must have the
same set of Attributes.
13
4.Set Difference(-): Set Difference in relational algebra is the same set difference operation as
in set theory.
Example: From the above table of FRENCH and GERMAN, Set Difference is used as follows
Query: π(Student_Name)FRENCH - π(Student_Name)GERMAN
OUTPUT:
Student_Name
Ram
Mohan
Note: The only constraint in the Set Difference between two relations is that both relations
must have the same set of Attributes.
5. Set Intersection(∩): Set Intersection in relational algebra is the same set intersection operation in set
theory.
Example: From the above table of FRENCH and GERMAN, the Set Intersection is used as follows
OUTPUT:
Student_Name
Vivek
Geeta
Note: The only constraint in the Set Difference between two relations is that both relations must
have the same set of Attributes.
6.Cross Product(X): Cross-product between two relations. Let’s say A and B, so the cross
product between A X B will result in all the attributes of A followed by each attribute of B.
Each record of A will pair with every record of B.
Example:
14
A B
ID Course
Name Age Sex
1 DS
Ram 14 M
2 DBMS
Sona 15 F AXB
Kim 20 M
Ram 14 M 1 DS
Ram 14 M 2 DBMS
Sona 15 F 1 DS
Sona 15 F 2 DBMS
Kim 20 M 1 DS
Kim 20 M 2 DBMS
Note: If A has ‘n’ tuples and B has ‘m’ tuples then A X B will have ‘ n*m ‘ tuples.
15
EXPERIMENT 5
Creating a Database:
Syntax
CREATE DATABASE databasename;
a) Select database
Syntax
USE DATABASE NAME
EX. USE testDB;
The BACKUP DATABASE statement is used in SQL Server to create a full back up of an existing SQL
database.
Syntax
BACKUP DATABASE databasename TO DISK = 'filepath';
Example:
16
BACKUP DATABASE testDB TO DISK = 'D:\backups\testDB.bak';
EXPERIMENT 6
Practicing DDL commands
Objectives
Student will be able to learn DDL Statements to Create and Manage Tables.
Outcomes
17
SQL-Structured Query Language
AIM : Creating Tables and altering the Tables
18
19
Mysql>Alter Table passenger3 add Foreign key(TicketNo) references Ticket(TicketNo);
20
Mysql>Alter table passenger drop foreign key fk1;
21
EXPERIMENT 7
DML COMMANDS
AIM: Create a DML Commands are used to manage data within the scheme objects.
Objectives:
Student will be able to learn commands that make changes in relational database and transaction
management.
Outcomes
Student gains the knowledge to perform transactions like updating, deleting, inserting and selecting
data from a data base.
DML Commands:
(0.03 sec)
(0.01 sec)
mysql> insert into Bus2 values(23,'Hyderabad','Kolkata'); Query OK, 1 row affected (0.03
sec)
mysql> insert into Bus2 values(45,'Tirupathi','Banglore'); Query OK, 1 row affected (0.03
sec)
mysql> insert into Bus2 values(34,'Hyderabad','Chennai'); Query OK, 1 row affected (0.03
sec)
22
mysql> select * from Passenger2; Empty set (0.00 sec)
24
UPDATE COMMAND ON BUS2 RELATION
mysql> Update Bus2 SET Source='Secundrabad' where BusNo=1234; Query OK, 1 row
25
DELETE COMMAND ON BUS2 RELATION
mysql> Delete from Bus2 where BusNo=1234; Query OK, 1 row affected (0.05 sec) mysql>
26
mysql> Delete from Bus2 where Source=’Secundrabad’; Query OK, 1 row affected
27
EXPERIMENT 8
For a given set of relation Schemas, Create tables and perform the following
Simple Queries, Simple Queries with Aggregate functions, Queries
with aggregate functions (group by
And having clause), Queries involving –Date Functions, String Functions,
Math Functions.
AIM :-
Queriesusingaggregatefunctions(COUNT,AVG,MIN,MAX,SU M),Group
by,Orderby,Having.
28
(ii) Countnumber of employee names from employeetable.
SQL> select count(ename) from emp; COUNT(ENAME)
-------------------------
7
(iii)Find
the Maximum age from employeetable.
SQL> select max(age) from emp;
MAX(AGE)
----------------- 44
(iv) Find the Minimum age from employeetable.
SQL> select min(age) from emp;
MIN(AGE)
---------------- 22
Display the Sum of age employeetable.
SQL> select sum(age) from emp;
SUM(AGE)
---------------- 220
Display the Average of age from Employeetable.
SQL> select avg(age) from emp; AVG(AGE)
---------------- 31.4285714
Create a View for age in employeetable.
SQL> create or replace view A as select age from emp where age<30; View created.
Displayviews
SQL> select * from A;
AGE
22
29
27
29
30
SQL> select ename,salary from emp where age<29 group by ename,salary having
salary<10000;
ENAME SALARY
----------- --------------
alex 7000
anu 9000
Date functions:
NOW()
Returns the current date and time.
Query:
SELECT NOW();
Output:
CURDATE()
Returns the current date.
Query:
SELECT CURDATE();
Output:
31
CURTIME()
Returns the current time.
Query:
SELECT CURTIME();
Output:
DATE()
Extracts the date part of a date or date/time expression. Example: For the below table
named ‘Test’
Id Name BirthTime
Prati
1996-09-26
k
32
EXTRACT()
Returns a single part of a date/time.
Syntax
EXTRACT(unit FROM date);
Several units can be considered but only some are used such as MICROSECOND,
SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR,
etc. And ‘date’ is a valid date expression. Example: For the below table named ‘Test’
Id Name BirthTime
Query:
SELECT Name, Extract(DAY FROM
BirthTime) AS BirthDay FROM Test;
Output:
Name Birthday
Prati
26
k
Query:
SELECT Name, Extract(YEAR FROM BirthTime)
AS BirthYear FROM Test;
Output:
Name BirthYear
Pratik 1996
Query:
SELECT Name, Extract(SECOND FROM
BirthTime) AS BirthSecond FROM Test;
Output:
33
Name BirthSecond
Prati
581
k
DATE_ADD()
Adds a specified time interval to a date.
Syntax:
DATE_ADD(date, INTERVAL expr type);
Where, date – valid date expression, and expr is the number of intervals we want to
add. and type can be one of the following: MICROSECOND, SECOND, MINUTE,
HOUR, DAY, WEEK, MONTH, QUARTER, YEAR, etc. Example: For the below
table named ‘Test’
Id Name BirthTime
DATE_SUB()
Subtracts a specified time interval from a date. The syntax for DATE_SUB is the
same as DATE_ADD just the difference is that DATE_SUB is used to subtract a
given interval of date.
String functions
Example:
+-------------------+
| concatenated_string |
+-------------------+
| Hello World |
34
+-------------------+
Example:
+------------------+
| uppercase_string |
+------------------+
| HELLO |
+------------------+
LOWER(): Converts a string to lowercase.
Example:
+------------------+
| lowercase_string |
+------------------+
| world |
+------------------+
LENGTH(): Returns the length of a string.
Example:
+--------------+
| string_length |
+--------------+
35
| 11 |
+--------------+
SUBSTRING(): Extracts a substring from a string.
Example:
+-------------------+
| extracted_substring |
+-------------------+
| World |
+-------------------+
TRIM(): Removes leading and trailing spaces from a string.
Example:
+---------------+
| trimmed_string |
+---------------+
| Hello World |
+---------------+
REPLACE(): Replaces occurrences of a substring within a string with another substring.
Example:
+------------------+
| replaced_string |
+------------------+
| Hi World |
36
+------------------+
EXPERIMENT 9
To create a view, a user must have the appropriate system privilege according to the specific
implementation.
You can include multiple tables in your SELECT statement in a similar way as you use them in a
normal SQL SELECT query
Example
Consider the CUSTOMERS table having the following records −
37
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 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
Following is an example to create a view from the CUSTOMERS table. This view would be used to
have customer name and age from the CUSTOMERS table.
The following code block has an example of creating same view CUSTOMERS_VIEW with the WITH CHECK
OPTION.
Updating a View
SQL > UPDATE CUSTOMERS_VIEW
SET AGE = 35
WHERE name = 'Ramesh';
39
DROPPING VIEWS
DROP VIEW CUSTOMERS_VIEW;
EXPERIMENT 10
Normalization of tables
Objectives:
Student will be able to learn to avoid problems that are associated with updating redundant data.
Outcomes:
Student gains the knowledge to build the database that does not have redundant data.
Normalization
A basic objective of the first normal form defined by Edgar Frank "Ted" Codd in 1970 was to
permit data to be queried and manipulated using a "universal data sub-language" grounded in
first-order logic. (SQL is an example of such a data sub-language, albeit one that Codd regarded
as seriously flawed.)
The objectives of normalization beyond 1NF (First Normal Form) were stated as follows
by Codd:
40
1. To free the collection of relations from undesirable insertion, update and deletion
dependencies;
2. To reduce the need for restructuring the collection of relations, as new types of data are
introduced, and thus increase the life span of application programs;
4. To make the collection of relations neutral to the query statistics, where these statistics are
liable to change as time goes by.
To each customer corresponds a repeating group of transactions. The automated evaluation of any
query relating to customers' transactions therefore would broadly involve two stages:
For example, in order to find out the monetary sum of all transactions that occurred in October
2003 for all customers, the system would have to know that it must first unpack the Transactions
group of each customer, then sum the Amounts of all transactions thus obtained where the Date
of the transaction falls in October 2003.
One of Codd's important insights was that this structural complexity could always be removed
completely, leading to much greater power and flexibility in the way queries could be formulated
41
(by users and applications) and evaluated (by the DBMS). The normalized equivalent of the
structure above would look like this:
Now each row represents an individual credit card transaction, and the DBMS can obtain the
answer of interest, simply by finding all rows with a Date falling in October, and summing their
Amounts. The data structure places all of the values on an equal footing, exposing each to the
DBMS directly, so each can potentially participate directly in queries; whereas in the previous
situation some values were embedded in lower-level structures that had to be handled specially.
Accordingly, the normalized design lends itself to general-purpose query processing, whereas the
unnormalized design does not.
A relation is in 1 NF if and only if all the domains(fields or columns) contain only atomic values(it
should not contain list of values or set of values)
A relation R is said to be in 2 NF if and only if it is in 1 NF(first normal form) and all non-prime
42
attributes are fully functional dependent on the primary key
"A relation R is in 3NF, if it is in Second normal form, and not any non-prime attribute of the
relation is transitively dependent on the primary key.“
A relation R is said to be in BCNF if and only if it is in 3 NF and all the determinants are
candidate keys
For a table to satisfy the Fourth Normal Form, it should satisfy the following two conditions
5NF is satisfied when all the tables are broken into as many tables as possible in order to avoid
redundancy.
The broken smaller tables must satisfy join dependency. Means after joining the smaller tables we
must get the original table without losing any data.
43
EXPERIMENT 11
Student will be able to learn to operate on multiple result sets to return a single result set. Student
will be able to learn to perform nested Queries, Correlated Queries
Q: Find the names of sailors who have reserved a red or a green boat.
Q: Find the names of sailors who have reserved both a red and a green boat.
44
SELECT S.sname
From Sailors S, Reserves R, Boats B
Where S.sid=R.sid AND R.bid=B.bid AND B.color=’red’
INTERSECT
SELECT S2.sname
From Sailors S2, Reserves R2, Boats B2
Where S2.sid=R2.sid AND R2.bid=B2.bid AND B2.color=’green’;
Q: Find the sids of all sailors who have reserved red boats but not green boats
Set-Comparison Operators
Q: Find sailors whose rating is better than some sailor called Horatio.
45
SQL Join statement is used to combine data or rows from two or more tables based
on a common field between them.
StudentCourse
46
A. 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.
47
C. RIGHT JOIN
RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows of the table on
the right side of the join and matching rows for the table on the left side of the join.
For the rows for which there is no matching row on the left side, the result-set will
contain null. RIGHT JOIN is also known as RIGHT OUTER JOIN.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;
48
RIGHT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output:
D. FULL JOIN
FULL JOIN creates the result-set by combining results of both LEFT JOIN and
RIGHT JOIN. The result-set will contain all the rows from both tables. For the rows
for which there is no matching, the result-set will contain NULL values.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;
HARSH 1
PRATIK 2
RIYANKA 2
DEEP 3
SAPTARHI 1
DHANRAJ NULL
ROHIT NULL
NIRAJ NULL
NULL 4
NULL 5
NULL 4
IN vs. EXISTS
IN Operator
The IN operator is used to retrieves results when the specified value matches any
value in a set of values or is returned by a subquery.
50
If we want to get all customer details whose occupation is either doctor, engineer,
or scientist, then we can use the statement as follows:
EXISTS Operator
EXISTS is a Boolean operator which checks the subquery result and returns an
either TRUE or FALSE value. It is used in combination with subquery and checks
whether a row is returned through this subquery or not. This operator returns TRUE if
the subquery returns single or multiple records. Otherwise, it gives a FALSE result
when no records are returned.
51
If we want to get all customer names and occupation who has placed at least one
order, then we can use the statement as follows:
52
EXPERIMENT 12
NESTED QUERIES
A nested query is a query that has another query embedded within it. The embedded query is
called a subquery. Outer and inner queries are completely independent of each other
53
Q: Find the names of sailors who have reserved boat 103.
Q: Find the names of sailors who have not reserved a red boat.
Q: Find the names of sailors who have reserved boat number 103.
54
55
EXPERIMENT 13
Write a PL/SQL Program using FOR loop to insert ten rows into a database table.
Output:
56
EXPERIMENT 14
Given the table EMPLOYEE (Emp No, Name, Salary, Designation, Dept Id) write
cursor to select the five highest paid employees from the table.
Declare Variables: Declare variables to hold employee information and loop counter.
sql:
sql:
OPEN employee_cursor
Fetch Records: Fetch records one by one until the desired number of records are
fetched or until there are no more records.
sql:
Process Records: Check if the fetched record's rank is within the top five. If it is, print
the employee information.
sql:
57
WHILE @@FETCH_STATUS = 0 AND @Rank <= 5 BEGIN PRINT 'EmpNo: ' +
CAST(@EmpNo AS VARCHAR(10)) + ', Name: ' + @Name + ', Salary: ' +
CAST(@Salary AS VARCHAR(10)) + ', Designation: ' + @Designation + ', DeptId: '
+ CAST(@DeptId AS VARCHAR(10)) FETCH NEXT FROM employee_cursor
INTO @EmpNo, @Name, @Salary, @Designation, @DeptId, @Rank END
Close Cursor: Close the cursor after fetching all required records.
sql:
58
EXPERIMENT 15
p_table_name: The name of the table where the tuple will be inserted.
p_integer_value: The integer value to be inserted into the table along with the string
value 'xx'.
Here's we can call this procedure:
sql
BEGIN
InsertTuple('your_table_name', 1);
END;
/
Output
Tuple inserted successfully.
59
EXPERIMENT 16
Queries for Creating Triggers
For example, a trigger can be invoked when a row is inserted into a specified table or when certain
table columns are being updated.
Explanation of syntax:
create trigger [trigger_name]: Creates a trigger with the trigger_name.
[before | after]: This specifies when the trigger will be executed.
{insert | update | delete}: This specifies the DML operation.
on [table_name]: This specifies the name of the table associated with the trigger.
[for each row]: The trigger will be executed for each row being affected.
[trigger_body]: This provides the operation to be performed when a trigger is activated
Example:
In such schema, create a trigger so that the total and percentage of specified marks are automatically
calculated and inserted whenever a student row is inserted.
60
sub1 integer,
sub2 integer,
sub3 integer,
total integer,
percentage real,
PRIMARY KEY (rollno) );
Above SQL statement will create a trigger in the student table in which whenever subjects marks are
entered,
before inserting the marks into the database, the trigger will compute the total marks & percentage and
insert with the marks.
61
In this way triggers can be created and executed in a database.
62