DBMS Lab Manual
DBMS Lab Manual
01
PART A
(PART A: TO BE REFFERED BY STUDENTS)
A.1 Aim: Explore various fundamental concepts of DBMS and its future prospective.
A.2 Prerequisite: -
A.3 Outcome:
After successful completion of this experiment students will be able to
A.4 Theory:
To define the database system, the following terminologies must be clarified:
1. File
2. Database
3. Database Management System (DBMS)
File consists of only one file or table, with each entry containing all the required data defined
within it. It is like a cabinet containing only one folder which has many pages in it, each page
containing all the information for that specific entry. This makes it easy for the user to know where
to find requested entries and all the data associated with them. As entire data are at one place,
retrieval of data is easy and fast. But the flat file suffers from the problem of data redundancy.
Suppose there is an order processing application which includes the name, address, and phone
number of a customer. If this customer has placed order for two items then there could be two
entries for this customer with his name, address and phone number. In other words, the file contains
redundant data, i.e. twice the name, address, and the phone number of the customer. If his address
is to be changed then it is to be changed at two places.
Database is a collection of interrelated files, while database management system is a collection of
database, database utilities (DBMS software) operated by user groups and administered by
database administrator.
Database is a collection of interrelated files. The conventional file processing system will lead to
excessive data redundancy and associated difficulties. But, in a database system which has an
integrated single database, all the problems of the conventional file processing system will be
minimized, even though the time taken to design and implement a robust database will be relatively
longer when compared to the design of files in the conventional file processing system. There will
be greater payoff by using the robust database which will offset the cost towards longer duration
of designing and implementing the database.
A database is a collection of interrelated data stored together with controlled redundancy to serve
one or more applications in an optimal way. The data are stored in such a way that they are
independent of the programs used by the people for accessing the data. The approach used in
adding the new data, modifying and retrieving the existing data from the database is common and
controlled one.
It is also defined as a collection of logically related data stored together that is designed to meet
information requirements of an organization. We can also define it as an electronic filing system.
A database management system is a software package that controls all access to database. When a
request to access database comes, it examines the request interprets it using some commands.
There are many different types of database users, out of which database administrator is
responsible for managing overall system and all other users of the system.
1. Define, create and organize a database: The DBMS establishes the logical relationships
among different data elements in a database.
2. Input data: It performs the function of entering the data into the database through an input
device with the help of the user.
3. Process data: It performs of manipulation and processing of the data stored in the database.
4. Maintain data integrity and security: It allows limited access of the database to authorized
users to maintain data integrity and security.
5. Query database: It provides information to the decision makers that they need to make
important decisions. The information is provided by querying the database using SQL.
User
Database (Hardware)
User
Data
Data
Data User
DBMS Users:
The users of a database system are:
5. What are various possible user roles available in the area of Databases? and what are
their responsibilities?
PART B
(PART B: TO BE COMPLETED BY STUDENTS)
(Students must submit the soft copy as per following segments within two hours of the
practical. The soft copy must be uploaded on the Blackboard or emailed to the concerned
lab in charge faculties at the end of the practical in case the there is no Black board access
available)
2. Justify the correctness of following statements: “The knowledge of DBMS is essential for
becoming the Data scientist ”
***************
Experiment No.02
PART A
(PART A: TO BE REFFERED BY STUDENTS)
A.1 Aim: Apply Data Definition language [DDL] on the relational model designed and apply
certain constrains on the relational model designed.
A.3 Outcome:
After successful completion of this experiment students will be able to
A.4 Theory:
SQL (pronounced "ess-que-el") stands for Structured Query Language. SQL is used to
communicate with a database. According to ANSI (American National Standards Institute), it is
the standard language for relational database management systems. SQL statements are used to
perform tasks such as update data on a database, or retrieve data from a database. Some common
relational database management systems that use SQL are: Oracle, Sybase, Microsoft SQL Server,
Access, Ingres, etc. Although most database systems use SQL, most of them also have their own
additional proprietary extensions that are usually only used on their system. However, the standard
SQL commands such as "Select", "Insert", "Update", "Delete", "Create", and "Drop" can be used
to accomplish almost everything that one needs to do with a database.
A relational database system contains one or more objects called tables. The data or information
for the database are stored in these tables. Tables are uniquely identified by their names and are
comprised of columns and rows. Columns contain the column name, data type, and any other
attributes for the column. Rows contain the records or data for the columns. Here is a sample table
called "weather". City, state, high, and low are the columns. The rows contain the data for this
table:
Weather
city state high low
Phoenix Arizona 105 90
Tucson Arizona 101 92
Flagstaff Arizona 88 69
San Diego California 77 60
New
Albuquerque 80 72
Mexico
The create table statement is used to create a new table. Here is the format of a simple create
tablestatement:
To create a new table, enter the keywords create table followed by the table name, followed by
an open parenthesis, followed by the first column name, followed by the data type for that column,
followed by any optional constraints, and followed by a closing parenthesis. It is important to make
sure you use an open parenthesis before the beginning table, and a closing parenthesis after the
end of the last column definition. Make sure you seperate each column definition with a comma.
All SQL statements should end with a ";".
The table and column names must start with a letter and can be followed by letters, numbers, or
underscores - not to exceed a total of 30 characters in length. Do not use any SQL reserved
keywords as names for tables or column names (such as "select", "create", "insert", etc).
Data types specify what the type of data can be for that particular column. If a column called
"Last_Name", is to be used to hold names, then that particular column should have a "varchar"
(variable-length character) data type.
char(size) Fixed-length character string. Size is specified in parenthesis. Max 255 bytes.
number(size) Number value with a max number of column digits specified in parenthesis.
Number value with a maximum number of digits of "size" total, with a maximum
number(size,d)
number of "d" digits to the right of the decimal.
Constraints:
What are constraints? When tables are created, it is common for one or more columns to
have constraints associated with them. A constraint is basically a rule associated with a column
that the data entered into that column must follow. For example, a "unique" constraint specifies
that no two records can have the same value in a particular column. They must all be unique. The
other two most popular constraints are "not null" which specifies that a column can't be left blank,
and "primary key". A "primary key" constraint defines a unique identification of each record (or
row) in a table.
The PRIMARY KEY constraint uniquely identifies each record in a database table. Primary keys
must contain UNIQUE values. A primary key column cannot contain NULL values. Most tables
should have a primary key, and each table can have only ONE primary key.
or
or adding primary key constraint using alter command – can be used only if table has been
already created and during creation time constraint was not given.
2. Unique constraint:
The UNIQUE constraint uniquely identifies each record in a database table. The UNIQUE and
PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of
columns. A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.
Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY
constraint per table.
Or
create table person(p_id number(4) primary key, pname varchar(40), mobile_no number(10),
address varchar(100), unique(mobile_no));
or adding unique key using alter command – can be used only if table is already created and at the
time of creation of table constraint was not applied.
The NOT NULL constraint enforces a column to NOT accept NULL values. The NOT NULL
constraint enforces a field to always contain a value. This means that you cannot insert a new
record, or update a record without adding a value to this field.
create table person(p_id primary key, pname varchar(4) not null, mobile_no number(10), address
varchar(100));
4. Foreign key:
A FOREIGN KEY in one table points to a PRIMARY KEY in another table. Let's illustrate the
foreign key with an example. Look at the following two tables:
1 77895 3
2 44678 3
3 22456 2
4 24562 1
Note that the "P_Id" column in the "Orders" table points to the "P_Id" column in the "Persons"
table. The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table. The
"P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table. The FOREIGN
KEY constraint is used to prevent actions that would destroy links between tables. The FOREIGN
KEY constraint also prevents invalid data from being inserted into the foreign key column, because
it has to be one of the values contained in the table it points to.
create table orders(o_id number(3) primary key, orderno number not null, p_id foreign key
references persons(p_id));
Adding foreign key with alter table command: Applicable only if table is already created and
at the time of creation foreign key was not given.
Syntax:
5. ticket_header: fleet_id number(5), ticket_no number(5), doi date, dot date, time_travel
char(8), board_place varchar(20), origin varchar(40), destination varchar(40), adult
number(3), children number(3), total_fare number(7,2), route_id number(5)
fleet_id foreign key, ticket_no primary key, doi- not null, dot-not null, route_id – foreign
key
6. ticket_detail: ticket_no number(5), name varchar(20), sex char(1), age number(3), fare
number(5,2)
1. Write a query to increase size of category description column in category header table
from varchar(20) to varchar(50).
2. Create a table Student_MPSTME with columns student number, student name, student
address, student phone number with appropriate data types.
3. Write a query to add primary key column to above created Student_MPSTME table.
4. Write a query to create new table Student_NMIMS with columns Student number,
Student name selected from table Student_MPSTME.
7. Write a query to delete column student phone number from Stu_MPSTME table.
(Students must submit the soft copy as per following segments within two hours of the
practical. The soft copy must be uploaded on the student portal or emailed to the concerned
lab in charge faculties at the end of the practical in case the there is no student portal access
available)
B.1 Tasks given in PART A to be completed here (Students must write the answers of the
task(s) given in the PART A )
B.1.1 : Execution of each SQL query used to complete the task given in PART A :
B.3 Conclusion:
(Students must write the conclusive statements as per the attainment of individual outcomes listed above and
learning/observation noted in section B.2)
***************
Experiment No.03
PART A
(PART A: TO BE REFFERED BY STUDENTS)
A.1 Aim: Apply Data Manipulation language [DML] on the relational model designed and
apply certain constrains on the relational model designed.
A.3 Outcome:
After successful completion of this experiment students will be able to
A.4 Theory:
Data Manipulation Language (DML) statements are used for managing data in database. DML
commands are not auto-committed. It means changes made by DML command are not permanent
to database, it can be rolled back. DML is short name of Data Manipulation Language which deals
with data manipulation, and includes most common SQL statements such as SELECT, INSERT,
UPDATE, DELETE etc, and it is used to store, modify, retrieve, delete and update data in database.
1. SELECT:
Syntax:
select column_name(s) from table_name; selects only particular column(s) and all
rows
Or
Select * from table_name selects all columns and all rows of the table mentioned
2. INSERT:
Syntax:
Or
insert into table_name values(value1, value2, value3, ….. valuen) used when you
want to insert values into all columns of the table.
3. UPDATE:
Syntax:
Update table_name set column= value; used when you want to update all the rows
for the particular column.
Or
4. DELETE:
Syntax:
delete from table_name; - used when you want to delete all the rows of the table.
Or
A.5 Task: insert below values into table and apply queries
category_header
route_header
Place Header:
Fleet Header:
Ticket Header:
Ticket Detail:
Route Detail:
Queries:
a. Display all records of Category Header table.
b. Display place name and place address.
c. Check what will be the fare if it is incremented by 10 rs for each route. (Give new
column alias as new_fare).
d. Display distinct destination from route header table. [Hint : Use ‘distinct’ keyword]
e. Display structure of table route detail. [Hint; Use ‘desc’]
f. Gautam’s fare got increased by 1 unit. Make changes in the appropriate table.
g. Write a query to change age of ‘Anand’ from 28 to 30.
h. Write a query to insert a new record into Route_Detail table with details as below:
a. Route_id: 105 , Place_id : 01, NonStop: S
i. Write a query to delete row inserted above from Route_Detail table.
PART B
PART B: TO BE COMPLETED BY STUDENTS)
(Students must submit the soft copy as per following segments within two hours of the
practical. The soft copy must be uploaded on the Student Portal or emailed to the concerned
lab in charge faculties at the end of the practical in case the there is no Black board access
available)
B.1 Tasks given in PART A to be completed here (Students must write the answers of the
task(s) given in the PART A )
B.1.1 : Execution of each SQL query used to complete the task given in PART A :
B.2 Conclusion:
(Students must write the conclusion as per the attainment of individual outcome listed above and
learning/observation noted in section B.3)
A.1 Aim: To design Entity Relationship and relational model for the given case study.
A.2 Prerequisite: - Basic concepts of database, data models like ER-models and relational
model.
A.3 Outcome:
After successful completion of this experiment, students will be able to
7. Explain the basics of ER/EER Diagram and its importance in database design.
8. Design ER diagram for the case study given.
9. Convert the ER diagram into equivalent relational model.
10. Enlist the difference between ER and Relational model.
A.4 Theory:
Summary of symbols used in ER notation:
Reduction of ER model to relational model:
Rules:
Build a table for each relationship set if necessary (depending upon cardinality)
Make a column in the table for each attribute in the entity set
Construct a table with one column for each attribute in the weak entity set
Augment one extra column on the right side of the table, put in there the
primary key of the Strong Entity Set (the entity set that the weak entity set is
depending on)
Primary Key of the weak entity set = Discriminator + foreign key
Build a table with two columns, one column for each participating entity set’s
primary key. Add successive columns, one for each descriptive attributes of
the relationship set (if any).
For one-to-one relationship with one entity set having total participation
Augment one extra column on the right side of the table of the entity set with
total participation, put in there the primary key of the entity set without
complete participation as per to the relationship.
Augment one extra column on the right side of the table of the entity set on
the “many” side, put in there the primary key of the entity set on the “one”
side as per to the relationship.
Primary key of this new schema is the union of the foreign keys of both entity
sets.
Representing Generalization\Specialization:
create a table for each super class entity set according to normal
entity set translation method.
Create a table for each subclass entity set with a column for each of
the attributes of that entity set plus one for each attributes of the
primary key of the super class entity set
This primary key from super class entity set is also used as the
primary key for this new table
Create a table for each subclass entity set include all attributes of that
subclass entity set and attributes of the superclass entity set
A.5.1 Task1
Draw an ER diagram for given case study and convert it into relational model:
We need to create a database schema design based on the following (simplified) requirements of
the COMPANY Database:
1. The company is organized into DEPARTMENTs. Each department has a name, number
and an employee who manages the department. We keep track of the start date of the
department manager. A department may have several locations.
2. Each department controls a number of PROJECTs. Each project has a unique name, unique
number and is located at a single location.
3. There are two types of employees in company- technical employee and non-technical
employee (administrative staff).
4. We store each EMPLOYEE’s Aadhar number, address, salary, sex, and birthdate.
5. Each technical employee works for one department but may work on several projects.
6. We keep track of the number of hours per week that a technical employee currently works
on each project.
7. The technical employee gains score based on work done. The latest score of each technical
employee is stored.
11. For each dependent, we keep track of their name, sex, birthdate, and relationship to the
employee.
******************
PART B
(PART B: TO BE COMPLETED BY STUDENTS)
(Students must submit the soft copy as per following segments within two hours of the
practical. The soft copy must be uploaded on the student portal or emailed to the concerned
lab in charge faculties at the end of the practical in case the there is no Black student portal
access available)
Write your observation related to difference between ER model and Relational Model.
B.3 Conclusion:
(Students must write the conclusive statements as per the attainment of individual outcomes listed above and
learning/observation noted in section B.2)
8. Justify the statement, “The MISTAKES made in ER diagram badly affects the complete
database design”
9. Design ER diagram for library management system considering following entities and its
interrelationships: Books, Students, Book_Issued, Books_returned
***************
Experiment No.05
PART A
(PART A: TO BE REFFERED BY STUDENTS)
A.1 Aim: Apply DML select statement with where clause, and, or, not, in, between and like
clauses.
A.3 Outcome:
After successful completion of this experiment students will be able to
A.4 Theory:
The select statement is used to view records from the database. In order to view only specific
records, select statement is used with where clause. The SQL WHERE clause is used to specify
a condition while fetching the data from single table or joining with multiple tables. If the given
condition is satisfied then only it returns specific value from the table. You would use WHERE
clause to filter the records and fetching only necessary records.
The WHERE clause is not only used in SELECT statement, but it is also used in UPDATE,
DELETE statement, etc.,
SELECT column_name,column_name
FROM table_name
WHERE column_name operator value;
Example:
The SQL requires single quotes around text values (as shown in above example). However
numeric fields should not be enclosed in quotes.
Example:
Operator Description
= Equal
Example:
The AND operator allows the existence of multiple conditions in an SQL statement's WHERE
clause.
FROM table_name
You can combine N number of conditions using AND operator. For an action to be taken by the
SQL statement, whether it be a transaction or query, all conditions separated by the AND must be
TRUE.
Example:
select employee_id, name, salary from employee where salary >2000 and age <25;
The OR operator is used to combine multiple conditions in an SQL statement's WHERE clause.
FROM table_name
You can combine N number of conditions using OR operator. For an action to be taken by the
SQL statement, whether it be a transaction or query, only any ONE of the conditions separated by
the OR must be TRUE.
Example:
The IN operator:
The IN operator allows you to specify multiple values in a WHERE clause.
SQL IN syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...);
Example:
The following SQL statement selects all customers with a City of "Paris" or "London":
The BETWEEN operator is used to select values within a range. The values can be number, text
or dates.
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Example:
The following SQL statement selects all products with a price BETWEEN 10 and 20:
To display the products outside the range of the previous example, use NOT BETWEEN:
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
In SQL, wildcard characters are used with the SQL LIKE operator. SQL wildcards are used to
search for data within a table.
Wildcard Description
The following SQL statement selects all customers with a City starting with "ber":
The following SQL statement selects all customers with a City containing the pattern "es":
The following SQL statement selects all customers with a City starting with any character,
followed by "erlin":
The following SQL statement selects all customers with a City starting with "L", followed by any
character, followed by "n", followed by any character, followed by "on":
category_header
route_Header
Place Header:
Fleet Header:
Ticket Header:
Ticket Detail:
Route Detail:
2. Display only those rows from route_header whose origin begins with ‘m’.
3. Display only those rows whose fare ranges between 30 and 50.
4. Display the fare and the origin for route_no which are greater than 15.
9. Find out category whose category description starts with ‘s’ and ends with ‘t’.
12. Display details of those routes whose fare is less than 70 and distance greater than 120.
13. Find out details of tickets issued to female travelers and with age greater than 10.
14. What will be fare of each route after incrementing fare by 10 percent?
16. Display those routes for which origin is “Madras” and distance is greater than 300 or
destination is “Madras” and distance less than 300.
17. Create a new table temp_MPSTME with columns as place_id, place_name and
place_address (column data type and size must be same as columns of place_header
table).
18. Write a query to insert records into temp_MPSTME table from place_header table. Only
those records are to be selected for which place_id is between 1 to 4 and place_name starts
from ‘m’.
PART B
(PART B: TO BE COMPLETED BY STUDENTS)
(Students must submit the soft copy as per following segments within two hours of the
practical. The soft copy must be uploaded on the student portal or emailed to the concerned
lab in charge faculties at the end of the practical in case the there is no student portal access
available)
B.1 Tasks given in PART A to be completed here (Students must write the answers of the
task(s) given in the PART A )
B.1.1 : Execution of each SQL query used to complete the task given in PART A :
B.3 Conclusion:
(Students must write the conclusive statements as per the attainment of individual outcomes listed above and
learning/observation noted in section B.2)
A.1 Aim: To apply order by clause and concept of different types of Joins for solving queries.
A.2 Prerequisite:
A.3 Outcome:
After successful completion of this experiment students will be able to
7. Apply knowledge of relational algebra and structural query language to retrieve and
manage data in relational databases.
A.4 Theory:
Order By Clause:
An ORDER BY clause allows you to specify the order in which rows appear in the result set. The
SQL ORDER BY clause is used to sort the records in the result set for a SELECT statement.
Example:
Sorting above table using order by clause using salary (SAL) column in ascending order.
Query:
Result:
Sorting above table using order by clause using salary (SAL) column in ascending order.
Query:
select * from emp order by SAL desc;
Result:
102 b - - - - - 30
7839 KING PRESIDENT - 11/17/1981 5000 - 10
7788 SCOTT ANALYST 7566 12/09/1982 3000 - 20
7902 FORD ANALYST 7566 12/03/1981 3000 - 20
7566 JONES MANAGER 7839 04/02/1981 2975 - 20
7698 BLAKE MANAGER 7839 05/01/1981 2850 - 30
7782 CLARK MANAGER 7839 06/09/1981 2450 - 10
7499 ALLEN SALESMAN 7698 02/20/1981 1600 300 30
7844 TURNER SALESMAN 7698 09/08/1981 1500 0 30
7934 MILLER CLERK 7782 01/23/1982 1300 - 10
7521 WARD SALESMAN 7698 02/22/1981 1250 500 30
7654 MARTIN SALESMAN 7698 09/28/1981 1250 1400 30
7876 ADAMS CLERK 7788 01/12/1983 1100 - 20
101 a b 7839 04/01/2004 1000 10 20
7900 JAMES CLERK 7698 12/03/1981 950 - 30
7369 SMITH CLERK 7902 12/17/1980 800 - 20
The table can also be sorted using column number or column position. While sorting we can
specify whether to display null values first or last using “NULL FIRST” or “NULL LAST” clause.
For example in EMP table column position of SALARY column is 6. Using column position table
will be sorted as below:
Example:
Result:
Joins:
JOINS are used to retrieve data from multiple tables. A JOIN is performed whenever two or more
tables are joined in a SQL statement.
There are 4 different types of Oracle joins:
INNER JOIN:
It is the most common type of join. Oracle INNER JOINS return all rows from multiple
tables where the join condition is met.
Syntax
Example:
Supplier:
supplier_id supplier_name
10000 IBM
10002 Microsoft
10003 NVIDIA
Orders:
order_id supplier_id order_date
Applying inner join between supplier and orders table in order to fetch supplier id, supplier
name and order date from both tables supplier and orders.
Syntax:
Result:
Old Syntax: In earlier version of Oracle inner joins were specified as below:
In order to join above three tables to fetch employee last name, department in which employee is
working and the city where department is located below query will be used.
Another type of join is called an Oracle LEFT OUTER JOIN. This type of join returns all rows
from the LEFT-hand table specified in the ON condition and only those rows from the other table
where the joined fields are equal (join condition is met).
Syntax
SELECT columns FROM table1 LEFT [OUTER] JOIN table2 ON table1.column = table2.column;
Visual Illustration
In this visual diagram, the Oracle LEFT OUTER JOIN returns the shaded area:
The Oracle LEFT OUTER JOIN would return the all records from table1 and only those records
from table2 that intersect withtable1.
Example
This LEFT OUTER JOIN example would return all rows from the suppliers table and only those
rows from the orders table where the joined fields are equal.
If a supplier_id value in the suppliers table does not exist in the orders table, all fields in the orders
table will display as <null> in the result set.
Result:
Syntax
SELECT columns FROM table1 RIGHT [OUTER] JOIN table2 ON table1.column = table2.column;
In some databases, the RIGHT OUTER JOIN keywords are replaced with RIGHT JOIN.
Visual Illustration
In this visual diagram, the Oracle RIGHT OUTER JOIN returns the shaded area:
The Oracle RIGHT OUTER JOIN would return the all records from table2 and only those
records from table1 that intersect with table2.
Example
This RIGHT OUTER JOIN example would return all rows from the orders table and only those
rows from the suppliers table where the joined fields are equal.
If a supplier_id value in the orders table does not exist in the suppliers table, all fields in the
suppliers table will display as <null>in the result set.
Syntax
SELECT columns FROM table1 FULL [OUTER] JOIN table2 ON table1.column = table2.column;
In some databases, the FULL OUTER JOIN keywords are replaced with FULL JOIN.
Visual Illustration
In this visual diagram, the Oracle FULL OUTER JOIN returns the shaded area:
The Oracle FULL OUTER JOIN would return the all records from both table1 and table2.
Natural Join:
The natural join clause is based on all columns in the two tables that have the same name. It
selects rows from the two tables that have equal values in all matched columns.
Syntax:
Query:
Result:
category_header
route_Header
Place Header:
Fleet Header:
Ticket Header:
Ticket Detail:
Route Detail:
Queries:
1. Display all routes sorted using distance (descending order).
2. Display details of those routes for which category description is “Delux”.
3. Find out details of ticket issued to passenger “Charu”.
4. Find out places for which routes are non stop.
5. Display all rows from route header and only matching rows from route detail.
6. Find out common route id’s those are present in route_header and route_detail.
7. Find out names of passengers who travel through routes with origin as ‘Madurai’
and destination as ‘Madras’.
8. Find out fleets which passes through routes which are not non stop.
9. Insert into category_header table new row with below details:
Cat code: 05 cat description: fast
10. Display cat_code, cat_description and all route details for all the categories, whether
route available for category or not.
11. Find out details of those tickets for which origin of one ticket is same as destination
of another ticket.
PART B
(PART B: TO BE COMPLETED BY STUDENTS)
(Students must submit the soft copy as per following segments within two hours of the
practical. The soft copy must be uploaded on the student portal or emailed to the concerned
lab in charge faculties at the end of the practical in case the there is no student portal access
available)
B.3 Conclusion:
(Students must write the conclusion as per the attainment of individual outcome listed above and
learning/observation)
Experiment No.07
PART A
A.1 Aim: To implement group by, having clause, aggregate functions, sub queries, set
operation and views for solving queries.
A.2 Prerequisite:
A.3 Outcome:
After successful completion of this experiment students will be able to
8. Apply knowledge of relational algebra and structural query language to retrieve and
manage data in relational databases.
A.4 Theory:
Aggregate Functions:
Aggregate functions are statistical functions such as count, min, max etc. They are used to compute
a single value from a set of attribute values of a column:
avg Computes average value for a column (only applicable to the data type number)
Note: avg, min and max ignore tuples that have a null value for the specified attribute, but
count considers null values.
Grouping:
We have seen how aggregate functions can be used to compute a single value for a column. Often
applications require grouping rows that have certain properties and then applying an aggregate
function on one column for each group separately. For this, SQL provides the clause group by
<group column(s)>. This clause appears after the where clause and must refer to columns of tables
listed in the from clause.
Syntax:
select <column(s)> from <table(s)> where <condition> group by <group column(s)> [having
<group condition(s)>];
Those rows retrieved by the selected clause that have the same value(s) for <group column(s)> are
grouped. Aggregations specified in the select clause are then applied to each group separately. It
is important that only those columns that appear in the <group column(s)> clause can be listed
without an aggregate function in the select clause!
Example: For each department, we want to retrieve the minimum and maximum salary.
Rows from the table EMP are grouped such that all rows in a group have the same department
number. The aggregate functions are then applied to each such group.
We thus get the following query result:
DEPTNO MIN(SAL) MAX(SAL)
10 1300 5000
20 800 3000
30 950 2850
Rows to form a group can be restricted in the where clause. For example, if we add the condition
where JOB = ’CLERK’, only respective rows build a group. The query then would retrieve the
minimum and maximum salary of all clerks for each department. Note that is not allowed to specify
any other column than DEPTNO without an aggregate function in the select clause since this is
the only column listed in the group by clause (is it also easy to see that other columns would not
make any sense).
Once groups have been formed, certain groups can be eliminated based on their properties, e.g., if
a group contains less than three rows. This type of condition is specified using the having clause.
As for the select clause also in a having clause only <group column(s)> and aggregations can be
used.
Example: Retrieve the minimum and maximum salary of clerks for each department having
more than three clerks.
select DEPTNO, min(SAL), max(SAL) from EMP where JOB = ’CLERK’ group by DEPTNO
having count(job) > 3;
Sub Queries:
Up to now we have only concentrated on simple comparison conditions in a where clause, i.e., we
have compared a column with a constant or we have compared two columns. As we have already
seen for the insert statement, queries can be used for assignments to columns. A query result can
also be used in a condition of a where clause. In such a case the query is called a subquery and the
complete select statement is called a nested query.
In a where clause conditions using subqueries can be combined arbitrarily by using the logical
connectives and and or.
Example: List the name and salary of employees of the department 20 who are leading
a project that started before December 31, 1990:
select ENAME, SAL from EMP where EMPNO in (select PMGR from PROJECT
where PSTART < ’31-DEC-90’) and DEPTNO =20;
Explanation: The subquery retrieves the set of those employees who manage a project that started
before December 31, 1990. If the employee working in department 20 is contained in this set (in
operator), this tuple belongs to the query result set.
Example: List all employees who are working in a department located in BOSTON:
select * from EMP where DEPTNO in (select DEPTNO from DEPT where LOC =
’BOSTON’);
The subquery retrieves only one value (the number of the department located in Boston). Thus it
is possible to use “=” instead of in. As long as the result of a subquery is not known in advance,
i.e., whether it is a single value or a set, it is advisable to use the in operator.
Conditions of the form <expression> <comparison operator> [any|all] <subquery> are used to
compare a given <expression> with each value selected by <subquery>.
• For the clause any, the condition evaluates to true if there exists at least on row selected by the
subquery for which the comparison holds. If the subquery yields an empty result set, the condition
is not satisfied.
• For the clause all, in contrast, the condition evaluates to true if for all rows selected by the
subquery the comparison holds. In this case the condition evaluates to true if the subquery does
not yield any row or value.
Example: Retrieve all employees who are working in department 10 and who earn at least
as much as any (i.e., at least one) employee working in department 30:
select * from EMP where SAL >= any (select SAL from EMP where DEPTNO = 30)
and DEPTNO = 10;
Note: Also in this subquery no aliases are necessary since the columns refer to the innermost
from clause.
Example: List all employees who are not working in department 30 and who earn more than
all employees working in department 30:
select * from EMP where SAL > all (select SAL from EMP where DEPTNO = 30) and DEPTNO
<> 30;
SET OPERATION
According to SQL Standard there are following Set operator types:
Union [DISTINCT];
Union All;
Intersect [DISTINCT];
Intersect All
Minus
Some facts:
UNION and INTERSECT operators are commutative, i.e. the order of queries is not
important; it doesn't change the final result.
Minus operator is NOT commutative, it IS important which query is first, which second
using Minus operator.
UNION, Minus and INTERSECT used without anything or with DISTINCT returns only
unique values. This is especially interesting when one query returning many nonunique
rows is UNIONED to another query returning zero rows. The final result contains fewer
rows than first query.
These usually are most widely used set operators. Quite many times one cannot get all the
result from one Select statement. Then one of the UNIONS can help. Graphically UNION can
be visualised using Venn diagrams. Assume we have two row sets.
Then Query1 UNION Query2 would be as follows. Grey area shows resultant set.
Example of Union:
The First table,
ID Name
1 John
2 adam
2 Adam
3 Chirag
ID Name
1 John
2 Adam
3 Chirag
Union All:
This operation is similar to Union. But it also shows the duplicate rows.
1 John
2 Adam
2 Adam
3 Chirag
Intersect:
Intersect operation is used to combine two SELECT statements, but it only returns the records
which are common from both SELECT statements. In case of Intersect the number of columns
and data type must be same.
For the given above tables (In example of Union), intersect query will be:
select * from First INTERSECT select * from second
The result table will be as below:
ID Name
2 Adam
Minus:
Minus operation combines result of two Select statements and return only those results which
belong to first set of result.
For the above tables (given in example of Union), Minus query will be:
select * from First MINUS select * from second
1 John
DCL command:
Data Control Language(DCL) is used to control privilege in Database. To perform any operation
in the database, such as for creating tables, sequences or views we need privileges. Privileges are
of two types,
System : creating session, table etc are all types of system privilege.
Object : any command or query to work on tables comes under object privilege.
Example:
To give access of table faculty to user U2 command will be:
grant all on faculty to U2;
To revoke access of table faculty from user U2 command will be:
Revoke all on faculty from U2;
Views:
After a table is created, it may become necessary to prevent all users from accessing all columns
of a table, for data security reasons. This would mean creating several tables having the appropriate
number of columns and assigning specific users to each table as required. But this will increase
redundancy. To reduce redundant data, oracle allows the creation of an object called a view. A
view takes the output of a query and treats it as a table, therefore view can be thought of as a ‘stored
query’ or a ‘virtual table’. The tables upon which views are based are known as base tables.
The syntax for creating a view:
If we don’ t want user to update data of table through views we can create read only views
as below:
create or replace emp_vw as select * from emp with read only;
If we now fire query as below then it will give an error:
update emp_vw set sal=10000 where empno=7456;
category_header
route_Header
Place Header:
Fleet Header:
Ticket Header:
Ticket Detail:
Route Detail:
Queries:
1. Give average of the total fare.
2. Give the total collection of fare.
3. Which bus runs for minimum distance?
4. Give the total number of people who have traveled so far group by ticket
number.
5. Find out total fare for routes with same origin.
6. Find out total fare for routes with origin as madras.
7. Calculate average fare for each ticket.
8. Find out details of fleets that run on route number 33 or 25.
9. Count how many male or female passengers have travelled till now.
10. Count total number of routes for each category except category 02.
11. Find out place names for which nonstop buses run.
12. Find out details of tickets from ticket header having more than one passenger.
13. Find out details of route having category code same as category code of a route
having maximum distance.
14. Display distinct ticket number from both ticket_header and ticket_detail.
15. Display all ticket numbers from both ticket_header and ticket_detail.
16. Display only common fleet_id’s that are present in fleet_header and
ticket_header.
17. Select distinct route_id from route_header and not in route_detail using both the
tables.
18. Display distinct route_id’s from route header and route_detail.
19. Display all category_code from route_header and category_header.
20. Display only common place_id’s that are present in place_header and
route_detail.
21. Select common ticket_numbers from ticket_header and ticket_detail where the
route_id’s are smaller than the route_id which belong to place id as 01.
22. Select unique fleet_id’s from ticket_header and fleet_header where the route_id
is greater than route_id’s in route_header which belongs to the category_code as
01.
23. Create read only view route_vw on table route_header to display route_id,
origin and destination.
24. Try to update any record of view route_vw and explain error message.
25. Create view route_vw2 on table route_header with columns route_no, cat_code,
orgin and destination.
26. Display records of view route_vw2.
27. Try to insert record into view route_vw2 and state the output if possible else
explain error message.
28. Create view route_category_vw to display those routes which belong to category
‘delux’.
PART B
(Students must submit the soft copy as per following segments within two hours of the
practical. The soft copy must be uploaded on the Portal or emailed to the concerned lab in
charge faculties at the end of the practical in case the there is no Portal access available)
c. Find distributor who has never supplied any item (using sub query).
d. Count total number of items of each colour.
e. Count number of items supplied by each distributor.
2. Justify the statement, “Views can be used for better manipulation of the given table”
4. Explain at least one real life Application of views to solve any real life problem.
B.3 Conclusion:
(Students must write the conclusion as per the attainment of individual outcome listed above and
learning/observation)
Experiment No.08
PART A
A.1 Aim: To implement advanced aggregation features like ranking, partition by, Top-N queries,
Rollup and Cube Operators.
A.2 Prerequisite:
A.3 Outcome:
After successful completion of this experiment, students will be able to
A.4 Theory:
The aggregation support in SQL, which we have seen earlier, is quite powerful and handles most
common tasks with ease. However, some tasks are hard to implement efficiently with the basic
aggregation features.
1. Ranking and Partition By: RANK calculates the rank of a value in a group of values. The
return type is NUMBER. Rows with equal values for the ranking criteria receive the same rank.
As an aggregate function, RANK calculates the rank of a hypothetical row identified by the
arguments of the function with respect to a given sort specification. The arguments of the function
must all evaluate to constant expressions within each aggregate group, because they identify a
single row within each group. The constant argument expressions and the expressions in
the ORDER BY clause of the aggregate match by position. Therefore, the number of arguments
must be the same and their types must be compatible.
As an analytic function, RANK computes the rank of each row returned from a query with respect
to the other rows returned by the query, based on the values of the value_exprs in
the order_by_clause.
For example:
3. Top-N analysis: Top-N queries provide a method for limiting the number of rows returned
from ordered sets of data.
• Top-N queries ask for the n largest or smallest values of a column. For example:
• Both largest values and smallest values sets are considered Top-N queries.
• They are extremely useful when you want to return the top or bottom "N" number of rows
from a set or when you are paging through data.
General Syntax:
FROM table
4. Rollup and Cube Operator: ROLLUP and CUBE are simple extensions to
the SELECT statement's GROUP BY clause. ROLLUP creates subtotals at any level of
aggregation needed, from the most detailed up to a grand total. CUBE is an extension similar
to ROLLUP, enabling a single statement to calculate all possible combinations of
subtotals. CUBE can generate the information needed in cross-tab reports with a single query. To
enhance performance, both CUBE and ROLLUP are parallelized: multiple processes can
simultaneously execute both types of statements.
category_header
route_Header
Place Header:
Fleet Header:
Ticket Header:
Ticket Detail:
Route Detail:
Queries:
1. Find the rank of a record with route id 105 as per the descending order of distance
in a route_header table.
2. Find out first three routes having largest distance.
3. Find out first three routes having lowest distance.
4. Find out rank of the tickets in the ascending order of the age of the passenger.
5. Find out rank of the routes for each category in the ascending order of distance
6. Find out total fare for all routes and total fare for each category.
7. Display sum of fare of all tickets, sum of fare for each ticket and sum of fare for
each sex.
PART B
(Students must submit the soft copy as per following segments within two hours of the
practical. The soft copy must be uploaded on the Portal or emailed to the concerned lab in
charge faculties at the end of the practical in case the there is no Portal access available)
B.2 Conclusion:
(Students must write the conclusion as per the attainment of individual outcome listed above and
learning/observation)
Experiment No.09
PART A
(PART A: TO BE REFFERED BY STUDENTS)
A.1 Aim: To Study commands of transaction management, commands like Commit, Rollback
and concept of concurrency control.
A.2 Prerequisite:
A.3 Outcome:
After successful completion of this experiment students will be able to
A.4 Theory:
Transaction:
A transaction is a logical unit of work that contains one or more SQL
statements. A transaction is an atomic unit. The effects of all the SQL
statements in a transaction can be either all committed (applied to the
database) or all rolled back (undone from the database).
A transaction begins with the first executable SQL statement. A
transaction ends when it is committed or rolled back, either explicitly with
a COMMIT or ROLLBACK statement or implicitly when a DDL
statement is issued.
To illustrate the concept of a transaction, consider a banking database.
When a bank customer transfers money from a savings account to a
checking account, the transaction can consist of three separate operations:
Decrement the savings account
Increment the checking account
Record the transaction in the transaction journal
Oracle must allow for two situations. If all three SQL statements can be performed to maintain the
accounts in proper balance, the effects of the transaction can be applied to the database. However,
if a problem such as insufficient funds, invalid account number, or a hardware failure prevents one
or two of the statements in the transaction from completing, the entire transaction must be rolled
back so that the balance of all accounts is correct.
Transactional control commands are only used with the DML commands INSERT, UPDATE and
DELETE only. They can not be used while creating tables or dropping them because these
operations are automatically commited in the database.
1. COMMIT Command:
The COMMIT command is the transactional command used to save changes invoked by a
transaction to the database.
The COMMIT command saves all transactions to the database since the last COMMIT or
ROLLBACK command.
SQL> COMMIT;
SQL> ROLLBACK;
SAVEPOINT SAVEPOINT_NAME;
This command serves only in the creation of a SAVEPOINT among transactional statements. The
ROLLBACK command is used to undo a group of transactions.
The syntax for rolling back to a SAVEPOINT is as follows:
ROLLBACK TO SAVEPOINT_NAME;
Example:
SQL> SAVEPOINT SP1;
Savepoint created.
1 row deleted.
Savepoint created.
SQL> DELETE FROM CUSTOMERS WHERE ID=2;
1 row deleted.
Savepoint created.
1 row deleted.
Rollback complete.
A.5 Tasks:
Task 1:
1. Open two SQL command line windows. Do the login with same username in both windows.
begin
end;
7. Now again fire select query in second window select * from emp where empno=7900;. Note
what value are you getting for salary column? Note it down in part B. Why this difference?
Task 2:
1. Now let use try update the same tuple concurrently from two windows. In first window
execute:
begin
update emp set sal=sal+1000 where empno=7900;
end;
then in second window type same above code. Now in first window press enter and type ‘/’ to
execute procedure. Same time immediately in second window press enter and type ‘/’ to
execute procedure.
Now type commit; in first window. See what happen? Not it down in part B.
Now fire below SQL query in both windows and note down salary column value in both
windows.
select * from emp where empno=7900;
Now type commit in second window and fire same SQL query in both window.
PART B
(PART B: TO BE COMPLETED BY STUDENTS)
(Students must submit the soft copy as per following segments within two hours of the
practical. The soft copy must be uploaded on the student portal or emailed to the concerned
lab in charge faculties at the end of the practical in case the there is no Black student portal
access available)
1. What is transaction?
2. What is rollback and commit command? Explain with an example.
3. What was your observation about savepoint command? Explain with an
example?
4. Explain your observation about task1.
5. Explain your observation about task2.
B.2 Conclusion:
(Students must write the conclusion as per the attainment of individual outcome listed above and
learning/observation)