DBMS Lab Manual for MCA Students
DBMS Lab Manual for MCA Students
ENIKEPADU, VIJAYAWADA
Prepared by
[Link]
Objective:
To understand the different issues involved in the design and implementation of a database system
To understand and use data definition language to write query for a database
Theory:
Oracle has many tools such as SQL * PLUS, Oracle Forms, Oracle Report Writer, Oracle Graphics
etc.
SQL * PLUS: The SQL * PLUS tool is made up of two distinct parts. These are
Interactive SQL: Interactive SQL is designed for create, access and manipulate data structures
like tables and indexes.
PL/SQL: PL/SQL can be used to developed programs for different applications.
Oracle Forms: This tool allows you to create a data entry screen along with the suitable menu
objects. Thus it is the oracle forms tool that handles data gathering and data validation in a
commercial application.
Report Writer: Report writer allows programmers to prepare innovative reports using data
from the oracle structures like tables, views etc. It is the report writer tool that handles the reporting
section of commercial application.
Oracle Graphics: Some of the data can be better represented in the form of pictures. The oracle
graphics tool allows programmers to prepare graphs using data from oracle structures like tables,
views etc.
Structured Query Language is a database computer language designed for managing data in relational
database management systems (RDBMS), and originally based upon Relational Algebra. Its scope
includes data query and update, schema creation and modification, and data access control.
SQL was one of the first languages for Edgar F. Codd's relational model and became the most widely
used language for relational databases.
IBM developed SQL in mid of 1970’s.
Oracle incorporated in the year 1979.
SQL used by IBM/DB2 and DS Database Systems.
SQL adopted as standard language for RDBS by ASNI in 1989.
DATA TYPES:
1. CHAR (Size): This data type is used to store character strings values of fixed length. The size in
brackets determines the number of characters the cell can hold. The maximum number of character is
255 characters.
2. VARCHAR (Size) / VARCHAR2 (Size): This data type is used to store variable length
alphanumeric data. The maximum character can hold is 2000 character.
3. NUMBER (P, S): The NUMBER data type is used to store number (fixed or floating point).
Number of virtually any magnitude may be stored up to 38 digits of precision. Number as large as
9.99 * 10 124. The precision (p) determines the number of places to the right of the decimal. If scale
is omitted then the default is zero. If precision is omitted, values are stored with their original
precision up to the maximum of 38 digits.
4. DATE: This data type is used to represent date and time. The standard format is DD- MM-YY as
in 17-SEP-2009. To enter dates other than the standard format, use the appropriate functions. Date
time stores date in the 24-Hours format. By default the time
in a date field is 12:00:00 am, if no time portion is specified. The default date for a date field is the
first day the current month.
5. LONG: This data type is used to store variable length character strings containing up to 2GB.
Long data can be used to store arrays of binary data in ASCII format. LONG values cannot be
indexed, and the normal character functions such as SUBSTR cannot be applied.
6. RAW: The RAW data type is used to store binary data, such as digitized picture or image. Data
loaded into columns of these data types are stored without any further conversion. RAW data type
can have a maximum length of 255 bytes. LONG RAW data type can contain up to 2GB.
Expressions, which can produce either scalar values or tables consisting of columns and rows of
data.
Predicates which specify conditions that can be evaluated to SQL three-valued logic
(3VL) Boolean truth values and which are used to limit the effects of statements and queries, or to
change program flow.
Queries which retrieve data based on specific criteria.
Statements which may have a persistent effect on schemas and data, or which may control
transactions, program flow, connections, sessions, or diagnostics.
SQL statements also include the semicolon (";") statement terminator. Though not required on
every platform, it is defined as a standard part of the SQL grammar.
Insignificant white space is generally ignored in SQL statements and queries, making it easier to
format SQL code for readability.
1. DATA DEFINITION LANGUAGE (DDL): The Data Definition Language (DDL) is used
to create and destroy databases and database objects. These commands will primarily be used
by database administrators during the setup and removal phases of a database project. Let's
take a look at the structure and usage of four basic DDL commands:
1. CREATE:
Example:
SQL> CREATE TABLE Student (sno NUMBER (3), sname CHAR (10), class CHAR (5));
2. ALTER:
(a) ALTER TABLE ...ADD...: This is used to add some extra fields into existing relation.
Syntax: ALTER TABLE relation_name ADD (new field_1 data_type(size), new field_2
data_type(size),..);
(b) ALTER TABLE...MODIFY...: This is used to change the width as well as data type of fields of
existing relations.
d)ALTER TABLE..RENAME...: This is used to change the name of fields in existing relations.
3. DROP TABLE: This is used to delete the structure of a relation. It permanently deletes the
records in the table.
SQL
3. Queries to Retrieve and Change Data: Select, Insert, Delete, and Update
6. Queries for Creating, Dropping, and Altering Tables, Views, and Constraints
8. Write a PL/SQL Code using Basic Variable, Anchored Declarations, and Usage of
Assignment Operation
10. Write a PL/SQL block using SQL and Control Structures in PL/SQL
11. Write a PL/SQL Code using Cursors, Exceptions and Composite Data Types
12. Write a PL/SQL Code using Procedures, Functions, and Packages FORMS
Program 1
1 .Character Functions:
Converts the first letter of each word to upper case and remaining letters to
Initcap
lowercase
Concat Joins values together you are limited to two arguments with concat
LENGTH('SQLFUNCTIONS')
----------------------
12
Number Functions:
Date Functions:
SYSDATE is a pseudo column that returns the current date and time. When we select sysdate it
will display in a dummy table called DUAL. Oracle date range between 1st jan 4712 BC and 31st
Dec 4712 AD.
Months_between It returns the numeric value. Finds the no. of months between date1
and date2, result may be positive or negative.
Add_months It returns the date datatype. Adds n number of calendar months to
date, n must be an integer and it can be negative
Next_day It returns the date datatype. Date of the next specified day of the week
following date1, char may be number representing a day, or a
character
MONTHS_BETWEEN(SYSDATE,HIREDATE)
--------------------------------
354.728983
352.632208
352.567692
351.212854
345.374144
14 rows selected.
Sunday 1
Monday 2
Tuesday 3
Wednesday 4
Thursday 5
Friday 6
Saturday 7
Conversion Functions:
To_char(number | date,[‘fmt’] Converts numbers or date to character format fmt
To_date Converts the char value representing date, into a date value
according to fmt specified. If fmt is omitted, format is DD-
MM-YYYY
Table created.
1 row created.
1 row created.
SQL> /
Enter value for id: 33
Enter value for name: sridhar
Enter value for mob: 9966778855
old 1: insert into student values(&id,'&name',&mob)
new 1: insert into student values(33,'sridhar',9966778855)
1 row created.
1 row created.
1 row created.
Q4) create a table std_mob (sid,mob_no) from student table with records also.
Table created.
5 rows created.
SID MOB_NO
---------- ----------
11 9988776655
22 9977886655
33 9966778855
44
55 9988667755
Table created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
SNAME
---------------
Dustin
Brutus
Lubber
Andy
Rusty
Horatio
Zorba
Horatio
Art
Bob
10 rows selected.
SNAME
---------------
Andy
Art
Bob
Brutus
Dustin
Horatio
Lubber
Rusty
Zorba
9 rows selected.
SNAME RATING
--------------- ----------
Dustin 7
Horatio 7
Q11) Find sailor names and ratings whose rating is greater than 7.
SNAME RATING
--------------- ----------
Lubber 8
Andy 8
Rusty 10
Zorba 10
Horatio 9
Q12) Find sailor names and rating whose rating is less than 6 using not.
SNAME RATING
--------------- ----------
Brutus 1
Art 3
Bob 3
Q13) Find sailor names and rating whose rating is between 3 and 7.
SNAME RATING
--------------- ----------
Dustin 7
Horatio 7
Art 3
Bob 3
Q14) Find sailor names and rating whose name starts with B.
SNAME RATING
--------------- ----------
Brutus 1
Bob 3
Q15) Find sailor names and rating whose name ends with y.
SNAME RATING
--------------- ----------
Andy 8
Rusty 10
Q15) Find sailor names and rating whose name contains the substring or.
SNAME RATING
--------------- ----------
Horatio 7
Zorba 10
Horatio 9
Q16) Find sailor names and rating whose name contains exactly 3 characters.
SQL> select sname,rating from sailors where sname like '_ _ _';
SNAME RATING
--------------- ----------
Art 3
Bob 3
Q17) Find sailor names and rating whose name does not contains letter r.
SQL> select sname,rating from sailors where sname not like '%r%';
SNAME RATING
--------------- ----------
Dustin 7
Andy 8
Rusty 10
Bob 3
Q18) Diasplay all sailor names and rating whose name does not contains letter r in increasing order of
rating
SQL> select sname,rating from sailors where sname not like '%r%' order by rating;
SNAME RATING
--------------- ----------
Bob 3
Dustin 7
Andy 8
Rusty 10
Q18) Display sailor names and rating whose name does not contains letter r and display in decreasing
order of rating.
SQL>select sname,rating from sailors where sname not like '%r%' order by rating desc;
SNAME RATING
--------------- ----------
Rusty 10
Andy 8
Dustin 7
Bob 3
Q19) Display sailor names and rating whose rating is 8 in alphabetical order.
SNAME RATING
--------------- ----------
Andy 8
Lubber 8
Q20) select sailor name and rating whose rating is either greater than 7 or rating less than 3
SNAME RATING
--------------- ----------
Brutus 1
Lubber 8
Andy 8
Rusty 10
Zorba 10
Horatio 9
6 rows selected.
Table created.
1 row created.
1 row created.
Q23) Create table reserves(sid,bid,day) where sid,bid,day as primary key and sid,did as foreign key
referencing the tables sailors and boats respectively.
Table created.
1 row created.
1 row created.
SQL> insert into reserves (sid, bid, day)
2 values (22, 104, '10/jul/98');
1 row created.
1 row created.
1 row created.
SQL> insert into reserves (sid, bid, day)
2 values (31, 104, '11/dec/98');
1 row created.
SQL> insert into reserves (sid, bid, day)
2 values (64, 101, '9/may/98');
1 row created.
1 row created.
Q25) Find the sailor names who have reserved atleast one boat.
SNAME BID
--------------- ----------
Dustin 101
Dustin 102
Dustin 103
Dustin 104
Lubber 102
Lubber 103
Lubber 104
Horatio 101
Horatio 102
Horatio 103
10 rows selected.
Q26) Find the sailors name who have reserved boat number 103.
SQL> select [Link],[Link] from sailors a, reserves b where [Link]=[Link] and [Link]=103;
SNAME BID
--------------- ----------
Dustin 103
Lubber 103
Horatio 103
Q27) Find the sailors name who have reserved boat ‘Marine’.
SQL> select [Link],[Link] from sailors a, reserves b,boats c where [Link]=[Link] and [Link]=[Link] and
[Link]='Marine';
SNAME BID
--------------- ----------
Dustin 104
Lubber 104
Q28) Find the sailors who have reserved red color boat.
SQL> select [Link], [Link], [Link] from sailors a, reserves b,boats c where [Link]=[Link] and
[Link]=[Link] and [Link]='red'
SNAME RATING BNAME
--------------- ---------- ----------
Dustin 7 Interlake
Dustin 7 Marine
Lubber 8 Interlake
Lubber 8 Marine
Horatio 7 Interlake
Q29) Find the sailors who have reserved either red or blue color boat.
Q30) Find the sailor names who have reserved both red and blue color boats.
Q31) Find the sailor names who have reserved red color boat but not blue color boat.
SQL> (select [Link] from sailors a, reserves b,boats c
2 where [Link]=[Link] and [Link]=[Link] and [Link]='red')
3 minus
4 (select [Link] from sailors a, reserves b,boats c
5 where [Link]=[Link] and [Link]=[Link] and [Link]='blue');
SNAME
---------------
Lubber
Q32) Find all the sailor names who reserved either red or blue color boats.
SQL> (select [Link] from sailors a, reserves b,boats c
2 where [Link]=[Link] and [Link]=[Link] and [Link]='red')
3 union
4 (select [Link] from sailors a, reserves b,boats c
5 where [Link]=[Link] and [Link]=[Link] and [Link]='blue');
SNAME
---------------
Dustin
Horatio
Lubber
Q33) Find all the sailor names(with duplicates) who reserved either red or blue color boats.
SNAME
---------------
Dustin
Dustin
Lubber
Lubber
Horatio
Dustin
Horatio
7 rows selected.
Q34) Find the sailors who have reserved atleast one boat using nested query.
SQL> select * from sailors where sid in (select sid from reserves);
SQL> select * from sailors where sid not in (select sid from reserves);
6 rows selected.
Q36) Find the sailors whose who have reserved boat number 103 using nested query.
Q37) Find the sailors who have not reserved red color boat.
7 rows selected.
Q38) Find the sailor names who reserved boat number 103
Q39) Find the sailor names who do not reserved boat number 103
SNAME
---------------
Brutus
Andy
Rusty
Horatio
Zorba
Art
Bob
7 rows selected.
Q40) Find the sailor names who reserved all the boats.
SNAME
---------------
Dustin
Program 3
Aim: Queries to Retrieve and Change Data: Select, Insert, Delete, and Update
Table created.
1 row created.
1 row created.
SQL> /
Enter value for id: 33
Enter value for name: sridhar
Enter value for mob: 9966778855
old 1: insert into student values(&id,'&name',&mob)
new 1: insert into student values(33,'sridhar',9966778855)
1 row created.
1 row created.
Q4) create a table std_mob (sid,mob_no) from student table with records also.
Table created.
5 rows created.
SID MOB_NO
---------- ----------
11 9988776655
22 9977886655
33 9966778855
44
55 9988667755
Table created.
Table created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
Table created.
1 row created.
1 row created.
Q10) Create table reserves(sid,bid,day) where sid,bid,day as primary key and sid,did as foreign key
referencing the tables sailors and boats respectively.
Table created.
1 row created.
1 row created.
1 row created.
1 row created.
SQL> insert into reserves (sid, bid, day)
2 values (31, 104, '11/dec/98');
1 row created.
SQL> insert into reserves (sid, bid, day)
2 values (64, 101, '9/may/98');
1 row created.
1 row created.
SNAME
---------------
Dustin
Brutus
Lubber
Andy
Rusty
Horatio
Zorba
Horatio
Art
Bob
10 rows selected.
9 rows selected.
SNAME RATING
--------------- ----------
Dustin 7
Horatio 7
Q15) Find sailor names and ratings whose rating is greater than 7.
SNAME RATING
--------------- ----------
Lubber 8
Andy 8
Rusty 10
Zorba 10
Horatio 9
Q16) Find sailor names and rating whose rating is less than 6 using not.
SNAME RATING
--------------- ----------
Brutus 1
Art 3
Bob 3
Q17) Find sailor names and rating whose rating is between 3 and 7.
SNAME RATING
--------------- ----------
Dustin 7
Horatio 7
Art 3
Bob 3
Q18) Find sailor names and rating whose name starts with B.
SNAME RATING
--------------- ----------
Brutus 1
Bob 3
Q19) Find sailor names and rating whose name ends with y.
SNAME RATING
--------------- ----------
Andy 8
Rusty 10
Q20) Find sailor names and rating whose name contains the substring or.
SNAME RATING
--------------- ----------
Horatio 7
Zorba 10
Horatio 9
Q21) Find sailor names and rating whose name contains exactly 3 characters.
SQL> select sname,rating from sailors where sname like '_ _ _';
SNAME RATING
--------------- ----------
Art 3
Bob 3
Q22) Find sailor names and rating whose name does not contains letter r.
SQL> select sname,rating from sailors where sname not like '%r%';
SNAME RATING
--------------- ----------
Dustin 7
Andy 8
Rusty 10
Bob 3
Q23) select sailor name and rating whose rating is either greater than 7 or rating less than 3
SNAME RATING
--------------- ----------
Brutus 1
Lubber 8
Andy 8
Rusty 10
Zorba 10
Horatio 9
6 rows selected.
Q24) Modify the color to yellow whose boat id=101.
1 row updated.
3 rows updated.
2 rows updated.
Table created.
1 row created.
SQL> /
Enter value for id: 66
Enter value for name: praneeth
Enter value for sal: 32000
old 1: insert into employee values(&id,'&name',&sal)
new 1: insert into employee values(66,'praneeth',32000)
1 row created.
SQL> /
Enter value for id: 55
Enter value for name: rajesh
Enter value for sal: 33000
old 1: insert into employee values(&id,'&name',&sal)
new 1: insert into employee values(55,'rajesh',33000)
1 row created.
1 row deleted.
2 rows deleted.
no rows selected
SQL> commit;
Commit complete.
Program 4
Aim:Queries using Group By, Order By, and Having Clauses
Table created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
6 rows selected.
Q1.1)Find the number of records in the table loan
COUNT(*)
----------
6
COUNT(*)
----------
3
COUNT(*)
----------
3
MIN(AMOUNT)
-----------
10000
MAX(AMOUNT)
-----------
90000
Q1.6)Find the sum of all emi’s
SUM(EMI)
----------
30600
AVG(EMI)
----------
5100
AVG(EMI) BRANCH
---------- ----------
2100 eluru
6100 guntur
5433.33333 vizag
AVG(EMI) BRANCH
---------- ----------
6100 guntur
5433.33333 vizag
Q1.11)Find the average of emi’s for all the branches whose name conatins the letter u
AVG(EMI) BRANCH
---------- ----------
2100 eluru
6100 guntur
MAX(ROWNUM)
-----------
6
Q1.16)Display all the rows except the last row from the table loan
SQL> commit;
Commit complete
SQL> exit;
Program 5
AIM: Queries on Controlling Data: Commit, Rollback, and Save point
Q1) Execute save point,rollback for insertion operation
Savepoint created.
Rollback complete
Savepoint created.
1 row deleted.
Rollback complete.
1 row updated.
Rollback complete.
Savepoint created.
SQL> commit;
Commit complete.
SQL> commit;
Commit complete.
SQL> exit;
Program 6
AIM: Queries for Creating, Dropping, and Altering Tables, Views, and Constraints
Table created.
Q3) Create table employee_1 without allowing null values to ename and salary not exceeding 100000.
Table created.
Q4) Create table employee_2 with unique constraint on eid and default value as 199 for age of an
employee.
Table created.
Table created.
Q6) Create table course with cid as primary key and check constraint on dept name.
Q7.a) Select different constraint names and constraint types in the table student.
CONSTRAINT_NAME C
------------------------------ -
SYS_C006238 P
b)Select different constraint names and constraint types in the table enroll.
CONSTRAINT_NAME C
------------------------------ -
SYS_C006241 R
c) Select different constraint names and constraint types in the table course.
SQL> select constraint_name,constraint_type
2 from user_constraints
3 where table_name like 'COURSE';
CONSTRAINT_NAME C
------------------------------ -
SYS_C006239 C
SYS_C006240 P
Q8) create table std_dup_1 with the following constraints and names:
sid as primary key, sname as unique, age not greater than 150
Table created.
CONSTRAINT_NAME C
------------------------------ -
CHK C
PKY P
UNI U
Q9) create table enroll with foreign key as sid refers to sid in student table.
1 row created.
1 row created.
SQL> /
Enter value for id: 33
Enter value for name: sumanth
Enter value for age: 27
old 1: insert into student values(&id,'&name',&age)
new 1: insert into student values(33,'sumanth',27)
1 row created.
SQL> select * from student;
SID SNAME AGE
---------- ---------- ----------
22 sudhakar 32
11 praneeth 28
33 sumanth 27
Q11) Create table std_dup_with_rec from existing table student with records also.
Table created.
SNAME SID
---------- ----------
sudhakar 22
praneeth 11
sumanth 33
Q12) Create table std_dup_no_rec from existing student table without records
Table created.
no rows selected
Table altered.
SQL> desc sailors;
Name Null? Type
----------------------------------------- -------- --------------
SID NOT NULL NUMBER(38)
SNAME VARCHAR2(20)
AGE NUMBER(3)
Q15) Add new columns height as number,weight as real to existing table sailors
SQL> alter table sailors add (height number(3),weight real);
Table altered.
Q16) Modify the data type of the sid attribute in the sailors table.
SQL> alter table sailors modify sid number(3);
Table altered.
SQL> desc sailors;
Name Null? Type
----------------------------------------- -------- -------------
SID NOT NULL NUMBER(3)
SNAME VARCHAR2(20)
AGE NUMBER(3)
HEIGHT NUMBER(3)
WEIGHT FLOAT(63)
Q17) Modify the data types of name and weight in sailors table.
Table altered.
Table altered.
SQL> desc sailors;
Name Null? Type
----------------------------------------- -------- --------------
SID NOT NULL NUMBER(3)
SNAME NOT NULL VARCHAR2(20)
AGE NUMBER(3)
HEIGHT NUMBER(3)
WEIGHT NUMBER(5,2)
Table altered.
Table created.
Table altered.
Table altered.
Q23) Add unique key constraint on bname in boats table
Table altered.
Q24) Add a check constraint on color which accepts either red, green or blue color in boats table.
Table altered.
CONSTRAINT_NAME C
------------------------------ -
PKY P
UNI U
CHK C
Q26) Drop a constraint whose name is chk from the table boats.
Table altered.
CONSTRAINT_NAME C
------------------------------ -
PKY P
UNI U
Table created.
Q28) Add foreign key constraints on sid,bin in reserves referencing tables sailors and boats.
Table altered.
CONSTRAINT_NAME C
------------------------------ -
FKY R
FKY2 R
Table renamed.
Table dropped.
SQL> /
Enter value for id: 103
Enter value for name: ranger
Enter value for color: blue
old 1: insert into boats values (&id,'&name','&color')
new 1: insert into boats values (103,'ranger','blue')
1 row created.
Q33) Remove all the rows in the table boats (by using ‘truncate’).
Table truncated.
no rows selected
SQL> commit;
Table created.
1 row created.
SQL> /
Enter value for id: 66
Enter value for name: praneeth
Enter value for sal: 26005.25
Enter value for age: 28
old 1: insert into employee values(&id,'&name',&sal,&age)
new 1: insert into employee values(66,'praneeth',26005.25,28)
1 row created.
View created.
1 row created.
ENAME AGE
--------------- ----------
sudhakar 32
praneeth 28
suresh 28
1 row updated.
1 row deleted.
ENAME AGE
--------------- ----------
sudha 32
suresh 28
1 row created.
1 row updated.
1 row deleted.
View created.
Table renamed.
View dropped.
SQL> commit;
Commit complete
SQL> exit;
Program 7
SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based on a related column between them.
(INNER) JOIN: Returns records that have matching values in both tables
LEFT (OUTER) JOIN: Return all records from the left table, and the matched records from the right
table
RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records from the
left table
FULL (OUTER) JOIN: Return all records when there is a match in either left or right table
In this example, we have a table called customers with the following data:
Inner Join:
Nested query
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.
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 BETWEEN operator cannot be used with a subquery. However, the BETWEEN operator can be
used within the subquery
Table created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
Table created.
1 row created.
SQL> insert into boats (bid, bname, color)
2 values (104, 'Marine', 'red');
1 row created.
Q5) Create table reserves(sid,bid,day) where sid,bid,day as primary key and sid,did as foreign key
referencing the tables sailors and boats respectively.
Table created.
1 row created.
1 row created.
1 row created.
1 row created.
SQL> insert into reserves (sid, bid, day)
2 values (31, 104, '11/dec/98');
1 row created.
SQL> insert into reserves (sid, bid, day)
2 values (64, 101, '9/may/98');
1 row created.
SNAME BID
--------------- ----------
Dustin 101
Dustin 102
Dustin 103
Dustin 104
Lubber 102
Lubber 103
Lubber 104
Horatio 101
Horatio 102
Horatio 103
10 rows selected.
Q8) Find the sailors name who have reserved boat number 103.
SQL> select [Link],[Link] from sailors a, reserves b where [Link]=[Link] and [Link]=103;
SNAME BID
--------------- ----------
Dustin 103
Lubber 103
Horatio 103
Q9) Find the sailors name who have reserved boat ‘Marine’.
SQL> select [Link],[Link] from sailors a, reserves b,boats c where [Link]=[Link] and [Link]=[Link] and
[Link]='Marine';
SNAME BID
--------------- ----------
Dustin 104
Lubber 104
Q10) Find the sailors who have reserved red color boat.
SQL> select [Link], [Link], [Link] from sailors a, reserves b,boats c where [Link]=[Link] and [Link]=[Link]
and [Link]='red'
SNAME RATING BNAME
--------------- ---------- ----------
Dustin 7 Interlake
Dustin 7 Marine
Lubber 8 Interlake
Lubber 8 Marine
Horatio 7 Interlake
Q12) Find the sailors who have reserved atleast one boat using nested query.
SQL> select * from sailors where sid in (select sid from reserves);
SQL> select * from sailors where sid not in (select sid from reserves);
6 rows selected.
Q15) Find the sailors whose who have reserved boat number 103 using nested query.
Q16) Find the sailors who have not reserved red color boat.
7 rows selected.
Q17) Find the sailor names who reserved boat number 103
SNAME
---------------
Dustin
Lubber
Horatio
Q18) Find the sailor names who do not reserved boat number 103
SQL> select [Link] from sailors a where not exists
2 (select * from reserves b where [Link]=103 and [Link]=[Link]);
SNAME
---------------
Brutus
Andy
Rusty
Horatio
Zorba
Art
Bob
7 rows selected.
Q19) select sailors details whose age greater any one of the sailors whose name starts with “pra”
SQL> select * from sailors where age>any(select age from sailors where sname like 'pra%');
SQL> commit;
Commit complete.
SQL> exit;
PL/SQL PROGRAMS
Description:
To develop the PL/SQL program we include the following tools which we prescribe are block structure,
execution statements.
PL/SQL-PROGRAMMING LANGUAGE
FEATURES:
It is a procedure language.
It is developed by oracle company.
Used only with oracle.
It process only row at time where non-procedural language process a set of rows at time.
BLOCK STRUCTURE:
>declare
<variable declaration>;
Begin
<executable statements>;
Exception;
<executable statements>;
End;
EXECUTABLE STATEMENTS:
1. DML allowed.
2. TCL allowed.
3. DDL and DCL are not allowed.
4. select<column list>into<variable list> from<table name> where<condition>;
5. –single line comment;
/*Multi
Line
Comment*/
6. dbms_output.put_line(‘message’||variable);
Used to print variables and messages.
DBMS_OUTPUT->It is a package.
7. set serveroutput on
(used to activities [Link].)
:=it for external value
Into----used with select command.
Sal number(7,2);
Note:- select statements must return one and only one row.
SNO SNAME M1 M2 M3
09JM1A0501 DIVYA 85 90 78
09JM1A0502 HARSHITA 86 94 74
09JM1A0503 RUKMINI 92 89 75
09JM1A0501 jm A
09JM1A0502 jm A
09JM1A0503 mf B
09JM1A0504 sd B
09JM1A0505 se C
09JM1A0506 ab D
SQL> declare
5 percent number(6,2);
6 BEGIN
8 percent:=(ma1+ma2+ma3)/300*100;
9 if percent>65 then
11 else
12 dbms_output.put_line('normal student');
13 end if;
14 EXCEPTION
15 whenno_data_found then
17 end;
18 /
SQL> begin
4 commit;
6 rollback;
7 savepoint s1;
9 rollback to s1;
10 end;
11 /
SNO SNAME M1 M2 M3
09JM1A0501 DIVYA 85 90 78
09JM1A0502 HARSHITA 86 94 74
09JM1A0503 RUKMINI 92 89 75
09JM1A0504 MANJU 35 60 75
09JM1A0505 VENI 66 76 86
6.A) DEVELOP A PL/SQL PROGRAM THAT INCLUDES THE FEATURES NESTED IF FUNCTION?
SQL>set serveroutput on
SQL> declare
2 a number (5);
3 begin
5 if a>2500 then
6 dbms_output.put_line('high_sal'||a);
8 dbms_output.put_line('normal_sal'||a);
9 else
10 dbms_output.put_line('low level'||a);
11 end if;
12 end;
13 /
low level800
SQL> declare
2 a number(5);
3 begin
6 dbms_output.put_Line('High-sal'||a);
7 when(a>1500)and(a<2500)then
8 dbms_output.put_Line('Normal-sal'||a);
9 else
10 dbms_output.put_Line('low-sal'||a);
11 end case;
12 end;
13 /
High-sal5000
SQL> declare
2 a number(2);
3 BEGIN
4 a:=1;
5 while(a<=10)
6 loop
7 dbms_output.put_line(a);
8 a:=a+1;
9 end loop;
10 end;
11 /
7
8
10
SQL> declare
2 a number(2);
3 BEGIN
4 for a in 1..10
5 loop
6 dbms_output.put_line(a);
7 end loop;
8 end;
9 /
10
SQL> declare
2 a number(5);
3 begin
5 if a>2500 then
6 dbms_output.put_line('High-sal'||a);
7 else
8 dbms_output.put_line('low-sal'||a);
9 end if;
10 exception
11 whenno_data_found then
14 /
High-sal3000
2 begin
3 b:=a*0.10;
4 end;
5 /
Procedure created.
SQL> declare
2 [Link]%type;
3 bonus number(6);
4 begin
6 p1(salary,bonus);
7 dbms_output.put_line('bonus is'||bonus);
8 end;
9 /
2 product number;
3 i number default 1;
4 begin
5 product:=1;
6 whilei<=a
7 loop
8 product:=product*i;
9 i:=i+1;
10 end loop;
11 return product;
12 end;
13 /
Function created.
SQL> declare
2 no number default 1;
3 res number;
4 begin
5 no:=&no;
6 res:=fact(no);
8 end;
9 /
old 5: no:=&no;
new 5: no:=6;
10) DEVELOP A PL/SQL PROGRAM USING CREATION OF PACKAGE BODIES, PRIVATE OBJECTS,
PACKAGE VARIABLES AND CURSOR CALLING STORE A PACKAGE?
2 proceduresum_sal;
3 procedureavg_sal;
4 end mypack1;
5 /
Package created.
2 procedure sum_sal is
3 salaries number;
5 BEGIN
6 open a;
9 endsum_sal;
10 procedureavg_sal is
11 avg_sal number;
13 BEGIN
14 open b;
16 dbms_output.put_line('avg of salaries'||avg_sal);
17 end avg_sal;
18 end mypack1;
19 /
SQL> declare
2 begin
3 [Link];
4 [Link];
5 end;
6 /
SQL> declare
2 cursor details is
4 BEGIN
5 for m2 in details
6 loop
8 end loop;
9 end;
10 /
SNO SNAME M1 M2 M3
09JM1A0501 DIVYA 93 90 78
09JM1A0502 HARSHITA 94 94 74
09JM1A0504 MANJU 43 60 75
09JM1A0505 VENI 74 76 86
12.A) DEVELOP A PROGRAM USING AFTER TRIGGER WITH STATEMENT TRIGGER IN PL/SQL BLOCK?
2 BEGIN
3 delete marks1;
5 end;
6 /
Trigger created.
1 row created.
SNO M1 M2 M3
09JM1A0501 85 90 78
09JM1A0502 86 94 74
09JM1A0503 92 89 75
09JM1A0504 35 60 75
09JM1A0505 66 76 86
A 35 45 65
6 rows selected.
12.B) DEVELOP A PROGRAM USING BEFORE AND AFTER TRIGGERS NOW AND COLUMN STATEMENTS
AND INSTEAD OF TRIGGERS?
SQL> create or replace trigger enroll3 before insert or update on enroll3 for each row
2 declare
3 total number;
4 name varchar(10);
5 BEGIN
7 if total>=3 then
10 end if;
11 EXCEPTION
12 whenno_data_found then
14 end;
15 /
Trigger created.
1 row created.
Aim: Write a PL/SQL Code Bind and Substitution Variables. Printing in PL/SQL
Bind Variable:
SQL> Exec:v_bind1:='rani';
V_BIND1
--------------------------------
Rani
SQL> ed bindd
BEGIN
:v_bind1 := 'Ramu';
DBMS_OUTPUT.PUT_LINE(:v_bind1);
END;
OutPut 1:
SQL> set serveroutput on;
SQL> @ bindd
Ramu
Output2:
SQL> set serveroutput off;
SQL> @ bindd
V_BIND1
--------------------------------
Ramu
Substitution Variable
DECLARE
name varchar2(10):='&name';
age number:=&age;
begin
dbms_output.put_line('name is '||name);
dbms_output.put_line('age is '||age);
end;
name is rani
age is 25
SQL> /
name is rani
age is 28
Program 10
AIM: Write a PL/SQL block using SQL and Control Structures in PL/SQL
The NULLIF function compares two expressions. If they are equal, the function returns NULL;
otherwise, it returns the value of the first expression.
BEGIN
END;
THE COALESCE FUNCTION
The COALESCE function compares each expression to NULL from the list of expressions and
returns the value of the first non-null expression.
[Link]
declare
fname varchar2(10);
lname varchar2(10);
ch number;
res varchar2(10);
res1 varchar2(10);
begin
fname:='&fname';
lname:='&lname';
ch:=&ch;
case ch
when 1 then
res:=nullif(fname,lname);
dbms_output.put_line('res is:'||res);
dbms_output.put_line('lname is null');
elsif res=lname and fname is null then
dbms_output.put_line('fname is null');
else
end if;
when 2 then
res:=COALESCE(fname,lname);
res1:=coalesce(lname,fname);
dbms_output.put_line('res is:'||res);
if res=lname then
dbms_output.put_line('Fname is null');
dbms_output.put_line('Lname is null');
else
end if;
else
end case;
end;
Output:
SQL> @ 6
new 8: fname:='chp';
old 9: lname:='&lname';
new 9: lname:='abc';
res is:chp
SQL> @ 6
old 8: fname:='&fname';
new 8: fname:='abc';
old 9: lname:='&lname';
new 9: lname:='chp';
res is:abc
Syntax
WHILE condition LOOP
sequence_of_statements
END LOOP;
Example
DECLARE
a number(2) := 10;
BEGIN
a := a + 1;
END LOOP;
END;
When the above code is executed at the SQL prompt, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
A FOR LOOP is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
Syntax
sequence_of_statements;
END LOOP;
The initial step is executed first, and only once. This step allows you to declare and initialize any loop
control variables.
Next, the condition, i.e., initial_value .. final_value is evaluated. If it is TRUE, the body of the loop is
executed. If it is FALSE, the body of the loop does not execute and the flow of control jumps to the next
statement just after the for loop.
After the body of the for loop executes, the value of the counter variable is increased or decreased.
The condition is now evaluated again. If it is TRUE, the loop executes and the process repeats itself (body
of loop, then increment step, and then again condition). After the condition becomes FALSE, the FOR-
LOOP terminates.
The initial_value and final_value of the loop variable or counter can be literals, variables, or expressions
but must evaluate to numbers. Otherwise, PL/SQL raises the predefined exception VALUE_ERROR.
The initial_value need not be 1; however, the loop counter increment (or decrement) must be 1.
PL/SQL allows the determination of the loop range dynamically at run time.
Example
DECLARE
a number(2);
BEGIN
FOR a in 10 .. 20 LOOP
END LOOP;
END;
When the above code is executed at the SQL prompt, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
value of a: 20
By default, iteration proceeds from the initial value to the final value, generally upward from the lower
bound to the higher bound. You can reverse this order by using the REVERSE keyword. In such case,
iteration proceeds the other way. After each iteration, the loop counter is decremented.
However, you must write the range bounds in ascending (not descending) order. The following program
illustrates this −
DECLARE
a number(2) ;
BEGIN
END LOOP;
END;
When the above code is executed at the SQL prompt, it produces the following result −
value of a: 20
value of a: 19
value of a: 18
value of a: 17
value of a: 16
value of a: 15
value of a: 14
value of a: 13
value of a: 12
value of a: 11
value of a: 10
Program 11
AIM: Write a PL/SQL Code using Cursors, Exceptions and Composite Data Types
Cursor
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.
CURSOR c_customers IS
SELECT id, name, address FROM customers;
OPEN c_customers;
CLOSE c_customers;
Example
DECLARE
c_id [Link]%type;
c_name [Link]%type;
c_addr [Link]%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE c_customers;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
1 Ramesh Ahmedabad
2 Khilan Delhi
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP
declare
cursor emp_cur is
for update;
cur_rec emp_cur%rowtype;
begin
end loop;
Open emp_cur;
End if;
LOOP
END LOOP;
Close emp_cur;
end;
Output:
SQL> @ cur;
age is chp
1 age is chp
SQL> ed zd_excep.sql;
declare
x number(5);
d number(5);
q number(5);
begin
x:=÷nt;
d:=&divisor;
if((d!=0)) then
q:=x/d;
dbms_output.put_line('the quotient is '|| q);
else
raise zero_divide;
end if;
exception
when zero_divide then dbms_output.put_line('division with 0 is not possible');
end;
/
SQL> @zd_excep.sql;
Enter value for divident: 22
old 6: x:=÷nt;
new 6: x:=22;
Enter value for divisor: 4
old 7: d:=&divisor;
new 7: d:=4;
the quotient is 6
SQL> @zd_excep.sql;
Enter value for divident: 77
old 6: x:=÷nt;
new 6: x:=77;
Enter value for divisor: 0
old 7: d:=&divisor;
new 7: d:=0;
division with 0 is not possible
Table created.
1 row created.
1 row created.
1 row created.
SQL> ed ndf_excep.sql;
declare
name [Link]%type;
id number(3);
begin
id:=&id;
select sname into name from student where sid=id;
if (name is not null) then
dbms_output.put_line('Student name is' ||name);
else
raise no_data_found;
end if;
exception
when no_data_found then dbms_output.put_line('no studnet with the roll number ' ||id);
end;
/
SQL> @ndf_excep.sql;
Enter value for id: 22
old 5: id:=&id;
new 5: id:=22;
Student name issudhakar
PL/SQL procedure successfully completed.
SQL> @ndf_excep.sql;
Enter value for id: 88
old 5: id:=&id;
new 5: id:=88;
no studnet with the roll number 88
SQL> ed snf_excep.sql;
declare
x number(3);
p real;
begin
x:=&one_or_two;
case x
when 1 then dbms_output.put_line('you are number one');
when 2 then dbms_output.put_line('you are second');
else raise case_not_found;
end case;
exception
when case_not_found then dbms_output.put_line('enter 1 or 2 only. try again');
end;
/
SQL> @snf_excep.sql;
Enter value for one_or_two: 1
old 5: x:=&one_or_two;
new 5: x:=1;
you are number one
SQL> @snf_excep.sql;
Enter value for one_or_two: 2
old 5: x:=&one_or_two;
new 5: x:=2;
you are second
SQL> @snf_excep.sql;
Enter value for one_or_two: 22
old 5: x:=&one_or_two;
new 5: x:=22;
enter 1 or 2 only. try again
SQL> ed ud_excep.sql;
declare
name [Link]%type;
sage [Link]%type;
my_excep exception;
id number(3);
begin
id:=&sid;
select sname into name from student where sid=id;
if(name='chp') then
select age into sage from student where sid=id;
dbms_output.put_line('student age is' || age);
else
raise my_excep;
end if;
exception
when my_excep then dbms_output.put_line('the id you entered is not correct ');
when no_data_found then dbms_output.put_line('the id is not table');
end;
/
SQL> @ud_excep.sql;
Enter value for sudhakar_id: 22
old 7: id:=&sudhakar_id;
new 7: id:=22;
sudhakar age is32
SQL> @ud_excep.sql;
Enter value for sudhakar_id: 77
old 7: id:=&sudhakar_id;
new 7: id:=77;
the id you entered is not sudhakar id
SQL> @ud_excep.sql;
Enter value for sudhakar_id: 66
old 7: id:=&sudhakar_id;
new 7: id:=66;
the id is not table
SQL> commit;
declare
i number(5);
n number(2);
s number(3);
a number(5);
begin
n:=&n;
s:=0;
output:
SQL> @ sun
Enter value for n: 3
old 7: n:=&n;
new 7: n:=3;
Enter value for a: 2
old 11: a:=&a;
new 11: a:=2;
sum is6
Program 12
Aim: Write a PL/SQL Code using Procedures, Functions, and Packages FORMS
i integer;
begin
f:=1;
for i in 1 .. n
loop
f:=f*i;
end loop;
end;
SQL> @proced;
Procedure created.
SQL> ed calprog;
declare
x number(10);
f number(10);
begin
x:=&x;
if(x>0) then
factorial(x,f);
elsif(x=0) then
else
end if;
end;
/
SQL> @calprog;
Enter value for x: 5
old 5: x:=&x;
new 5: x:=5;
the factorial of 5 is 120
SQL> @calprog;
Enter value for x: 0
old 5: x:=&x;
new 5: x:=0;
the factorial of 0 is 1
FUNCTION
Table created.
SQL> insert into student values(11,'sudhakar',35);
1 row created.
1 row created.
1 row created.
1 row created.
SQL>edfunc;
name varchar2(15);
begin
return name;
exception
whenno_data_found then
end;
/
SQL> @func;
Function created.
SQL>edfuncal;
declare
id number(5);
name varchar2(15);
begin
id:=&student_id;
name:=stdname(id);
if (name!='-1') then
end if;
end;
SQL> @funcal;
Enter value for student_id: 11
old 5: id:=&student_id;
new 5: id:=11;
the student name with id 11 is sudhakar
SQL> @funcal;
Enter value for student_id: 44
old 5: id:=&student_id;
new 5: id:=44;
no student found with id 44
PACKAGE
SQL> set serveroutput on;
SQL>edpackdec;
create or replace package maths as
endmaths;
/
SQL> @packdec;
Package created.
SQL>edpackdef;
create or replace package body maths as
y number;
begin
y:=n*n;
dbms_output.put_line(chr(10));
end square;
begin
y:=n*n*n;
return y;
end cub;
endmaths;
/
SQL> @packdef;
SQL>edpackcal;
declare
n number;
y number;
begin
n:=&n;
[Link](n);
y:=[Link](n);
end;
SQL> @packcal;
Enter value for n: 5
old 5: n:=&n;
new 5: n:=5;
The square of 5is 25
SQL> commit;
Commit complete.
SQL> exit;