0% found this document useful (0 votes)
6 views21 pages

Section 1

Uploaded by

Rupa Devi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views21 pages

Section 1

Uploaded by

Rupa Devi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

SECTION 1 DBMS LAB

Structure Page Nos.


1.0 Introduction
1.1 Objectives
1.2 Database Creation, Data Modification and Simple Queries
1.2.1 Database Creation and Inserting data in the database
1.2.2 Simple Querying
1.2.3 Practical Exercises for Session 1 to Session 3
1.3 Sub-queries and Joins
1.3.1 Sub-queries
1.3.2 Joins
1.3.3 Practical Exercises for Session 4 to Session 6
1.4 Creating Views, Indexes and Queries
1.4.1 Creating a View
1.4.2 Indexes
1.4.3 Exercises for Session 7
1.5 Control Loops and Procedures
1.5.1 Control Loops
1.5.2 Procedures
1.5.3 Exercises for Session 8
1.6 Transaction Management, Triggers and Functions
1.6.1 Transaction Management
1.6.2 Triggers
1.6.3 Functions
1.6.4 Exercises for Session 9
1.7 User Management and Object Privileges
2.7.1 User Management
2.7.2 Exercises for Session 10
1.8 Summary

1.0 INTRODUCTION

Information Technology (IT) has influenced organisational performance and competitive standing.
The increasing processing power and sophistication of analytical tools and techniques require a strong
foundation of structured form of data. Thus, the presence of a commercial, secure, reliable database
management system is a major requirement for businesses.

You must have obtained the practical skills of several programming languages by now. However,
when you want to create a secure, managed database application, you need not re-start from scratch
and develop a huge system using a programming language; rather, you can use a database
management system. This software allows us to create databases, queries and many more operations
on data. This section is an attempt to familiarise you with commercial database management features
so that you are able to apply some of the important features of DBMS in a commercial situation. This
would require a sound background of the concepts of DBMS, which can be acquired through the
course MCS-207: Database Management Systems. You would also have to apply the conceptual
background to obtain problem solving skills using a commercial RDBMS. The topics that have been
included in this section are SQL commands for various types of operations.

Please note that we have given many examples in this lab section in different sessions,highlighting the
basic syntax of various statements; however, they are not exhaustive, as commercial RDBMSs

1
implement a large number of statements and functions. Therefore, you must refer to the user reference
manuals of the commercial RDBMS for more details on these topics. Also, we have given examples
for a typical RDBMS; however, you may do practical on any commercial RDBMS supporting such
concepts. However, you should find the changes in the statements used here for the RDBMS you may
be using. Remember, the objectives of this section consisting of ten sessions, will be completed only
if you practice using any commercial RDBMS. You are also advised to run all the example queries
too. However, you may find that some of these queries may run on the RDBMS selected by you. In
such cases, you are advised to modify the query as per your RDBMS.

1.1 OBJECTIVES

After going through this section and performing all the practical exercises, you should be able to:
 write and run SQL queries for table creation,
 create integrity and constraints on databases,
 write and run SQL queries,
 create and run sub-queries, views, indexes and procedures,
 write simple embedded SQL related programs,
 manage transactions using SQL,
 write simple triggers, and
 perform simple user management.

1.2 DATABASE CREATION, DATA


MODIFICATION AND SIMPLE QUERIES

Objectives
At the end of this section, you should be able to use SQL to:
 Create a database with constraints
 Insert data in a table
 Perform simple queries

This section deals with the process of database creation, insertion of data in the database, altering the
database design, data modification and writing simple queries.
1.2.1 Database Creation and Inserting data into the database
For database creation, you need to use the CREATE command. For this first, you need to create a
database using the command
CREATE databaseName
This is followed by the command
USE databaseName
You can now create tables in the database. The following command allows you to create a table:
CREATE TABLE tablename( Column_name1 data type (column width) [constraints],
Column_name2 data type (column width) [constraints],

2
……………………………………….. );
Where table name assigns the name of the table, column name defines the name of the field; data type
specifies the data type for the field and column width allocates specified size to the field.

Guidelines for creation of table:


• Table name should start with an alphabet.
• In table name, blank spaces and single quotes are not allowed.
• Reserve words of that DBMS cannot be used as table names.
• Proper data types and sizes should be specified.
• Unique column name should be specified.
Column Constraints:
Some of the important constraints are NOT NULL, UNIQUE, PRIMARY KEY, CHECK,
DEFAULT, REFERENCES, ON DELETE RESTRICT etc.

Example 1: The command to create a table named product (pno, pname, quantity), having the primary
key (pno), which ensures that product number (pno) is not null and unique (both are the properties of
primary key). The product name (pname) should not be left blank. The table has a constraint that the
quantity should be between 1000 and 4500. This table can be created using the following SQL
command

CREATE TABLE product ( pno number (4) PRIMARY KEY,


pname char (20) NOT NULL,
qoh number (5),
CHECK (qoh>1000 AND qoh<4500) );

In many implementations of SQL on commercial DBMS like SQL Server and Oracle, a data type
called varchar and varchar2 is used. Varchar and Varchar2 basically are variable length character
types subject to a maximum specified length in the declarations.

For inserting data into the tables, you can use INSERT command, which has the following format:

INSERT INTO tablename(Column_name1, Column_name2, …)


VALUES (Value1,Value2, …);
When you are inserting into the entire table, then you need not specify the column names. This will
reduce the format to:
INSERT INTO tablename VALUES (Value1,Value2, …);

Example 2: To insert records in the table created in example 1 are:

INSERT INTO product VALUES (1001, “Pencil”, 2000);


INSERT INTO product (pno, pname) VALUES (1002, “Pen”);
INSERT INTO product (pname, pno) VALUES (“Sharpner”, 1004);
INSERT INTO product VALUES (1002, “Eraser”, 2000);
INSERT INTO product VALUES (1003, “Eraser”, 200);
Please note that some of the statements above will not be executed; rather, they will generate error
message. Find out why?

1.2.2 Simple Querying


After creating the databases and inserting data in tables, you are ready to query the database.
The simple command to query the database is SELECT command. It has the following format:
SELECT <Column_name list using , as separator>
FROM <Tablename list using , as separator>
WHERE <Conditional Expressions using relational and logical operators>
GROUP BY <Column_name lists>

3
HAVING <Condition on groups>
ORDER BY <attribute for specifying ordering in ASC ascending of DESC order>

Example 3: List all the products for which quantity is less than 1500, in the alphabetical order of
names.

Solution: Use the following command of SQL. (ASC is for ascending order. Find out what keyword
will be used fro descending order.)

SELECT pname, pno


FROM product
WHERE qoh< 1500
ORDER BY pname ASC;

Example 4: Assuming that there are several products with the same name but different product
number (pno) in the data, find the total quantity of each of these product names.

Solution: Use the following command of SQL.

SELECT pname, sum(qoh) AS totalQuantity


FROM product
GROUP BY pname;

Example 5: Refer to example 4 query; show only those groups for which the total quantity is less than
2000.

SELECT pname, sum(qoh)


FROM product
GROUP BY pname
HAVING sum(qoh) < 2000;

For more details, you may refer to MCS207 or the manual of the RDBMS you are using to implement
these queries.

1.2.3 Practical Exercises for Session 1 to Session 3


This section lists the exercises relating to DBMS. You must perform the following exercise during the
practical sessions.

Question 1: Create a database for an Employee management system of an ABC organisation. The
details about the different tables are given below. You can proceed further and create tables using any
RDBMS.

Create the following tables with the specified constraints:


Employee
First name - Not NULL
Middle initials -
Last name - Not NULL
Employee-id - Primary Key
Date of Birth - Minimum age today > 21years
Address -
Gender - Male (M) or Female (F) or Not
Salary - Range of 500o to 25000
Date of Joining -

4
Department number - Refers to Department Number of Department table.
Department
Department name - Not NULL unique
Department number - Primary Key
Manager_id - Refers to employee-id of employee table.
Manager date of joining - Not NULL.
Department location
Department number - Refers to Department number of department table.
Department location - Not NULL.
Department number and Department location are combined Primary Key.
Project
Project name. - Not NULL.
Project number - Primary Key.
Project location - Not NULL.
Department number - Refers to department number of Department table.
Works-on
Employee-id - Not NULL refers to employee-id of employee table.
Project number - Not NULL refers to Project number of Project table.
Hours - Not NULL.
Employee - Id & Project number are combined primary key.
Dependent
Employee-id - Refer to employee table employee id field
Dependent name -
Gender - M or F
Date of Birth - Not NULL
Relationship - Not NULL

Now enter a few sets of meaningful data and answer the following queries:
1. List the department wise details of all the employees.
2. Find all those departments that are located in more than one location.
3. Find the list of projects.
4. Find the list of employees working on a project.
5. List the dependents of the employee whose employee id is ‘001’

Question 2: Develop a prototype database of the IGNOU library management system and
create the following tables:
(a) Book Records
(b) Book details
(c) Member details and
(d) Book issue details
The structure of the tables is given below:
Table Name Attribute Name
Book Records Accession Number, ISBN Number
Books ISBN Number, Author, Publisher, Price
Members Member Id, Member Name, Maximum Number of books that
can be issued to a member. Maximum Number of days for which
book can be issued
Book Issue Member Id, Accession Number, Issue Date, Return Date

5
You must create constraints, including referential integrity constraints, as appropriate. Please note
accession number is unique for each book. A book, which has no return date, can be considered as
the issued book. Enter suitable data into the tables. Now answer the following using SQL:
1. Insert data in all three tables (use insert).
2. Insert appropriate description associated with each table and the column (use comment).
3. Display the structure of the tables.
4. Write the queries for performing the following function in SQL:
(a) Get the list of all books (No need to find the number of copies)
(b) Get the list of all members
(c) Get the Accession number of the books that are available in the library
(d) On the return of a book by a member, calculate the fine on that book.
(e) List of books issued on 01-Jan-2021
(f) Get the list of all books having prices greater than Rs.500/-
(g) Get the list of members who did not have any book issued at any time.
(h) Get the list of members who have not returned the book.
(i) Display member ID and the list of books that have been issued to him/her from time to time.
(j) Find the number of copies of each book (A book accession number would be different, but
ISBN number would be the same).
(k) Find the number of copies available of a book of the given ISBN number.
(l) Get the member ID and name of the members to whom no more books can be issued, as
they have already got as many books issued as the number for which they are entitled.
Question 3: For the library management system; you created in question 2 above, answer the
following queries.

1. Get the list of ISBN-Number, Book names and number of available copies of those books
whose number of available copies is at least one. This list should be in ascending order of book
name.
2. Get the list of ISBN number, Book name, Author, total copies, cost (cost is price total copies)
in descending order of cost.
3. Get the list of books issued to each member.
4. Write a query to know the maximum and average price of the books.
5. Get the list of all existing members and the number of days for which a member is allowed to
keep the book. Also, find out the members who have got the maximum number of books
issued.
6. Get the list of member codes of those members who have more than two books issued.
7. Find the details of the books presently issued to a member.

Question 4: Create the following table named Customer


Column name type size
Customerid Character 10
Name Character 25
Area Character 3
Phone Numeric 7

Insert the appropriate data into the table and perform the following operations.

• Update Phone numbers of all customers with prefix as your city STD Code.
• Print the entire customer table.
• List the names of those customers who have ‘e’ as the second letter in their names.
• Find out the Customer belonging to area ‘abc’.
• Delete record where the area is NULL.
• Display all records in increasing order of name.
• Create a table temp from the Customer having customerid, name and area.

6
• Display area and the number of records within each area (use GROUP by clause).
• Display all those records from the customer table where name starts with ‘a’ or area is “abc”.
• Display all records of those where the name starts with ‘a’ and phone exchange is 55.
• Add one attribute named Mobile in the table and copy phone numbers into it.

Question 5: Create the following tables, set all the referential constraints among the tables. Insert
about 10 records in each relation. You may assume a suitable data type and length for each attribute.
Primary key of each relation is shown with an underline. Please also note that there is no overlap of
limits for a grade in the payscale relation.
teacher (t_no, f_name, l_name, salary, supervisor, joiningdate, birthdate, jobtitle)
class (class_no, t_no, room_no)
payscale (Min_limit, Max_limit, grade)
Please note that t_no in the class relation references t_no in the teacher relation and supervisor one of
the teacher.

1.3 SUB-QUERIES AND JOINS

Objectives
At the end of this section, you should be able to:
 define sub-queries and joins
 create different types of sub-queries
 perform different types of join queries.
The queries are given in this session, and most of the later sessions are based on the teacher, class and
payscale relations that you have created in Question 5 of the section 1.2.3 and are given below:
teacher (t_no, f_name, l_name, salary, supervisor, joiningdate, birthdate, jobtitle)
class (class_no, t_no, room_no)
payscale (Min_limit, Max_limit, grade)
Please note that t_no in the class relation references t_no in the teacher relation and supervisor one of
the teacher.
1.3.1 Sub-queries
Sub-query means a SELECT statement that retrieves the values from the table and passes these values
as an argument to the main or calling SELECT statement. In simple words, nested queries are sub-
queries. Sub-queries can be of different types:
1) Single-row sub-query
2) Multiple-row sub-query
3) Multiple-column sub-query
4) Correlated sub-query.
Single-Row Sub-query
Single-row sub-query is the query that returns only one value or row to the calling SELECT
statement. For example:
Query 1: Display the name of the teacher who is the oldest among all teachers.
Explanation: To know the name of the teacher who is the oldest, you need to first find the minimum
birth date and then, corresponding to that date, display the name of the teacher (assume that only one
teacher is the eldest).

7
SELECT f_name, l_name FROM teacher
WHERE birthdate = (SELECT MIN (birthdate)
FROM teacher);
Query 2: Display teacher number and name of those teachers who are earning less than a teacher,
whose first name is “Jatin”.
Explanation: To find the list of teachers earning less than ‘Jatin’, you need to first find the salary of
‘Jatin’ (assuming only one person has the first name ‘Jatin’).

SELECT t_no, f_name, l_name


FROM teacher
WHERE salary < ( SELECT salary
FROM teacher
WHERE f_name = ‘Jatin’);
Multiple-Row Sub-query
Multiple-row sub-queries are the queries that return more than one value or row to the calling
SELECT statement. For example:
Query 3: Display the list of all teachers who are earning equal to any teacher who has joined before
‘31-dec-94’
Explanation: First, you need to know the salaries of all those who have joined before ‘31-dec-94’ and
then any teacher whose salary matches any of these returned salaries. You can use the IN operator,
which looks for this existence into the set. You can also use DISTINCT to avoid duplicate salary
tuples.
SELECT t_no, f_name, l_name
FROM teacher
WHERE salary IN ( SELECT DISTINCT salary
FROM teacher
WHERE joiningdate < to_date (‘31DEC1994’, ‘ddmmyyyy’) );
Query 4: Display the list of all those teachers whose salary is greater than any other teachers with job
title is ‘PGT’.
Explanation: First, you need to know the salaries of all those who are ‘PGT’ and then any teacher
whose salary is greater than any of these returned salaries. ANY operator looks for inequality.
SELECT t_no, f_name, l_name, salary
FROM teacher
WHERE salary > ANY ( SELECT salary
FROM teacher
WHERE jobtitle = ‘PGT’);
Query 5: Display the list of all those teachers whose salary is greater than all the teachers with job
title as ‘PGT’.
Explanation: First, you need to know the salaries of all those who are ‘PGT’ and then any teacher
whose salary is greater than all of these returned salaries. ALL operator looks for inequality.
SELECT t_no, f_name, l_name, salary
FROM teacher
WHERE salary > ALL ( SELECT salary
FROM teacher
WHERE jobtitle = ‘PGT’);

Single-row Subquery Multiple-row subquery


Operator Description Operator Description
= Equal to IN Returns true if any of the values in the
> Greater than list match i.e. equality check
< Less than ALL Returns true if all the values returnedby

8
>= Greater than equalto the subquery match the condition

<= Less than or equalto ANY Returns true if any of the values returned
by subquery match thecondition.
<> Not equal to
Figure 1: Operators for subqueries

Multiple-Column sub-query
Multiple-Column sub-query is the sub-query that returns more than one column to the calling or main
SELECT statement. For example:
Query 6: Display the list of all teachers whose job title and salary are the same as that of the
employee whose first name is ‘Jaideep’.
Explanation: Firstly, you need to find the job title and salary of ‘Jaideep’, and then you need to find
all other teachers whose job title and salary exactly matches Jaideep’s job title and salary.
SELECT t_no, f_name,l_name, jobtitle, salary
FROM teacher
WHERE (jobtitle, salary) IN ( SELECT jobtitle, salary
FROM teacher
WHERE f_name = ‘Jaideep’);
Correlated Sub-queries
This is another type of sub-query where the sub-query is executed for each and every record retrieved
by the calling or main SELECT statement. A correlated sub-query returns only a Boolean value
(true/false). A true is returned if the sub-query returns one or more records; otherwise, a false is
returned. The operator EXISTS can be used for these types of sub-queries. For example:
Query 7: Display the records in the format given below for all class teachers:Jaideep Kumar is a class
teacher
Explanation: The main query uses the EXISTS operator to find whether the teacher is a class teacher
or not. If the correlated subquery returns a true value, then the record retrieved by the main SELECT
statement is accepted; otherwise, it is rejected.

SELECT f_name, l_name, ‘is a class teacher’


FROM teacher
WHERE exists ( SELECT *
FROM class
WHERE class.t_no = teacher.t_no);
1.3.2 Joins
Joins means retrieving data from more than one table in a single query. There are several types of
joins:
1) Natural Join – In this type of join, two or more tables are joined over common attributes
having similar values. For example:

Query 8: Display the names of all the class teachers.

SELECT f_name, l_name


FROM teacher t, class c
WHERE t.t_no = c.t_no;
This query can also be written as:
SELECT f_name, l_name

9
FROM teacher natural join class;

2) Non-equijoin - In this type of join, two or more tables do not have common attributes and
common values, but they are joined indirectly. For example:
Query 9: Display the names, salaries and salary grades of all the teachers. The query assumes that
grades are not overlapping.

SELECT f_name, l_name, salary, grade


FROM teacher, payscale
WHERE salary BETWEEN min_limit AND max_limit;
3) Outer join - In this type of join, two or more tables are joined over common attributes, but
the records of one or both the relations which do not participate in the join are preserved. Outer joins
are of three types – left outer join, right outer join and full outer join. For example:
Query 10: Display the names of all the teachers. In addition, display the classes of those teachers who
are class teachers. Thus, the result should include the names of teachers who are not class teachers.
Please note that teacher relation is towards the left of the outer join keyword; therefore, it is a left
outer join.
SELECT f_name, l_name, class_no
FROM teacher t LEFT OUTER JOIN class c
ON t.t_no = c.t_no;
4) Self join - In this type of join, the table is joined to itself. For example:
Query 11: Display the teacher number and name of all teachers, along with the names of their
supervisors and the supervisor number. (Please note field supervisor references t_no of teacher table.)
Please note that the supervisor of a teacher is also a teacher. Therefore, the query requires a self-join.

SELECT t.t_no, t.f_name, t.l_name, t.supervisor, s.f_name, s.l_name


FROM teacher t, teacher s
WHERE t.supervisor = s.t_no;
5) Cartesian join – In this type of join, each record of one table is joined to each record of the
other table, i.e., the join condition is not given. For example:
Query 12: Show all possible teacher name – class number pairs.

SELECT f_name, l_name, class_no


FROM teacher t, class c;
1.3.3 Practical Exercises for Session 4 to Session 6
Question 1: Please attempt the following problems for the teacher, class and payscale relations of
Question 5 Section 1.2.3, which is given below:
teacher (t_no, f_name, l_name, salary, supervisor, joiningdate, birthdate, jobtitle)
class (class_no, t_no, room_no)
payscale (Min_limit, Max_limit, grade)
Please note that t_no in the class relation references t_no in the teacher relation and supervisor one of
the teacher.
(a) Implement all the queries given in the examples. List the change in syntax, if any.
(b) Display the name of the teacher(s) who is (are) the youngest among all the teachers.
(c) Display details of all the teachers who have the same job title as that of ‘Jaideep’.
(d) Display the list of all the teachers who have joined after ‘10-Jul-95’ and whose salary is equal
to that of any of the teachers who joined before ‘10-Jul-95’.

10
(e) Use a correlated query to determine the teachers who are not class teachers.
(f) Identify all those teachers who are in grade ‘B’.
(g) Display the names and numbers of all teachers who are class teachers and are in grade ‘C’.
(h) Display the names of all teachers who are supervisors.
(i) Display the teacher id and salaries of all those teachers who are in grade‘A’ or ‘C’ and who
have at least one ‘L’ in their first name and one ‘L’ in their last name.
(j) Display details of all those teachers who are class teachers of class 1 to class 5
(k) Display the names of all teachers along with their dates of birth whose birthday is in the current
month.

Question 2: Answer the following queries using the Library system created earlier. Use any inbuilt
function and operators like IN, ANY, ALL, EXISTS etc.

a. List the records of members who have not been issued any book (use EXISTS operator).
b. List the members who have got issued at least one book (use IN / ANY operator).
c. List the books that have maximum Price using ALL operator.
d. Display Book Name, Member Name, Issue date of Book. Create a view of this query of the
currently issued books.
e. Get the list of books presently issued to the members, along with the names of the book as well
as names of the member to whom it is issued.
f. Get the list of the members who are entitled for more books than that the entitlement of member
named “abc”.
g. Get the list of the members who are issued the books for more days than the number of days for
which books are issued to “abc”.
h. Find the history of issuing of a list of books that have been identified during the inspection as
damaged books. (Create the necessary tables if needed).

Question 3: Create a table of Employee (emp-number, name, dept, salary) and Department (dept-
number, dept name). Create integrity constraints in the tables and insert some records in the tables.
Add some records in employee table who have no department. Now answer the following queries:

a. Display all records from the employee table who have no department.
b. Display those records depatrments, which has no employees.
c. Display those employee records who have salary less than the salary of the person whose emp-
number is ‘A100’.

Question 4: In an Open University, a student’s data is to be maintained using relations. The


University maintains data of all the students, their batches, Regional Centres andstudy centre details.
Each batch of students has one or more representative students. The batches are taught by the same or
different faculty.
a. Design and implement suitable relations for the University. Make andstate suitable
assumptions.
b. Write at least 15 queries (they must include at least one query of each type given in this section
2.2) for the database. Implement these queriesusing SQL. Also, explain the purpose of each
query.
Question 5: Design a suitable database system for a bank along with 20 possible queries to the
database (the queries should be such that their solution involves sub-queriesor joins or both).
Implement the database and the queries in a commercial DBMS using SQL.

11
1.4 CREATING VIEWS, INDEXES AND QUERIES
Objectives
At the end of this session, you will be able to:
 define database objects such as views and indexes
 create views and use views
 create and maintain indexes.
The views help you to simplify your complex queries on the tables. Also, they increase the secrecy of
data. To speed up the performance of queries, you should create indexes on one or more columns.
The discussion in this session is based on the following relations:

Teacher(t_no, f_name, l_name, salary, supervisor, joiningdate, birthdate, jobtitle)


Class(class_no, t_no, room_no)
Payscale(Min_limit, Max_limit, grade)

Please note commands used in this and the following sections may differ for different RDBMSs;
therefore, you may refer to the manual of RDBMS used by you.
1.4.1 Creating a view
Views are virtual tables that are derived from base tables at runtime. A view after creation can be used
as any other table, but a view does not store data and it derives data only when it is called. The
CREATE VIEW command is used to create views on the tables.
Syntax: CREATE VIEW AS
SELECT statement [with check option [constraint]]
[with read only]
With check option: Allows the DML operations only on the rows accessible to the view.
With read-only: Does not allow any DML operation using view.

For example:

Example 1: Create a view that displays teacher number, the names of teachers, along with salary,
jobtitle, age and grade.
CREATE VIEW teacher_details
AS SELECT t_no, f_name||’ ‘||l_name AS name, salary, jobtitle,
trunc(months_between(sysdate,birthdate)/12,0) AS age, grade
FROM teacher, payscale
WHERE salary BETWEEN min_limit AND max_limit;
Let us make a few queries on this view.

Query (a): Display teacher number, their names, age and grade of all PGT teachers.
SELECT t_no, name, age, grade
FROM teacher_details
WHERE jobtitle = ‘PGT’;
Query (b): Display details of all the teachers who are more than 40 years old.
SELECT t_no, name, salary, jobtitle, age
FROM teacher_details
WHERE age > 40;

12
To remove a view, DROP statement is used.
For example:DROP VIEW teacher_details;
1.4.2 Indexes
Index is an object that reduces the record-retrieval time. An index contains a row pointer, which
determines the location of the record and the values of the target columns. Indexes can be based on
one or more table columns. Two types of indexes can be created:
1. Unique indexes - These indexes are created automatically whenever a PRIMARY KEY or
UNIQUE constraint is defined.
2. Non-unique indexes - These indexes are created explicitly by the user on non-unique keys.
Syntax:
CREATE INDEX index_name ON tablename (column1 , column2 ,………);
Example 2: Create an index on the relation teacher on the job title for fast access.
CREATE INDEX t_title_index ON teacher(jobtitle);
To remove an index, drop statement is used. For example,
DROP INDEX t_title_index;
1.4.3 Exercises for Session 7

Question 1: Please attempt the following problems for the teacher, class and pay scale relations given
in section 1.2.3. These relations are shown below:

Teacher(t_no, f_name, l_name, salary, supervisor, joiningdate, birthdate, jobtitle)


Class(class_no, t_no, room_no)
Payscale(Min_limit, Max_limit, grade)
(a) Create a view named ‘supervisor_details’ that stores the names and numbers of all the
supervisors.
(b) Create a non-unique index on the foreign key column of the ‘class’ table.
(c) Modify the view created in (a) and add details like salary, job title, joining date, birth date etc.
of all supervisors.
(d) Using the view created in (c), display details of all supervisors who have worked for more than
15 years.
(e) Create a view that stores the details of all the teachers who are TGT and earning more than
Rs.12000/-.
(f) Drop the view created in (e).
(g) Create a non-unique index on the names of teachers in the ‘teachers’table.
(h) Drop the index created in (b).
(i) Create a view named ‘teacher_info’ that allows users to only view the teacher id, name, salary
and grade of the teachers. It should not allow any user to change/update any information.
(j) Create a view that displays details of all teachers who are in grade ‘B’and are more than 40
years old.
Question 2: Design suitable views on the Open University database system designed by you, as per
question 4, Section 1.3.3: Practical exercises for Session 4 to Session 6. For example, you can create a
view for the faculty giving him/her details of his/her students. Create at least 5 suitable queries on
each of the views created by you. Also, create indexes for the University database system. For
example, you can create an index on the student name, thus, allowing faster access to student
information in the order of student names. You must explain how the indexes created by you would

13
enhance the performance of the database system. Implement the above in a commercial DBMS using
SQL.
Question 3: Design suitable views and indexes for the Bank database system designed by you, as per
question 5, Section 1.3.3: Practical exercises for Session 4 to Session 6. Create at least five suitable
queries on each of the views. Explain how the indexes created by you would enhance the performance
of the database system. Implement the above in a commercial DBMS using SQL.

1.5 CONTROL LOOPS AND PROCEDURES


\

Objectives
At the end of this session, you should be able to:
 use procedural constructs like LOOP
 define and use FOR loop, While loop
 define and use procedures.
You can use the programming language supported by your DBMS. In this section, examples are
shown using PL/SQL.
PL/SQL extends SQL by adding control loops found in procedural languages, resulting in a structural
language that is more powerful than SQL. We will introduce the use of PL/SQL in this session with
the help of examples.
1.5.1 Control loops
Loops are the constructs that help to repeat the statement groups on certain conditions. Let us discuss
the two basic looping constructs.
 For
 While
FOR Loops

FOR loops are the common loops. FOR loop uses a loop variable. You define the initial value, the
upper bound, increment of loop variable in the FOR loop.

Example 4: Using FOR loop for a counter from 1 to 100.


DECLARE
a NUMBER := 1;
BEGIN
FOR counter IN 1 .. 100
LOOP
a := a + (counter * 5);
EXIT WHEN a > 10000;
END LOOP;
END;

WHILE Loops

This loop structure is iterated based upon a condition test. If the condition is true then the loop is
executed otherwise, not.
Example 6: A quantity can be issued if the total amount is below a sanctioned amount.
DECLARE

14
qty NUMBER := 1;
sanctioned_amt NUMBER := 1000;
unit_price NUMBER := 10;
tot_amt NUMBER := 0;
BEGIN
WHILE tot_amt < sanctioned_amt
LOOP
tot_amt := unit_price * qty;
qty := qty + 1;
END LOOP;
END;
1.5.2 Procedures
PL/SQL procedure is a named program block i.e., a logically grouped set of SQL and PL/SQL
statements that perform a specific task. They can be invoked or called by any PL/SQL block. The
syntax is:
CREATE OR REPLACE PROCEDURE name (argument {IN, OUT, INOUT} data type,…)
IS
Variables declarations;
BEGIN
PL/SQL subprogram body
EXCEPTION
Exception PL/SQL block
END procedure name;
Replace: if procedure is already created, then replace it.
IN : Indicates that the parameter will accept a value from the user.
OUT : Indicates that the parameter will return a value to the user.
INOUT : Indicates that the parameter will either accept from or return a value to theuser.
Example 7: Following procedure searches the name of a teacher in the relation
teacher
CREATE OR REPLACE PROCEDURE search_teacher
(o_t_no IN NUMBER,
o_f_name OUT VARCHAR2,
o_l_name OUT VARCHAR2)
IS
BEGIN
SELECT f_name, l_name INTO o_f_name, o_l_name
FROM teacher
WHERE t_no = o_t_no;
END search_teacher;
run; /* it is used to create the procedure */
To call this procedure:
DECLARE
o_f_name teacher.f_name%TYPE;
o_l_name teacher.l_name%TYPE;
BEGIN
search_teacher( 113, o_f_name, o_l_name);
DBMS_OUTPUT.PUT_LINE(‘Employee : 113’);
DBMS_OUTPUT.PUT_LINE(‘Name : ’|| o_f_name || ‘ ‘ || o_l_name);
END;
Example 8: To demonstrate use of INOUT parameter
CREATE PROCEDURE bonus_calc(o_t_no IN INTEGER, bonus INOUT INTEGER)

15
IS
join_date DATE;
BEGIN
SELECT salary * 0.20, joiningdate INTO bonus, join_date
FROM teacher
WHERE t_no = o_t_no;
IF MONTHS_BETWEEN(SYSDATE, join_date) > 36 THEN
bonus := bonus + 1000;
END IF;
END;
Important Notes:

1) Unlike the type specifier in a PL/SQL variable declaration, the type specifier in a
parameter declaration must be unconstrained, i.e. CHAR or VARCHAR2 should be used
instead of CHAR(5) or VARCHAR2 (20).
2) The name of the procedure after the END is optional.

3) A constant or a literal argument should not be passed in for an OUT/INOUT parameter.

1.5.3 Exercises for Session 8


Question 1: Please perform the following using the following relations:
Teacher(t_no, f_name, l_name, salary, supervisor, joiningdate, birthdate, jobtitle)
Class(class_no, t_no, room_no)
Payscale(Min_limit, Max_limit, grade)

(a) Calculate the bonus amount to be given to a teacher depending on the following conditions:
i. if salary > 10000 then bonus is 10% of the salary.
ii. if salary is between 10000 and 20000 then bonus is 20% of the salary.
iii. if salary is between 20000 and 25000 then bonus is 25% of the salary.
iv. if salary exceeds 25000 then bonus is 30% of the salary.

(b) Using a simple LOOP structure, list the first 10 records of the ‘teachers’ table.
(c) Create a procedure that selects all teachers who get a salary of Rs.20000 and if less than 5
teachers are getting Rs.20000, then give an increment of 5%.
(d) Create a procedure that finds whether a teacher number whose information is requested by a
user exists or not. In case the teacher information does not exists, then display “No Such
Teacher”.
(e) Using FOR loop, display the name and teacher number of all those teachers who are more than
58 years old.
(f) Using while loop, display details of all those teachers who are in grade ‘A’.
(g) Create a procedure that displays the names of all those teachers whose supervisor is teacher
named ‘Suman’.
(h) Calculate the tax to be paid by all the teachers depending on the following conditions:
i. if annual salary > 5,00,000 then no tax.
ii. if annual salary is between 5,00,001 and 15,00,000 then tax is 20% of the annual salary.
iii. if annual salary is between 15,00,001 and 25,00,000 then tax is 30% of the annual salary.
iv. if salary exceeds 25,00,000 then tax is 40% of the annual salary.
(i) Create a procedure that finds the name of all the teachers with the job title ‘PRT’ and if the
number of teachers returned is more than 10 then change the job title to ‘TGT’ for the top 3
‘PRT’ teachers based on their hire date.
Question 2: Identify the need for procedures for the University database system; for example, you can

16
create a procedure that awards 2% grace marks for those students who have got 48% marks. Design at
least five such procedures. Implement these procedures using embedded SQL.
Question 3: Implement at least five procedures for the Bank Database system using embedded SQL.

1.6 TRANSACTION MANAGEMENT, TRIGGERS AND


FUNCTIONS
Objectives
At the end of this session, you should be able to:
 use commit, rollback and save point specifications.
 define triggers and functions.
 define and create statement and row triggers.
 create functions with or without parameters.

1.6.1 Transaction Management


A transaction is a logical unit of work that is composed of one or more statements of Data
Manipulation Language (DML) or Data Definition Language (DDL), or Data Control Language
(DCL). A transaction starts when an SQL statement is executed and terminates when any of the
following occurs:
 Any DDL or DML statement is executed.
 A COMMIT or ROLLBACK statement is given.
 User exits SQL.
The transactions can be committed implicitly or explicitly. All DDL or DCL statements are implicitly
committed.
There are three explicit transaction specifications:
1) COMMIT: It ends the current transaction and saves all pending changes permanently since last
saved or COMMIT or ROLLBACK. The syntax is:
COMMIT;
2) SAVEPOINT: It marks and saves the current point of the transaction process. It is useful for
performing partial rollbacks. The syntax is:
SAVEPOINT name;
3) ROLLBACK: It ends the transaction but discards all pending changes since the last commit
point or save point. The syntax is:
ROLLBACK [ TO SAVEPOINT name];
Example:
SQL > UPDATE teacher SET jobtitle = ‘PGT’ WHERE salary > 15000;
SQL> COMMIT. /* Changes made by Update statement are saved */
SQL> INSERT INTO class (class_no, t_no, room_no) VALUES (10,127,226);
SQL> ROLLBACK; /* values inserted into ‘class’ table are discarded */
SQL> UPDATE teacher SET jobtitle = ‘SUPERVISOR’ WHERE salary > 20000;
SQL> SAVEPOINT update_done; /* savepoint created */
SQL> DELETE FROM teacher;
SQL> ROLLBACK TO SAVEPOINT update_done; /* just delete statement is discarded */

17
1.6.2 Triggers

For the following discussion, we will consider the following relations:


Teacher(t_no, f_name, l_name, salary, supervisor, joiningdate, birthdate, jobtitle)
Class(class_no, t_no, room_no)
Payscale(Min_limit, Max_limit, grade)
A trigger is a block of code stored in the database. It is executed on the occurrence of an event in a
database table, e.g. insertion of a record in a table. Triggers are implicitly invoked by DML
commands like INSERT, UPDATE or DELETE. But you cannot use COMMIT, ROLLBACK and
SAVEPOINT statements within trigger blocks. Triggers can be called BEFORE or AFTER the
events. Triggers can be of two types:
1) STATEMENT type - STATEMENT triggers fire BEFORE or AFTER the execution of the
statement that caused the trigger to fire.
2) ROW type - ROW triggers fire BEFORE or AFTER any affected row is processed.
Example 1: The following is a STATEMENT trigger, which does not allow working on the database
during weekends.
CREATE OR REPLACE TRIGGER not_working_hour
BEFORE DELETE OR INSERT OR UPDATE ON teacher
BEGIN
IF (TO_CHAR(SYSDATE, ‘DY’) IN (‘SAT’, ‘SUN’))THEN
DBMS_OUTPUT.PUTLINE (‘Sorry! you cannot delete/update/insert on weekends’);
END IF;
END;
Example 2: A ROW trigger for supplying new teacher id and system date as the joining date.
CREATE OR REPLACE TRIGGER new_teacher _id
AFTER INSERT ON teacher
FOR EACH ROW
DECLARE
o_t_no teacher.t_no%TYPE;
o_joiningdate teacher.joiningdate%TYPE;
BEGIN
SELECT t_no_sequence.nextval INTO o_t_no
FROM dual;
:NEW.t_no := o_t_no;
:NEW.joiningdate := SYSDATE;
END;
1.6.3 Functions
Functions are similar to procedures but in function definitions you must explicitly return a value to the
calling block via the RETURN statement. A function can have zero, one or more parameters.

Example 3: Find the grade of a teacher (one parameter function).


CREATE OR REPLACE FUNCTION get_grade (o_t_no IN NUMBER)
IS
o_grade VARCHAR2(20);
BEGIN
SELECT grade INTO o_grade
FROM Payscale, teacher
WHERE t_no = o_t_no AND salary between min_limit AND max_limit;

18
RETURN (o_grade);
END get_grade;
This function can be called from block of code as:
o_teacher_grade := get_grade(o_teacher_no);

Example 4: Function without parameter


CREATE OR REPLACE FUNCTION welcome_note RETURN VARCHAR2
IS BEGIN
RETURN ‘Good Morning!’;
END welcome_note;

This function can be called from a block of code as:


a := welcome_note;
DBMS_OUPUT.PUTLINE (a);
To drop a function:
DROP FUNCTION <function_name>;
1.6.4 Exercises for Session 9

1) Write an embedded SQL block to select the name of the teacher with a given salary. If more
than one row is returned, then display all the retrieved rows. If no row is returned, then display
‘no teacher with this salary’.
2) Write a program that displays the details of all those teachers who have reached the maximum
limit of their grades. If no row is retrieved, then display “no teacher reached the max limit of
grade”.
3) Insert at least 5 new rows in the ‘teacher’ table and then try to rollback the last 3 rows inserted
to the table.
4) Write a program that displays the names of all teachers who will attain the age of 60 years in
the current year. If no row is retrieved, then display a suitable message.
5) Write a code block that displays all the rows from ‘teacher’ table if the teacher was hired for
more than 10 years and still is a ‘PRT’. If there is no result, then display a suitable message.
6) Experiment with DDL and DML commands along with COMMIT andROLLBACK for the
Teacher, University and Banking databases.
7) Write a trigger that is fired before the DML statement’s execution on the TEACHER table. The
trigger checks the school timings based on SYSDATE. Beyond the School working hours, the
trigger does not allow any work to be performed on the data.
8) Write a trigger that is fired before an UPDATE statement is executed for the teacher table. The
trigger should write the name of the teacher, user name and system date in an already created
table called UPDATE_TABLE.
9) Write a function and pass a job title to it. If the TEACHER table does not contain any row
corresponding to that job title, then return false otherwise, true.
10) Write a trigger that verifies the joining date when a new row is inserted in the ‘teacher’ table.
The joining date should be greater or equal to the current date.
11) Write a function that gets the teacher number as a parameter and returns the class number
associated with that teacher. If the teacher is not a class teacher, then it outputs a suitable
message.

19
12) Write a function and pass a teacher number to it. If the TEACHER table does not contain that
teacher number, then return false otherwise, true.
13) Write a function that takes the teacher number as a parameter and returns the name and joining
date of the teacher.
14) Write appropriate triggers and functions for the University and Bank database systems.

1.7 USER MANAGEMENT AND OBJECT PRIVILEGES


Objectives
At the end of this session, you should be able to:
 define and create user accounts
 define the types of privileges
 give and withdraw the privileges.
1.7.1 User Management
Before the database is used by several users, they should be given privileges on their user groups. By
default, Oracle has two accounts: SYS and SYSTEM. The SYSTEM account is used to give
privileges to the users and to create new user accounts.
The user account can be created by the CREATE USER command.
Example 1: Create a user account ‘manager’ with password ‘pass’.
CREATE USER manager IDENTIFIED BY pass;

These user accounts are of use when the privileges are given to them. There are two types of
privileges:
1) System privilege: This kind of privilege allows a user to use DDL Commands like CREATE
TABLE, DROP INDEX etc.
2) Object privilege: This kind of privilege allows a user to use DML Commands like UPDATE,
INSERT etc.

We use GRANT and REVOKE commands to give and take back the privileges to user accounts,
respectively.
Example 2: Give CREATE and DROP privileges related to table/view to the user account ‘manager’.

GRANT CREATE TABLE, DROP TABLE, CREATE VIEW, DROP VIEW


TO manager;
Example 3: Withdraw DROP privilege related to table/view given to the user account‘manager’.
REVOKE DROP TABLE, DROP VIEW FROM manager;
1.7.2 Exercises for Session 10

1) Create a user account “class” and give privileges related to table/view creation, deletion,
updating and dropping.
2) Create a student account and give permission to this account for only viewing the information
on the relation Class (class_no, t_no, room_no.)
3) Create at least 3 to 4 different types of users for each of the database systems, viz. University
and Bank. Design suitable access privileges for the users. Grant these permissions to the users.
4) Consider when you have a large number of students and teachers in the University databases
that have different access rights. Is there any mechanism in DBMS that allows defining an

20
account type to some specific role? If yes, then define such types for the University database
system.
5) Define different types of users for the Bank database and provide them with suitable access
rights.
6) Practice different SQL commands on various databases you have developed.

1.8 SUMMARY
This section has broadly covered different aspects of a commercial DBMS. Some of the topics
covered during the practical sessions include database creation with constraints, database queries, sub-
queries and join based queries, creating views, indexes, operations using COMMIT and ROLLBACK
commands used in transactions, triggers and functions and user management.
You should try to solve not only the problems given in these exercises but also many other problems
during your practical sessions. You should consult online help/reference manuals of the commercial
RDBMS you are using while solving the problems. Practice is the key to achieving the basic
objectives of the sessions.
Finally, please keep in mind that the basic objective of this section is NOT to make you an expert
DBA but will introduce you to different types of SQL commands that you can perform using a
DBMS. You should look forward to applying your theoretical knowledge of MCS-207 along with the
skills obtained during the practical sessions to create solutions with respect to the data needs of
various business organisations.

21

You might also like