0% found this document useful (0 votes)
29 views79 pages

DBMS Lab Manual

Uploaded by

Smyla Lucia
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)
29 views79 pages

DBMS Lab Manual

Uploaded by

Smyla Lucia
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/ 79

1

St. Xavier’s Catholic College of Engineering


Chunkankadai-629003

B.E./B.Tech. LAB MANUAL

Subject Code : CS8481

Subject Name : DATABASE MANAGEMENT SYSTEMS LABORATORY


Category of the Subject : Professional Core
Regulation : 2017

Semester : IV

Academic Year : 2018-2019

Department : Information Technology


Degree & Program : B.Tech &Information Technology

Prepared By

Name : Dr.R.JEMILA ROSE


Designation : Associate Professor

Department : Information Technology


2

Contents

Sl. No. Description Page No.

1. College Vision, Mission, Slogan, Quality Policy, Objectives and 3


Values

2. Department Vision, Mission, Program Educational Objectives, 5


Program Outcomes and Program Specific Outcomes

3. Course Description, Objectives and Outcomes 7

4. PEO-Mission, CO-PO and CO-PSO Mapping 8

5. Syllabus with LTPC, Total Periods 10

6. Lab Experiments 13
3

College Vision, Mission, Slogan, Quality Policy, Objectives and Values


St. Xavier’s Catholic College of Engineering

Vision Mission
To transform the (rural) youth into top class
professionals and technocrats willing to serve
To be an institution of eminence of local and global society with ethical integrity, by
optimal human development, excellent providing vibrant academic experience of
engineering education and pioneering learning, research and innovation and stimulating
research towards developing a technically- opportunities to develop personal maturity and
empowered humane society. professional skills, with inspiring and high
caliber faculty in a quality and serene
infrastructural environment.

Slogan Quality policy


Attaining global eminence, by achieving
Towards a technically-empowered humane
excellence in all that we do, in life, education and
society.
service.

Objectives Values
To transform our students into fully-functioning human Efficiency that leads to
persons and empowering leaders with autonomy and Excellence
passion for continuous self-learning. Excellence that leads to Eminence
To equip them with contemporary scientific and technical Genuineness that leads to
knowledge with student centered teaching methods. authenticity
To animate them into pioneering researchers and Transparency that leads to
investors. credibility
To train them to excel with cutting edge technical, Person centeredness that leads to
entrepreneurial and managerial skills for a successful family-ness
career. Appreciation that leads to high
To expose them to challenging opportunities of self- motivation
discovery and to commit themselves to lead a value-based Altruism that leads to humane
life of humane service. service
To recruit faculty who inspire the students with their Critical thinking that leads to
passion for knowledge and transmit knowledge to the scientific approach
students by student-centered creative and innovative Fidelity that leads to
teaching and learning methods, lead them by example in responsibility
high-end researchers, and edify the students with their life Knowledge that leads to wisdom
of integrity and ethics. Innovative research that leads to
To provide standard infrastructure, serene and stimulating inventions
environment that is most conducive to learning. Hardwork that leads to
To develop avenues of continuous and responsive achievements
collaboration with stakeholders for the optimal Eco friendliness that leads to
4

development of the students and institution. protection of nature


Aesthetic campus that leads to
serene environment
Fiscal discipline that leads to
economic sustainability
Feedback that leads to
responsivity
Spirituality that leads to
committed service.
5

Department Vision, Mission, Program Educational Objectives, Program


Outcomes and Program Specific Outcomes Vision Mission PEO PO PSO
Department : Information Technology
Program: B.Tech. Information Technology

Vision
Creating top-notch Information Technology Engineers, innovative researchers and successful
entrepreneurs towards developing a technically-empowered humane society.
Mission
Providing quality technical education and high caliber skill training that meets
M1
the needs of society and latest technical expectations of the industry.
Fostering innovative and rigorous research culture among staff and students to
M2
find optimal solutions for complex problems.
Imparting value-based education to imbibe ethical principles and act with social
M3
responsibility, team spirit, and leadership.
Promoting and developing entrepreneurial skills of the students and handhold
M4
them towards commercial success.
Program Educational Objectives (PEO)
To ensure graduates will be proficient in utilizing the fundamental knowledge of
PEO 1 basic sciences, mathematics and Information Technology for the applications
relevant to various streams of Engineering and Technology.
To enrich graduates with the core competencies necessary for applying
PEO 2 knowledge of computers and telecommunications equipment to store, retrieve,
transmit, manipulate and analyse data in the context of business enterprise.
To enable graduates to think logically, pursue lifelong learning and will have the
PEO 3 capacity to understand technical issues related to computing systems and to
design optimal solutions.
To enable graduates to develop hardware and software systems by
PEO 4 understanding the importance of social, business and environmental needs in the
human context.
To enable graduates to gain employment in organizations and establish
themselves as professionals by applying their technical skills to solve real world
PEO 5 problems and meet the diversified needs of industry, academia and research.

Program Outcomes (PO) (with Graduate Attributes)


Engineering knowledge: Apply the knowledge of mathematics, science,
PO 1 engineering fundamentals, and an engineering specialization to the solution of
complex engineering problems.
Problem analysis: Identify, formulate, review research literature, and analyze
PO 2 complex engineering problems reaching substantiated conclusions using first
principles of mathematics,natural sciences, and engineering sciences.
Design/development of solutions: Design solutions for complex engineering
PO 3 problems and design system components or processes that meet the specified
needs with appropriate consideration for the public health and safety, and the
6

cultural, societal, and environmental considerations.


Conduct investigations of complex problems: Use research-based knowledge
and research methods including design of experiments, analysis and
PO 4
interpretation of data, and synthesis of the information to provide valid
conclusions.
Modern tool usage: Create, select, and apply appropriate techniques, resources,
PO 5 and modern engineering and IT tools including prediction and modeling to
complex engineering activities with an understanding of the limitations.
The engineer and society: Apply reasoning informed by the contextual
PO 6 knowledge to assess societal, health, safety, legal and cultural issues and the
consequent responsibilities relevant to the professional engineering practice.
Environment and sustainability: Understand the impact of the professional
PO 7 engineering solutions in societal and environmental contexts, and demonstrate
the knowledge of, and need for sustainable development.
Ethics: Apply ethical principles and commit to professional ethics and
PO 8
responsibilities and norms of the engineering practice.
Individual and team work: Function effectively as an individual, and as a
PO 9
member or leader in diverse teams, and in multidisciplinary settings.
Communication: Communicate effectively on complex engineering activities
with the engineering community and with society at large, such as, being able to
PO 10
comprehend and write effective reports and design documentation, make
effective presentations, and give and receive clear instructions.
Project management and finance: Demonstrate knowledge and understanding of
the engineering and management principles and apply these to one’s own work,
PO 11
as a member and leader in a team, to manage projects and in multidisciplinary
environments.
Life-long learning: Recognize the need for, and have the preparation and ability
to engage in independent and life-long learning in the broadest context of
PO 12 technological change.

Program Specific Outcomes (PSO)


Design optimal solutions for the challenges in the area of Information and
PSO 1
Communication Engineering using programming proficiencies.
Apply the modelling and prediction tools, techniques and resources to analyze
PSO 2
the real-world problems.
Develop computing systems using the software design and development skills to
PSO 3
enhance the lifestyle of the public.
7

Course Description, Objectives and Outcomes


Course Code and Title: CS8481 DATABSE MANAGEMENT SYSTEMS LABORATORY

Course Description

The aim of this laboratory is to inculcate the abilities of applying the principles of the database
management systems. This course aims to prepare the students for projects where a proper
implementation of databases will be required.

Course Objectives

1.
To understand data definitions and data manipulation commands

2.
To learn the use of nested and join queries

3.
To understand functions, procedures and procedural extensions of data bases

4.
To be familiar with the use of a front end tool

5.
To understand design and implementation of typical database applications

Course Outcomes

CO 1 Understand data definitions and data manipulation commands


CO 2 Apply the use of nested and join queries
CO 3 Understand functions, procedure and procedural extensions of data bases
CO 4 Familiar with the use of a front end tool
CO 5 Understand design and implementation of typical database applications
8

PEO-Mission, CO-PO and CO-PSO Mapping Matrices

(Correlation level: 1-slight/reasonable; 2-moderate/significant; 3-substantial/strong and “-” for no correlation)

Mapping of Program Educational Objectives to Program Outcomes


Program Outcomes
PEO
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
PEO1 3 2 - - - - - - - - - -
PEO2 3 3 1 1 - - - - - - - 2
PEO3 - - 3 - - 1 - - - - - 3
PEO4 - - 3 - 1 2 3 1 - - - -
PEO5 - - - 3 - - - 1 1 2 2 1

Mapping of Program Specific Outcomes to Program Outcomes


Program Outcomes
PSO
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
PSO1 3 2 3 - - - - - 1 - - -
PSO2 - 2 - 2 3 - 3 3 - - - -
PSO3 - - 3 - - 2 - - 2 1 - 2

Mapping of Program Educational Objective to Mission


Department Mission
PEO College Mission
M1 M2 M3 M4
PEO1 3 2 - - 3
PEO2 3 2 - 2 3
PEO3 2 3 - 1 3
PEO4 3 - 3 2 3
PEO5 2 3 - - 3

Mapping of Course Outcomes to Program Outcomes


Program Outcomes
CO
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
CS8481. 1 3 3 3 1 1 1 - - - - - 2
CS8481. 2 3 2 3 2 2 2 1 - 1 - - 1
CS8481. 3 3 3 3 2 2 1 2 - 1 - - 1
CS8481. 4 3 3 3 1 2 1 - - 1 - - 1
CS8481. 5 3 3 3 1 1 1 1 - 1 - - 1
CS8481 3 3 3 1 2 1 1 - 1 - - 1

Mapping of Course Outcomes to Program Specific Outcomes


Program Specific Outcomes
CO
PSO1 PSO2 PSO3
9

CS8481. 1 3 - -
CS8481. 2 3 - -
CS8481. 3 3 - -
CS8481. 4 3 - -
CS8481. 5 3 - -
CS8481 3 - -

Mapping of Course Outcomes to Vision and Mission


Department Mission College Department College
CO
M1 M2 M3 M4 Mission Vision Vision
CS8481.1 3 2 3 - 3 2 1
CS8481.2 3 2 3 - 3 1 1
CS8481.3 3 2 3 - 3 2 1
CS8481.4 3 2 3 - 3 1 1
CS8481.5 3 2 3 - 3 2 1
10

Syllabus
CS8481 DATABASE MANAGEMENT SYSTEMS LABORATORY L T P C 0 0 4 2

1. Data Definition Commands, Data Manipulation Commands for inserting, deleting, updating
and retrieving Tables and Transaction Control statements

2. Database Querying – Simple queries, Nested queries, Sub queries and Joins

3. Views, Sequences, Synonyms

4. Database Programming: Implicit and Explicit Cursors

5. Procedures and Functions

6. Triggers

7. Exception Handling

8. Database Design using ER modeling, normalization and Implementation for any application

9. Database Connectivity with Front End Tools

10. Case Study using real life database applications

TOTAL: 60 PERIODS
11

Scheme of Evaluation, Course Plan and Target


Sl.
Evaluation Description Marks
No.

1 Internal Assessment Marks (75% Observation and Record, 25% Model Exam) 20

2 University Examination Marks 80

3 Maximum Marks 100

4 Pass Minimum (Minimum Marks required in University Examination is 36/80) 50

Grade Point
Marks Range Grade Points Letter Grade

91-100 10 O

81-90 9 A+

71-80 8 A

61-70 7 B+

50-60 6 B

<50 0 RA

GPA or CGPA= (ΣCiGPi)/(ΣCi); Ci-credit of the i-th course, GPi-grade point obtained for the course.

Percentage= CGPA × 10.

Methods of Evaluation
1) Continuous Assessment (Pls. tick)

Observation Mini Project

Record Others (Pls. Specify):

Viva

2) University Examination

Target
12

Attainment of course outcomes : 3

University examination results : 100 %

Academic record of the course:

Average of the last three


CAYm1 CAYm2 CAYm3
years

University result (%) 9.32

CO attainment 3

Name of the course Dr R Jemila


--
instructor Rose

Academic record of the batch:

Number of students having backlogs in university examinations


Total Students
No Backlog Backlog < 5 5 ≤ Backlog ≤ 9 Backlog ≥ 10

22 6 7 7 2

After the Current


Result
13

List of Experiments

Ex. CO Page
Title
No. Mapping No.

Data Definition Commands, Data Manipulation Commands for


inserting, deleting, updating and retrieving Tables and
Transaction Control statements
1.a.Data Definition Commands for inserting, deleting, updating 14-21
1. and retrieving Tables and Transaction Control 1
statements
b) Data Manipulation Commands for inserting, deleting, 22-25
updating and retrieving Tables and Transaction Control
statements
Database Querying – Simple queries, Nested queries, Sub 26-29
2. 1
queries and Joins
3. Views, Sequences, Synonyms 2 30-34

4. Database Programming: Implicit and Explicit Cursors 2 35-42

5. Procedures and Functions 3 43-50

6. Triggers 3 51-57

7. Exception Handling 4 58-61

Database Design using ER modeling, normalization and 62-67


8. 2, 4
Implementation for any application

9. Database Connectivity with Front End Tools 5 68-73

10. Case Study using real life database applications 5 74-77

Open Ended Experiments (Content Beyond Syllabus)

Ex. CO Page
Title
No. Mapping No.

1. Realtime Database Applications 1-5 78-79


14

EX.NO.1.a. DATA DEFINITION COMMANDS

Data Definition Commands, Data Manipulation Commands for inserting, deleting,


updating and retrieving Tables and Transaction Control statements

Aim:
To study and work with DDL Commands (Create, Describe, Alter, Rename, Drop, Truncate)

Algorithm/Procedure:
Switch on the system and go to the terminal and type 'sqlplus64
<username>/<password>@oracle . A new window open with the prompt <SQL>.Here we have
to type all the SQL commands.

DBMS:

A Database Management System is essentially a collection of interrelated data and a set


of programs to access this data.

The collection of data is called database. Database system supports single user and multi-
user. When data are stored in a computer file using a database management system such as
FOXPRO, DBMS III plus, ORACLE etc., the file is called database file.

RDBMS:

It is acronym for Relational Data Base Management System. It is based on relational


theory in mathematics; some of the products in the IT industry based on RDBMS concept are
oracle, Sybase, Informix.

INTRODUCTION OF ORACLE:

ORACLE is a DBMS package developed by the ubuntu supportable front end to connect
oracle database ORACLE Corporation, various versions are oracle, oracle8, and oracle8i.Oracle8
is an Object Relational Database Management System (ORDBMS) package. It supports both
object oriented and relational concepts.

A table is a unit of storage which holds data in the form of rows and columns. Collection
of tables with their interrelation could be termed as database.

Oracle8 offers concurrent access to users. It supports client/server technology. The


individual table can have up to 1000 columns.

TOOLS OF ORACLE:
15

• SQL/PLUS

• PL/SQL

• Forms

• Reports

SQL/PLUS:

Structured Query Language is used for accessing and manipulating the database. Through
SQL plus we can store, retrieve, and edit the SQL commands. To communicate with the database
SQL supports the following commands.

1. DDL(Data Definition Language)

2. DML(Data Manipulation Language)

3. DCL(Data Control Language)

4. TCL(Transaction Control Language)

1. Data Definition Language(DDL):

▪ CREATE

▪ ALTER

▪ TRUNCATE

▪ DESC

▪ DROP

2. Data Manipulation Language(DML):

▪ INSERT

▪ SELECT

▪ UPDATE

▪ DELETE

3. Data Control Language(DCL):

▪ GRANT

▪ REVOKE
16

4. Transaction Control Language(TCL):

▪ COMMIT

▪ SAVE POINT

▪ ROLL BACK

Advantages of SQL:

➢ Simple commands

➢ Non-Procedural Language

Oracle Data Types:

A) Character data types

1. CHAR

Char data type is used to store a fixed length character data.

Syntax:

CHAR (size)

Where

Size – Number of characters. It is varying from 1 to 255 bytes.

Example:

CHAR (20), CHAR.

2. VARCHAR2

This data type is used to store variable length strings. It can also store alpha
numerical values. The size of this data types varies from 1 to 2000 bytes.

Syntax:

VARCHAR2 (size)

3. LONG

This data type can store variable character strings up to 2GB.

B) Number Data Types


17

Number data type is used to declare a column to store only numbers. This type
supports the storage of integers, real numbers, floating-point numbers etc.

Syntax:

NUMBER (P)

Where P is the total number of digits (1 to 38).

C) Date Data Type

This data type is used to store date.

Syntax:

DATE

The standard date format in ‘DD-Mon-YY’ Where DD refers the date in number,
on stands for the first three letter abbreviation of a month (like Mar, Jan etc.) and YY
stands for the last two digits of the year.

D) RAW data type

This data type is used to store binary data.

Syntax:

RAW (size)

Where Size – size of the data (maximum 2000 bytes).

E) LONG RAW data type

Binary data up to a maximum size of 2GB can be stored in this data type.

Syntax:

LONG RAW (size)

Data Definition Language (DDL):

The Data Definition Language (DDL) is used for the following purposes.

1. To create an object

2. To alter the structure of an object

3. To drop an object
18

DDL used for table definition are classified as,

• CREATE table command

• DESC table command

• ALTER table command

• DROP table command

• TRUNCATE table command

• RENAME table command

1) CREATING A TABLE

Syntax:

CREATE TABLE <table name> (column1 datatype1,………., column n datatype n);

While naming a Table:

a) The first letter should be an alphabet

b) Oracle reserve words cannot be used as table name

c) The length of a table name should not exceed 30 characters

d) Different tables should have different names

e) Underscore, numerals and letters are allowed. Blank space and single quote are
not allowed.

2) ALTERING A TABLE

The structure of a table can be changed using ALTERING command. Using this
command we can do the following.

▪ Add a new column

▪ Change the width of a datatype

▪ Change the data type of a column

▪ Include an integrity Constraint


19

▪ Drop an integrity Constraints

Syntax:

ALTER TABLE <table name> MODIFY (column datatype,………………);

ALTER TABLE <table name> ADD (column datatype,…………………..);

To delete a column

ALTER TABLE <table name> drop column <column name>;

Restrictions in altering a table:

a) Cannot change the name of a column

b) Cannot drop more than one column at a time from the table

c) Cannot change the name of a table

3) VIEWING A TABLE STRUTURE

This command is used to view the structure of a table.

Syntax:

DESC <table name>;

4) TRUNCATING A TABLE

This command is used to delete all records stored in a table. If we use this command, the
structure of the table is retained.

Syntax:

TRUNCATE TABLE <table name>;

5) DROPPING A TABLE

This command is used to remove a table from the database.

Syntax:

DROP TABLE <table name>;

6) RENAME A TABLE

Syntax:
20

RENAME <current table name> TO <new table name>;

Program:
EXERCISE:

1. Create a table student with the following structure

Rollno number (4)

Name varchar2 (20)

Address varchar2 (20)

Gender char (2)

DOB date

DOJ date

2. Create a table department with the following structure

Dno NOT NULL number (2)

Dname varchar2 (20)

3. Create a table mark with the following structure

Rollno number (4)

Subject 1 number (3)

Subject 2 number (3)

Subject 3 number (3)

4. Display the structure of table student after adding a new field

Fee number (6)

5. Change data type for dname field to varchar2 (10) in department table.

6. Add two more fields to the department table.

7. Display the department table.

8. Rename the table mark to marklist.

9. Display the table marklist.


21

10.Display the mark table.

Output:
Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Now, let us check the following subquery with a SELECT statement.
SQL> SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS
WHERE SALARY > 4500) ;
This would produce the following result.
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+

Result:
Thus the program was executed successfully
22

EX.No:1.b. DATA MANIPULATION LANGUAGE COMMANDS

Aim:

To study and work with DML commands.

Algorithm/ Procedure:
Switch on the system and go to the terminal and type 'sqlplus64
<username>/<password>@oracle . A new window open with the prompt <SQL>.Here we have
to type all the SQL commands.

Program:

Commands:

1.INSERT

Syntax:

Insert into tablename values (‘Value1’,’Value2’,……….’Value n’);

Table:

It’s a name of the table into which rows are to be inserted.If you specified view oracle
insert close into the views table.

Column:

It is a column of the table or view in the inserted row each column in the list is assign a
value from a values clause are the subquery.If you emitt one of the tables column from this list
the columns values for the inserted row these columns default values as specified when the table
was created.If you vomit the column list altogether the values clause of the query must specified
values for all columns in the table.

Values:

Specifies a row of values to be inserted into the table or view.We must specifies the value
in the value clause for each column in the column list.

Example:

To insert a student name Smith into a student table

SQL>INSERT INTO student VALUES (‘1001’,’Smith’,’Ngl’,’F’,’26-Feb- 1991’,’20-


Jan-07’,’1’);

2.UPDATE
23

This command is used to make changes to records in tables.

Syntax:

update tablename set columnname = ‘newvalue’ where columnname OPERATOR


‘value’ [and|or columnnamex OPERATOR valuex];

3. DELETE

This command is used to delete rows or records in a table.

Syntax:

delete from tablename where columnname OPERATOR ‘value’ [and|or

columnnamex OPERATOR valuex];

4. RENAME

This command is used to change the name of the table.

Syntax:

rename oldtablename to newtablename;

EXERCISE:

1.Insert the following fields into the tables student.

Rollno Name Address Gender Dob Doj Dno Fees

1001 Ancy Nagercoil F 12-OCT-1979 20-SEP-2002 1 1000

1003 John Madurai M 21-OCT-1980 23-OCT-2001 1 8000.50

2002 Manoj Chennai M 02-NOV-1979 13-NOV-2004 3 6000.50

3005 Rose Chennai F 26-APR-1970 12-SEP-2006 2 3000

1008 Raju Nagercoil M 23-AUG-1982 12-NOV-2004 4 6000

4004 anu tirunelveli F 22-MAR-1991 30-JUL-2003 1 5000


24

2.Insert the following details into the table student.

2018 Susi Ngl F 21-jan-81 28-May-02 2 6000

3006 Ravi Chen M 16-Jul-82 16-May-03 3 5000

2134 Raju Chen M 10-Jun-80 17-Dec-01 1 9000

3.Change the address of the student susi to Trichy.

4.Change the fees amount of the rollno 3006 to old fees+10%

5.Change the DOJ of the student with rollno 3006 to 29-May-83

6.Decrement the fees amount of the student susi and Ravi by Rs.1000

7.Increase the fees of all student by Rs.100

8. Remove the student susi from the table student.

9. Remove the student with the Rollno 3000

10.Display all the records from the table student

Output:
Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Now, let us check the following subquery with a SELECT statement.
SQL> SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS
WHERE SALARY > 4500) ;
This would produce the following result.
25

+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+

Result:
Thus the program was executed successfully
26

EX.NO: 2 SIMPLE QUERIES, NESTED QUERIES, SUB QUERIES AND JOINS


Aim:
To study and work with Simple queries, Nested queries, Sub queries and Joins
Algorithm/ Procedure
A Subquery or Inner query or a Nested query is a query within another SQL query and
embedded within the WHERE clause.
A subquery is used to return data that will be used in the main query as a condition to further
restrict the data to be retrieved.
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along
with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
There are a few rules that subqueries must follow −
• Subqueries must be enclosed within parentheses.
• A subquery can have only one column in the SELECT clause, unless multiple columns
are in the main query for the subquery to compare its selected columns.
• An ORDER BY command cannot be used in a subquery, although the main query can
use an ORDER BY. The GROUP BY command can be used to perform the same
function as the ORDER BY in a subquery.
• Subqueries that return more than one row can only be used with multiple value operators
such as the IN operator.
• The SELECT list cannot include any references to values that evaluate to a BLOB,
ARRAY, CLOB, or NCLOB.
• A subquery cannot be immediately enclosed in a set function.
• The BETWEEN operator cannot be used with a subquery. However, the BETWEEN
operator can be used within the subquery.
Program
Subqueries with the SELECT Statement
Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows

SELECT column_name [, column_name ]
FROM table1 [, table2 ]
WHERE column_name OPERATOR
(SELECT column_name [, column_name ]
FROM table1 [, table2 ]
[WHERE])
27

Output
Example
Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Now, let us check the following subquery with a SELECT statement.
SQL> SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS
WHERE SALARY > 4500) ;
This would produce the following result.
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+

Subqueries with the INSERT Statement


Subqueries also can be used with INSERT statements. The INSERT statement uses the data
returned from the subquery to insert into another table. The selected data in the subquery can be
modified with any of the character, date or number functions.
The basic syntax is as follows.
INSERT INTO table_name [ (column1 [, column2 ]) ]
SELECT [ *|column1 [, column2 ]
FROM table1 [, table2 ]
[ WHERE VALUE OPERATOR ]
28

Example
Consider a table CUSTOMERS_BKP with similar structure as CUSTOMERS table. Now to
copy the complete CUSTOMERS table into the CUSTOMERS_BKP table, you can use the
following syntax.
SQL> INSERT INTO CUSTOMERS_BKP
SELECT * FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS) ;

Subqueries with the UPDATE Statement


The subquery can be used in conjunction with the UPDATE statement. Either single or multiple
columns in a table can be updated when using a subquery with the UPDATE statement.
The basic syntax is as follows.
UPDATE table
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
Example
Assuming, we have CUSTOMERS_BKP table available which is backup of CUSTOMERS
table. The following example updates SALARY by 0.25 times in the CUSTOMERS table for
all the customers whose AGE is greater than or equal to 27.
SQL> UPDATE CUSTOMERS
SET SALARY = SALARY * 0.25
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE >= 27 );
This would impact two rows and finally CUSTOMERS table would have the following records.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 125.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 2125.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
29

Subqueries with the DELETE Statement


The subquery can be used in conjunction with the DELETE statement like with any other
statements mentioned above.
The basic syntax is as follows.
DELETE FROM TABLE_NAME
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
Example
Assuming, we have a CUSTOMERS_BKP table available which is a backup of the
CUSTOMERS table. The following example deletes the records from the CUSTOMERS table
for all the customers whose AGE is greater than or equal to 27.
SQL> DELETE FROM CUSTOMERS
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE >= 27 );
This would impact two rows and finally the CUSTOMERS table would have the following
records.
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+

Result

Thus the implementation of simple and nested queries were executed.


30

EX:NO 3 VIEWS, SAVE POINT, SYNONYMS, SEQUENCE , INDEXES

Aim:

To study and execute views,savepoints,synonyms,sequence and indexes.

PROCEDURE:

Switch on the system and go to the terminal and type 'sqlplus64


<username>/<password>@oracle . A new window open with the prompt <SQL>.Here we have
to type all the SQL commands.

VIEWS

In SQL, a view is a virtual table based on the result-set of an SQL statement.A view
contains rows and columns, just like a real table. The fields in a view are fields from one or
more real tables in the database.

SQL CREATE VIEW Statement

In SQL, a view is a virtual table based on the result-set of an SQL statement.A view contains
rows and columns, just like a real table. The fields in a view are fields from one or more real
tables in the database.

SQL CREATE VIEW Syntax

CREATE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE


condition

SQL Updating a View

You can update a view by using the following syntax:

SQL CREATE OR REPLACE VIEW Syntax

CREATE OR REPLACE VIEW view_name AS SELECT column_name(s) FROM table_name


WHERE condition

SQL Dropping a View

You can delete a view with the DROP VIEW command.

SQL DROP VIEW Syntax


31

DROP VIEW view_name

Program

Exercises

1.Create the table BOOK with the following details

NAME BOOK EDITION PRICE ISBN

-------------------- ---------- ---------- ---------- ----------

DBMS 5 2010 500 4566

OS 6 2007 600 3456

ADT 3 2008 800 2345

2.Create the table AUTHOR with the following details

NAME BOOK AUTHOR PUBLISHER ISBN

-------------------- ---------- -------------------- ------------------------------

DBMS 5 KORTH TATA 4566

CA 4 JHON PEARSON 35467

DS 9 DATE TATA 78976

3. Create view named author_view from AUTHOR to display book,name,publisher where

ISBN is 4566.

4. Change the publisher as MCGRAW in author_view where book=5.

5. Create view named authordetail from AUTHOR with name,ISBN,publisher where

book number is greater than 5.

6. Create view named book_view with name,book by joining two relations BOOK and

AUTHOR.
32

7. Create view named author_view1 from AUTHOR with name,ISBN,publisher where

book number is greater than 5.

8. Create view named author_view1 withauthor,name,ISBN from AUTHOR where book

number is greater than 4.

9.delete the view named author_view1.

INDEX

SQL automatically creates some indexes based on column types and attributes.

An index can also be given to a table column to optimize speeds.

SYNTAX:

create index <index name> on <table name(column name)>;

drop index <index name>;

Output

Exercises

1.Create an index named indauthor for the relation AUTHOR.

2.Delete an index indauthor.

Sample output

SQL>create index indauthor on AUTHOR(book);

index created

SQL>drop index indauthor;

index dropped.

Savepoint

TCL COMMANDS:
33

1. COMMIT

2. ROLLBACK

3. SAVEPOINT

SYNTAX:

COMMIT:

This command is used for save the work done. The syntax is:

COMMIT;

ROLLBACK:

This command is used to restore the database to original since the last commit.
The syntax is:

ROLLBACK TO <save point id>;

ROLLBACK;

SAVEPOINT:

Savepoint is not a command. It is only a marker.

A savepoint is a point in a transaction that you can roll the transaction back to
without rolling back the entire transaction.

Identify a point in a transaction to which you can later rollback.


SAVEPOINT <save point id>;

DCL COMMANDS:

1. GRANT

2. REVOKE

GRANT:

To grant permission for a particular user name.

REVOKE:

To get back the permission for a particular user name.


34

EXERCISES:

1. Create a transaction by creating a table project with the fields project name,dept
name,no.of employees, start date(SD),completion date(CD),project manager name,
budget.

2. Insert the values in to the table.

3. Display the project table.

4. Create a savepoint s1.

5. Update the completion date for any one of the project.

6. Update the details of a project manager and display all the records from the table.

7. Create a savepoint s2. Delete the details of project whose budget is less than 50000 and
display all the records from the table.

8. Undo all changes made after the creation of the savepoint s2 and display all the records
from the table.

9. Show the details of the project before any updation.

10. Save the records permanently in the table.

Result

Thus, the implementation of views, savepoints, synonyms, sequence and indexes were
executed.
35

EX:NO 4 DATABASE PROGRAMMING: IMPLICIT AND EXPLICIT CURSORS

Aim:

To study and execute implicit and explicit cursors.

PROCEDURE:

Switch on the system and go to the terminal and type 'sqlplus64


<username>/<password>@oracle . A new window open with the prompt <SQL>.Here we have
to type all the SQL commands.

Cursors

Oracle creates a memory area, known as the context area, for processing an SQL statement,
which contains all the information needed for processing the statement; for example, the number
of rows processed, etc.
A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor. A
cursor holds the rows (one or more) returned by a SQL statement. The set of rows the cursor
holds is referred to as the active set.
You can name a cursor so that it could be referred to in a program to fetch and process the rows
returned by the SQL statement, one at a time. There are two types of cursors −
• Implicit cursors
• Explicit cursors

Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed,
when there is no explicit cursor for the statement. Programmers cannot control the implicit
cursors and the information in it.
Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor is
associated with this statement. For INSERT operations, the cursor holds the data that needs to be
inserted. For UPDATE and DELETE operations, the cursor identifies the rows that would be
affected.
Program
In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which always
has attributes such as %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT. The
SQL cursor has additional attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS,
designed for use with the FORALL statement. The following table provides the description of
the most used attributes −
36

S.No Attribute & Description

%FOUND

1 Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more rows
or a SELECT INTO statement returned one or more rows. Otherwise, it returns FALSE.

%NOTFOUND

2 The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or DELETE


statement affected no rows, or a SELECT INTO statement returned no rows. Otherwise, it
returns FALSE.

%ISOPEN

3 Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor
automatically after executing its associated SQL statement.

%ROWCOUNT

4 Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement, or


returned by a SELECT INTO statement.

Any SQL cursor attribute will be accessed as sql%attribute_name as shown below in the
example.
Output
Example
We will be using the CUSTOMERS table we had created and used in the previous chapters.
Select * from customers;

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
37

+----+----------+-----+-----------+----------+

The following program will update the table and increase the salary of each customer by 500 and
use the SQL%ROWCOUNT attribute to determine the number of rows affected −
6 customers selected

PL/SQL procedure successfully completed.

If you check the records in customers table, you will find that the rows have been updated −
Select * from customers;

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2500.00 |
| 2 | Khilan | 25 | Delhi | 2000.00 |
| 3 | kaushik | 23 | Kota | 2500.00 |
| 4 | Chaitali | 25 | Mumbai | 7000.00 |
| 5 | Hardik | 27 | Bhopal | 9000.00 |
| 6 | Komal | 22 | MP | 5000.00 |
+----+----------+-----+-----------+----------+

Explicit Cursors
Explicit cursors are programmer-defined cursors for gaining more control over the context area.
An explicit cursor should be defined in the declaration section of the PL/SQL Block. It is created
on a SELECT Statement which returns more than one row.
The syntax for creating an explicit cursor is −
CURSOR cursor_name IS select_statement;

Working with an explicit cursor includes the following steps −


5. Declaring the cursor for initializing the memory
6. Opening the cursor for allocating the memory
7. Fetching the cursor for retrieving the data
8. Closing the cursor to release the allocated memory

Declaring the Cursor


Declaring the cursor defines the cursor with a name and the associated SELECT statement. For
example −
38

CURSOR c_customers IS
SELECT id, name, address FROM customers;

Opening the Cursor


Opening the cursor allocates the memory for the cursor and makes it ready for fetching the rows
returned by the SQL statement into it. For example, we will open the above defined cursor as
follows −
OPEN c_customers;

Fetching the Cursor


Fetching the cursor involves accessing one row at a time. For example, we will fetch rows from
the above-opened cursor as follows −
FETCH c_customers INTO c_id, c_name, c_addr;

Closing the Cursor


Closing the cursor means releasing the allocated memory. For example, we will close the above-
opened cursor as follows −
CLOSE c_customers;

Example:

SQL> create table cur(itemno number(1),priceno number(1), duedate varchar2(20),delidate


varchar2(20));

table created

SQL> insert into cur values(&itemno,&priceno,'&duedate','&delidate');

Enter value for itemno: 1

Enter value for priceno: 0

Enter value for duedate: 6-jan-07

Enter value for delidate: 10-jan-07

old 1: insert into cur values(&itemno,&priceno,'&duedate','&delidate')

new 1: insert into cur values(1,0,'6-jan-07','10-jan-07')

1 row created.
39

SQL> /

Enter value for itemno: 2

Enter value for priceno: 0

Enter value for duedate: 9-mar-18

Enter value for delidate: 11-mar-18

old 1: insert into cur values(&itemno,&priceno,'&duedate','&delidate')

new 1: insert into cur values(2,0,'9-mar-18','11-mar-18')

1 row created.

SQL> /

Enter value for itemno: 3

Enter value for priceno: 0

Enter value for duedate: 1-feb-06

Enter value for delidate: 9-feb-06

old 1: insert into cur values(&itemno,&priceno,'&duedate','&delidate')

new 1: insert into cur values(3,0,'1-feb-06','9-feb-06')

1 row created.

SQL> /

Enter value for itemno: 4

Enter value for priceno: 0

Enter value for duedate: 2-dec-05

Enter value for delidate: 23-dec-05

old 1: insert into cur values(&itemno,&priceno,'&duedate','&delidate')

new 1: insert into cur values(4,0,'2-dec-05','23-dec-05')

1 row created.
40

SQL> /

Enter value for itemno: 5

Enter value for priceno: 0

Enter value for duedate: 5-sep-07

Enter value for delidate: 5-sep-07

old 1: insert into cur values(&itemno,&priceno,'&duedate','&delidate')

new 1: insert into cur values(5,0,'5-sep-07','5-sep-07')

1 row created.

SQL> select * from cur;

ITEMNO PRICENO DUEDATE DELIDATE

---------- ---------- -------------------- --------------------

1 4 9-jan-09 10-jan-10

1 0 6-jan-07 10-jan-07

2 0 9-mar-18 11-mar-18

3 0 1-feb-06 9-feb-06

4 0 2-dec-05 23-dec-05

5 0 5-sep-07 5-sep-07

6 rows selected.

SQL> commit;

Commit complete.

SQL> declare

cursor disc is select * from cur;

ds disc % rowtype;

begin
41

for ds in disc loop

if ds.delidate<ds.duedate then

update cur set priceno=3 where delidate<duedate;

else if ds.delidate=ds.duedate then

update cur set priceno=6 where delidate=duedate;

else if ds.delidate>ds.duedate then

update cur set priceno=2 where delidate>duedate;

end if;

end if;

end if;

end loop;

end;

/ 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

PL/SQL procedure successfully completed.

SQL> select * from cur;

ITEMNO PRICENO DUEDATE DELIDATE

---------- ---------- -------------------- --------------------

1 3 9-jan-09 10-jan-10

1 3 6-jan-07 10-jan-07

2 3 9-mar-18 11-mar-18

3 2 1-feb-06 9-feb-06

4 2 2-dec-05 23-dec-05

5 6 5-sep-07 5-sep-07

6 rows selected.
42

Result

Thus, the cursor implementation such as implicit and explicit were executed.
43

EX:NO 5 PROCEDURES AND FUNCTIONS

Aim:

To study and execute procedures and functions.

PROCEDURE:

Switch on the system and go to the terminal and type 'sqlplus64


<username>/<password>@oracle . A new window open with the prompt <SQL>.Here we have
to type all the SQL commands.

Procedure:

A stored procedure in PL/SQL is nothing but a series of declarative SQL statements which can
be stored in the database catalogue. A procedure can be thought of as a function or a method.
They can be invoked through triggers, other procedures, or applications on Java, PHP etc.

A stored procedure is a set of Structured Query Language (SQL) statements with an assigned
name, which are stored in a relational database management system as a group, so it can be
reused and shared by multiple programs.

Function:

Function must return a value but in Stored Procedure it is optional. Even a procedure can return
zero or n values. Functions can have only input parameters for it whereas Procedures can have
input or output parameters . Functions can be called from Procedure whereas Procedures cannot
be called from a Function.

Program/ output

Example:

SQL> create table emplye (empno number(6),empname varchar2(20),grade varchar2(20),salary


number(6));

Table created.

SQL> insert into emplye values(&empno,'&empname','&empgrade',&salary);

Enter value for empno: 101

Enter value for empname: rohan

Enter value for empgrade: designer


44

Enter value for salary: 15000

old 1: insert into emplye values(&empno,'&empname','&empgrade',&salary)

new 1: insert into emplye values(101,'rohan','designer',15000)

1 row created.

SQL> /

Enter value for empno: 102

Enter value for empname: swadeep

Enter value for empgrade: artist

Enter value for salary: 20000

old 1: insert into emplye values(&empno,'&empname','&empgrade',&salary)

new 1: insert into emplye values(102,'swadeep','artist',20000)

1 row created.

SQL> /

Enter value for empno: 103

Enter value for empname: varsha

Enter value for empgrade: architect

Enter value for salary: 50000

old 1: insert into emplye values(&empno,'&empname','&empgrade',&salary)

new 1: insert into emplye values(103,'varsha','architect',50000)

1 row created.

SQL> /

Enter value for empno: 104

Enter value for empname: rishwanth

Enter value for empgrade: supervisor

Enter value for salary: 38000


45

old 1: insert into emplye values(&empno,'&empname','&empgrade',&salary)

new 1: insert into emplye values(104,'rishwanth','supervisor',38000)

1 row created.

SQL> create table departmt(grade varchar2(20),salary number(6));

Table created.

SQL> insert into departmt values('&grade',&salary);

Enter value for grade: designer

Enter value for salary: 15000

old 1: insert into departmt values('&grade',&salary)

new 1: insert into departmt values('designer',15000)

1 row created.

SQL> /

Enter value for grade: artist

Enter value for salary: 20000

old 1: insert into departmt values('&grade',&salary)

new 1: insert into departmt values('artist',20000)

1 row created.

SQL> /

Enter value for grade: architect

Enter value for salary: 50000

old 1: insert into departmt values('&grade',&salary)

new 1: insert into departmt values('architect',50000)

1 row created.
46

SQL> /

Enter value for grade: lecturer

Enter value for salary: 25000

old 1: insert into departmt values('&grade',&salary)

new 1: insert into departmt values('lecturer',25000)

1 row created.

SQL> select * from departmt;

GRADE SALARY

-------------------- ----------

designer 15000

artist 20000

architect 50000

lecturer 25000

SQL> select * from emplye;

EMPNO EMPNAME GRADE SALARY

---------- -------------------- -------------------- ----------

101 rohan designer 15000

102 swadeep artist 20000

103 varsha architect 50000

104 rishwanth supervisor 38000

SQL> create or replace procedure changesalary(gr char,sal number) is

cnt number(5):0;

begin

select count(*)into cnt from departmt where grade=gr;


47

if cnt=0 then

insert into departmt values(gr,sal);

dbms_output.put_line('salary for this grade is inserted');

else

update departmt set salary=sal where grade=gr;

dbms_output.put_line('salary for this is updated');

end if;

update emplye set salary=sal where grade=gr;

end;

/ 2 3 4 5 6 7 8 9 10 11 12 13 14

Warning: Procedure created with compilation errors.

SQL>

create procedure changesalary(gr char,sal number) is

cnt number(5):0;

begin

select count(*)into cnt from departmt where grade=gr;

if cnt=0 then

insert into departmt values(gr,sal);

dbms_output.put_line('salary for this grade is inserted');

else

update departmt set salary=sal where grade=gr;

dbms_output.put_line('salary for this is updated');

end if;
48

update emplye set salary=sal where grade=gr;

end;

execute changesalary(‘designer’,35000);

PL/SQL procedure successfully completed.

SQL>select* from emplye;

SQL> Select * from departmt;

execute changesalary(‘supervisor’,40000);

PL/SQL procedure successfully completed.

SQL>select* from emplye;

SQL> Select * from departmt;


49

Functions

Example:

create or replace function fact(n number)

return number is

s number:=1;

i number;

begin

for i in 1..n

loop

s:=s*I;

end loop;

return(s);

end;

SQL> DECLARE

num number;

factorial number;

FUNCTION fact(x number)

RETURN number

IS

f number;

BEGIN

IF x=0 THEN

f := 1;
50

ELSE

f := x * fact(x-1);

END IF;

RETURN f;

END;

BEGIN

num:= 6;

factorial := fact(num);

dbms_output.put_line(' Factorial '|| num || ' is ' || factorial);

END;

/ 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

Factorial 6 is 720

PL/SQL procedure successfully completed.

Result

Thus the functions and procedures were successfully completed.


51

EX.No:6 TRIGGERS

Aim:

To study and execute triggers.


PROCEDURE:

Switch on the system and go to the terminal and type 'sqlplus64


<username>/<password>@oracle . A new window open with the prompt <SQL>.Here we have
to type all the SQL commands.

Triggers:
Triggers are stored programs, which are automatically executed or fired when some events
occur.

Triggers are, in fact, written to be executed in response to any of the following events −
A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
A database definition (DDL) statement (CREATE, ALTER, or DROP).
A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).
Triggers can be defined on the table, view, schema, or database with which the event is
associated.
Program

Creating Triggers
The syntax for creating a trigger is −
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
52

EXCEPTION
Exception-handling-statements
END;

Where,
• CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an
existing trigger with the trigger_name.
• {BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be
executed. The INSTEAD OF clause is used for creating trigger on a view.
• {INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML
operation.
• [OF col_name] − This specifies the column name that will be updated.
• [ON table_name] − This specifies the name of the table associated with the
trigger.
• [REFERENCING OLD AS o NEW AS n] − This allows you to refer new and
old values for various DML statements, such as INSERT, UPDATE, and DELETE.
• [FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be
executed for each row being affected. Otherwise the trigger will execute just once when
the SQL statement is executed, which is called a table level trigger.
• WHEN (condition) − This provides a condition for rows for which the trigger
would fire. This clause is valid only for row-level triggers.
Output
Example
CUSTOMERS table

SQL> create table customers(id number(4),name varchar2(20),age number(4),address


varchar2(20),salary number(6));

Table created.

SQL> insert into customers values('&id','&name','&age','&address','&salary');

Enter value for id: 1

Enter value for name: ramesh

Enter value for age: 32


53

Enter value for address: ahmedabad

Enter value for salary: 2000

old 1: insert into customers values('&id','&name','&age','&address','&salary')

new 1: insert into customers values('1','ramesh','32','ahmedabad','2000')

1 row created.

SQL> /

Enter value for id: 2

Enter value for name: khilan

Enter value for age: 25

Enter value for address: delhi

Enter value for salary: 1500

old 1: insert into customers values('&id','&name','&age','&address','&salary')

new 1: insert into customers values('2','khilan','25','delhi','1500')

1 row created.

SQL> /

Enter value for id: 3

Enter value for name: kaushik

Enter value for age: 23

Enter value for address: Kota

Enter value for salary: 2000

old 1: insert into customers values('&id','&name','&age','&address','&salary')

new 1: insert into customers values('3','kaushik','23','Kota','2000')

1 row created.

SQL> /

Enter value for id: 4


54

Enter value for name: chaitali

Enter value for age: 25

Enter value for address: Mumbai

Enter value for salary: 6500

old 1: insert into customers values('&id','&name','&age','&address','&salary')

new 1: insert into customers values('4','chaitali','25','Mumbai','6500')

1 row created.

SQL> /

Enter value for id: 5

Enter value for name: Hardik

Enter value for age: 27

Enter value for address: Bhopal

Enter value for salary: 8500

old 1: insert into customers values('&id','&name','&age','&address','&salary')

new 1: insert into customers values('5','Hardik','27','Bhopal','8500')

1 row created.

SQL> /

Enter value for id: 6

Enter value for name: Komal

Enter value for age: 22

Enter value for address: MP

Enter value for salary: 4500

old 1: insert into customers values('&id','&name','&age','&address','&salary')

new 1: insert into customers values('6','Komal','22','MP','4500')

1 row created.
55

SQL> select * from customers;

ID NAME AGE ADDRESS SALARY

---------- -------------------- ---------- -------------------- ----------

1 ramesh 32 ahmedabad 2000

2 khilan 25 delhi 1500

3 kaushik 23 Kota 2000

4 chaitali 25 Mumbai 6500

5 Hardik 27 Bhopal 8500

6 Komal 22 MP 4500

6 rows selected.

The following program creates a row-level trigger for the customers table that would fire for
INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This
trigger will display the salary difference between the old values and new values −
SQL> CREATE OR REPLACE TRIGGER display_salary_changes
BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;
/ 2 3 4 5 6 7 8 9 10 11 12 13

Trigger created.

The following points need to be considered here −


9. OLD and NEW references are not available for table-level triggers, rather you can
use them for record-level triggers.
56

10. If you want to query the table in the same trigger, then you should use the AFTER
keyword, because triggers can query the table or change it again only after the initial
changes are applied and the table is back in a consistent state.
11. The above trigger has been written in such a way that it will fire before any
DELETE or INSERT or UPDATE operation on the table, but you can write your trigger
on a single or multiple operations, for example BEFORE DELETE, which will fire
whenever a record will be deleted using the DELETE operation on the table.

Triggering a Trigger
Let us perform some DML operations on the CUSTOMERS table. Here is one INSERT
statement, which will create a new record in the table −

SQL> INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (7, 'Kriti', 22, 'HP', 7500.00 );

When a record is created in the CUSTOMERS table, the above create trigger,
display_salary_changes will be fired and it will display the following result −

Old salary:
New salary: 7500
Salary difference:

1 row created.

Because this is a new record, old salary is not available and the above result comes as null. Let
us now perform one more DML operation on the CUSTOMERS table. The UPDATE statement
will update an existing record in the table −
SQL> UPDATE customers
SET salary = salary + 500
WHERE id = 2;

1 row updated.
When a record is updated in the CUSTOMERS table, the above create trigger,
display_salary_changes will be fired and it will display the following result −

Old salary: 1500


New salary: 2000
Salary difference: 500
57

Result
Thus, the program was executed successfully
58

EX.No:7 EXCEPTION HANDLING

Aim:

To study and execute exception handling.

PROCEDURE:

Switch on the system and go to the terminal and type 'sqlplus64’


<username>/<password>@oracle . A new window open with the prompt <SQL>.Here we have
to type all the SQL commands.

Exception:

An exception is an error condition during a program execution. PL/SQL supports programmers


to catch such conditions using EXCEPTION block in the program and an appropriate action is
taken against the error condition. There are two types of exceptions −
System-defined exceptions
User-defined exceptions

Syntax for Exception Handling


The general syntax for exception handling is as follows. Here you can list down as many
exceptions as you can handle. The default exception will be handled using WHEN others THEN

DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling goes here >
WHEN exception1 THEN
exception1-handling-statements
WHEN exception2 THEN
exception2-handling-statements
WHEN exception3 THEN
exception3-handling-statements
........
WHEN others THEN
exception3-handling-statements
END;
59

Program
Example
Let us write a code to illustrate the concept. We will be using the CUSTOMERS table we had
created and used in the previous chapters −
DECLARE
c_id customers.id%type := 8;
c_name customerS.Name%type;
c_addr customers.address%type;
BEGIN
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);

EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/

When the above code is executed at the SQL prompt, it produces the following result −
No such customer!

PL/SQL procedure successfully completed.

User-defined Exceptions
PL/SQL allows you to define your own exceptions according to the need of your program. A
user-defined exception must be declared and then raised explicitly, using either a RAISE
statement or the procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR.
The syntax for declaring an exception is −
DECLARE
my-exception EXCEPTION;
60

Output
Example
The following example illustrates the concept. This program asks for a customer ID, when the
user enters an invalid ID, the exception invalid_id is raised.
DECLARE
c_id customers.id%type := &cc_id;
c_name customerS.Name%type;
c_addr customers.address%type;
-- user defined exception
ex_invalid_id EXCEPTION;
BEGIN
IF c_id <= 0 THEN
RAISE ex_invalid_id;
ELSE
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
END IF;

EXCEPTION
WHEN ex_invalid_id THEN
dbms_output.put_line('ID must be greater than zero!');
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/

When the above code is executed at the SQL prompt, it produces the following result −
Enter value for cc_id: -6 (let's enter a value -6)
old 2: c_id customers.id%type := &cc_id;
new 2: c_id customers.id%type := -6;
ID must be greater than zero!

PL/SQL procedure successfully completed.


61

Result

Thus the program was completed successfully.


62

EX.NO 8 DATABASE DESIGN USING ER MODELING, NORMALIZATION AND


IMPLEMENTATION FOR ANY APPLICATION

AIM:

To study and work with ER diagrams and simple SQL queries.

PROCEDURE:

Switch on the system and go to the terminal and type 'sqlplus64


<username>/<password>@oracle . A new window open with the prompt <SQL>.Here we have
to type all the SQL commands.

SQL
• SQL stands for Structured Query Language
• SQL lets you access and manipulate databases
• SQL is an ANSI (American National Standards Institute) standard

Learn to design ER-Diagrams


Basic Concepts
• Understand the requirements
• Don't think physical; think conceptual
• Don't think process; think structure
• Don't think navigation; think relationship

Entity - Attributes
Entity
• Something that exists and is capable of being described
• Entities are comprised of attributes
Attributes
An attribute is a characteristic of an entity.
Every attribute does one of three things:
• Describe
• Identify
• Relate
Relationships
• Define how the different entities are associated with each other
• A relationship is defined by the keys of the participating entities
63

• Primary - foreign key


• Parent - child relationship

ER-Diagram basic symbols

ER-Diagram examples (1/2)


64

ER-Diagram examples (2/2)

The logical-to-physical mapping


• Entities into tables
• Attributes into columns
• Domains into data types & constraints
• Domain - an area of interest or an area over which a person has control

Key Concepts
• Data Types
• Constraints
• Primary Key
• Nullability
• Fixed- Variable length
• Identity Columns
• Indexes (Clustered - Non Clustered)

Program

Primary and foreign keys


SQL PRIMARY KEY Constraint
The PRIMARY KEY constraint uniquely identifies each record in a database table.
Primary keys must contain UNIQUE values.
65

A primary key column cannot contain NULL values.


Most tables should have a primary key, and each table can have only ONE primary key.
SQL FOREIGN KEY Constraint
A FOREIGN KEY in one table points to a PRIMARY KEY in another table.

SQL Constraints
SQL constraints are used to specify rules for the data in a table.
If there is any violation between the constraint and the data action,
the action is aborted by the constraint.
Constraints can be specified when the table is created
or after the table is created.
SQL CREATE TABLE + CONSTRAINT Syntax
CREATE TABLE table_name
(
column_name1 data_type(size) constraint_name,
column_name2 data_type(size) constraint_name,
column_name3 data_type(size) constraint_name,
....
);

In SQL, we have the following constraints:


• NOT NULL - Indicates that a column cannot store NULL value
• UNIQUE - Ensures that each row for a column must have a unique value
• PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Ensures that a column
(or combination of two or more columns) have a unique identity which helps to find a
particular record in a table more easily and quickly
• FOREIGN KEY - Ensure the referential integrity of the data in one table to match values
in another table
• CHECK - Ensures that the value in a column meets a specific condition
• DEFAULT - Specifies a default value for a column

Output

SQL Select Queries


Always remeber that sql queries resemble spoken language!
SELECT column_name1, column_name2, ...
FROM table_name
WHERE condition
66

GROUP BY column_name1, column_name2, ...


ORDER BY column_name1, ...;

Example
--Display last and first name and the title of the employees that are situated in USA and are born
before 1960, alphabetically by their names.
SELECT EmployeeID, LastName, FirstName, Title
FROM Employees
WHERE Country = 'USA'
AND BirthDate < '1960-01-01'
ORDER BY LastName, FirstName;

SQL LIKE Operator & Wildcards


The LIKE operator is used to search for a specified pattern in a column.
Wildcard characters are used with the SQL LIKE operator.
We will need the following:
1. `% A substitute for zero or more characters
2. `_ A substitute for a single character

Examples
-- Returns Customers from Bern, Berlin and Bergamo
SELECT * FROM Customers
WHERE City LIKE 'ber%';
-- Returns Customers from Bruxelles, Resende, Buenos Aires etc.
SELECT * FROM Customers
WHERE City LIKE '%es%';
-- Returns Customers with regions CA and WA
select *
from Customers
where Region like '_A'

NULL values
• NULL values represent missing unknown data
• By default a column can hold NULL values
• NULL is different from zero
• To check for NULL we use IS or IS NOT NULL instead of = or <>.
Syntax example:
-- Get all customers for whom we have fax numbers.
SELECT *
67

FROM Customers
WHERE Fax IS NOT NULL;

-- Get all customers for whom we do not have fax numbers.


SELECT *
FROM Customers
WHERE Fax IS NULL;

Result

Thus, the program was executed successfully


68

EX.NO:9 DATABASE CONNECTIVITY WITH FRONT END TOOLS

Aim:

To study and execute database.


PROCEDURE:

To start the XAMPP

PHP and Mysql connectivity


open terminal and type

student@IT20:~$ sudo /opt/lampp/lampp start


[sudo] password for student:
Starting XAMPP for Linux 5.6.8-0...
XAMPP: Starting Apache...ok.
XAMPP: Starting MySQL...ok.
student@IT20:~$ sudo chmod -R 777 /opt/lampp/htdocs
student@IT20:~$ gedit

Run the program


open browser
http://localhost or
http://localhost/xampp/
69

click->phpmyadmin->new-> create database->(give name)->table name->(give name)


insert field(name, rollno, mark)
70

Run

Program

Basic PHP Syntax


A PHP script can be placed anywhere in the document.
A PHP script starts with <?php and ends with ?>:
<?php
// PHP code goes here
?>
The default file extension for PHP files is ".php".
A PHP file normally contains HTML tags, and some PHP scripting code.
Example
<!DOCTYPE html>
<html>
<body>

<h1>My first PHP page</h1>


71

<?php
echo "Hello World!";
?>

</body>
</html>

Output

My first PHP page

Hello World!

Example: gedit

save the program (filename.php) Ex: sample.php

<?php

//Sample Database Connection Script


//Setup connection variables, such as database username
//and password
$servername="localhost";
$username="root";
$password="";
$dbname="college";
$usertable="student";
$yourfield = "your_field";
72

//Connect to the database


$connection = mysql_connect($servername, $username, $password);
mysql_select_db($dbname, $connection);

//Setup our query


$query = "SELECT * FROM $usertable";

//Run the Query


$result = mysql_query($query);

//If the query returned results, loop through


// each result
if($result)
{
while($row = mysql_fetch_array($result))
{
echo "name: " . $row["name"]. "<br>" . "rollno:" . $row["rollno"]. "<br>". "mark" .
$row["mark"]."<br>";
}
}

?>

Run the program


open browser

http://localhost/sample.php
73

output
name: jemila
rollno:151
mark200
name: ramala
rollno:15
mark300
name: persha
rollno:18
mark500

Result
Thus, the php program was executed successfully
74

EX.NO 10 CASE STUDY USING REAL LIFE DATABASE APPLICATIONS


Aim:

To study and execute database applications.


PROCEDURE:

To start the XAMPP

PHP and Mysql connectivity


open terminal and type

student@IT20:~$ sudo /opt/lampp/lampp start


[sudo] password for student:
Starting XAMPP for Linux 5.6.8-0...
XAMPP: Starting Apache...ok.
XAMPP: Starting MySQL...ok.
student@IT20:~$ sudo chmod -R 777 /opt/lampp/htdocs
student@IT20:~$ gedit

Run the program


open browser
http://localhost or
http://localhost/xampp/
75

click->phpmyadmin->new-> create database->(give name)->table name->(give name)


insert field(employeename, employeeid, salary)
Example: gedit
save the program (filename.php) Ex: sample.php
<?php
//Sample Database Connection Script
//Setup connection variables, such as database username
//and password
$servername="localhost";
$username="root";
$password="";
$dbname="employee";
$usertable="company";
$yourfield = "your_field";
//Connect to the database
76

$connection = mysql_connect($servername, $username, $password);


mysql_select_db($dbname, $connection);
//Setup our query
$query = "SELECT * FROM $usertable";
//Run the Query
$result = mysql_query($query);
//If the query returned results, loop through
// each result
if($result)
{
while($row = mysql_fetch_array($result))
{
echo "employeename: " . $row["employeename"]. "<br>" . "employeeid:" .
$row["employeeid"]. "<br>". "salary" . $row["salary"]."<br>";
}
}
?>
Run the program
open browser

http://localhost/sample.php

output
employeename: jemila
employeeid:151
salary20000
employeename: ramala
employeeid:15
salary 30000
77

Result
Thus the php program was executed successfully
78

OPEN ENDED EXERCISE

DATABASE APPLICATIONS AND THE WEB

Most of the services we enjoy on the Web are provided by web database applications. Web-
based email, online shopping, forums and bulletin boards, corporate web sites, and sports and
news portals are all database-driven. To build a modern web site, you need to develop a database
application.

This book presents a highly popular, easy, low-cost way to bring together the Web and databases
to build applications. The most popular database management system used in these solutions is
MySQL, a very fast and easy-to-use system distributed under an Open Source license by its
manufacturer, MySQL AB. We discuss MySQL in detail in this book.

With a web server such as Apache (we assume Apache in this book, although the software
discussed here works with other web servers as well) and MySQL, you have most of what you
need to develop a web database application. The key glue you need is a way for the web server to
talk to the database; in other words, a way to incorporate database operations into web pages.
The most popular glue that accomplishes this task is PHP.

PHP is an open source project of the Apache Software Foundation and it’s the most popular
Apache web server add-on module, with around 53% of the Apache HTTP servers having PHP
capabilities.[1] PHP is particularly suited to web database applications because of its integration
tools for the Web and database environments. In particular, the flexibility of embedding scripts
in HTML pages permits easy integration of HTML presentation and code. The database tier
integration support is also excellent, with more than 15 libraries available to interact with almost
all popular database servers. In this book, we present a comprehensive view of PHP along with a
number of powerful extensions provided by a repository known as PEAR.

Apache, MySQL, and PHP can run on a wide variety of operating systems. In this book, we
show you how to use them on Linux, Mac OS X, and Microsoft Windows.

This is an introductory book, but it gives you the sophisticated knowledge you need to build
applications properly. This includes critical tasks such as checking user input, handling errors
79

robustly, and locking your database operations to avoid data corruption. Most importantly, we
explain the principles behind good web database applications. You’ll finish the book with not
only the technical skills to create an application, but also an appreciation for the strategies that
make an application secure, reliable, maintainable, and expandable.

The Web

When you browse the Web, you use your web browser to request resources from a web server
and the web server responds with the resources. You make these requests by filling in and
submitting forms, clicking on links, or typing URLs into your browser. Often, resources are
static HTML pages that are displayed in the browser. Figure 1-1 shows how a web browser
communicates with a web server to retrieve this book’s home page. This is the classic two-tier or
client-server architecture used on the Web.

Figure 1-1. A two-tier architecture where a web browser makes a request and the web server
responds

You might also like