0% found this document useful (0 votes)
58 views

Dbmslabmanual

The document describes the list of experiments for a Database Management System lab. It includes experiments on SQL queries involving functions, operators, retrieving and modifying data, and controlling transactions. It also includes experiments writing PL/SQL code using variables, control structures, cursors, exceptions, procedures, functions and packages. The final experiments involve database connectivity and creating forms for information systems.

Uploaded by

Charitha Iddum
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views

Dbmslabmanual

The document describes the list of experiments for a Database Management System lab. It includes experiments on SQL queries involving functions, operators, retrieving and modifying data, and controlling transactions. It also includes experiments writing PL/SQL code using variables, control structures, cursors, exceptions, procedures, functions and packages. The final experiments involve database connectivity and creating forms for information systems.

Uploaded by

Charitha Iddum
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 81

DATA BASE MANAGEMENT SYSTEM LAB

List of Experiments:
SQL
1. Queries to facilitate acquaintance of Built-In Functions, String Functions, Numeric
Functions, Date Functions and Conversion Functions.
2. Queries using operators in SQL
3. Queries to Retrieve and Change Data: Select, Insert, Delete, and Update
4. Queries using Group By, Order By, and Having Clauses
5. Queries on Controlling Data: Commit, Rollback, and Save point
6. Queries to Build Report in SQL *PLUS
7. Queries for Creating, Dropping, and Altering Tables, Views, and Constraints
8. Queries on Joins and Correlated Sub-Queries
9. Queries on Working with Index, Sequence, Synonym, Controlling Access, and
Locking Rows for Update, Creating Password and Security features
PL/SQL
10. Write a PL/SQL Code using Basic Variable, Anchored Declarations, and Usage of
Assignment Operation
11. Write a PL/SQL Code Bind and Substitution Variables. Printing in PL/SQL
12. Write a PL/SQL block using SQL and Control Structures in PL/SQL
13. Write a PL/SQL Code using Cursors, Exceptions and Composite Data Types
14. Write a PL/SQL Code using Procedures, Functions, and Packages
15. Write a PL/SQL Code Creation of forms for any Information System such as Student
Information System, Employee Information System etc.
16. Demonstration of database connectivity

Department of Computer Science & Engineering 1


DATA BASE MANAGEMENT SYSTEM LAB

USHA RAMA COLLEGE


OF
ENGINEERING & TECHNOLOGY

ORACLE

Oracle Was first developed by Relational Software in the year 1979 later came to be known as oracle
Corporation. This company produces the most widely used , server based , multi user RDBMS named
Oracle

SQL

• This is a language that provides an interface to relational database systems.


• The language developed by IBM to manipulate the data stored within Codds model was
originally called as Structured English query language (SEQUEL) later called as SQL
• SQL encompasses DDL(Data Definition Language) ,DML(Data Manipulation Language) ,
TCL(Transaction Control Language) and DCL(Data Control Language).

DDL

• This part of SQL is a syntax for database tables to be created or deleted. We can also define
indexes, specify links between tables, and impose constraints between database tables
• The important DDL statements are
– CREATE Table
– ALTER Table
– DROP Table
– TRUNCATE Table
– RENAME Table

DML

• This part of SQL is a syntax for executing queries. But the SQL language also include a syntax
to update, insert and delete records.
• The important DML Statements are
– SELECT – Extracts data from a database table
– UPDATE – Updates data in a database table
– DELETE – Deletes data from a database table
– INSERT INTO – Inserts new data into a database Table.

Department of Computer Science & Engineering 2


DATA BASE MANAGEMENT SYSTEM LAB

TCL

• This part of SQL is a syntax for control the transactions on a database .


• The important TCL statements are
– COMMIT – Save the changes permanent
– ROLLBACK – Undo the changes on data base
– SAVEPOINT – Save the changes upto this point of time.

DCL
• This part SQL is a syntax to control the flow of data among different users of the database
• The important DCL statements are
– GRANT – Grants permissions to users
– REVOKE – Revokes permissions to users

Data Types
• CHAR(size)
– Used to store character strings. The size determines number of characters the cell can
hold. The max number is 255 Characters
• VARCHAR(size)/VARCHAR2(size)
– Stores Variable length aplhanumeric data.The max is 4000 characters
• DATE
– Used to represent date and time. The standard format is DD-Mon-YY as in 03-dec-08. If
we want to change date function use appropriate function. Valid date range is Jan 1,4712
B.C to December 31,4712 A.D.
• NUMBER(p,s)

– Used to store numbers. Number of virtually any magnitude can be stored up to 38 digits
of precission.
• LONG
– Used to store variable length character strings containing upto 2 GB
• RAW/ LONG RAW
– Used to store binary data such as digitized picture or images. Upto 2 GB.
• TIME STAMP
– Used to store year, month, day, hour, minutes and seconds
• ROWID
– Fixed length binary data. Every record in the data base has unique Physical Address. The
format is BBBBBBB.RRRR.FFFFF where BBBBBBB is the block in database file,
RRRR is the row in the block and FFFFF is the database file
• BFILE
– File locator that points to a read-only binary object outside the database. Up to 4 GB.
• BLOB
– Locator for Large Binary objects within the database. Up to 4GB
• CLOB
– Locator for Large Character objects within the database. Up to 4 GB

Queries to facilitate acquaintance of String Functions, Numeric Functions, Date

Department of Computer Science & Engineering 3


DATA BASE MANAGEMENT SYSTEM LAB

Functions and Conversion Functions.

String Functions:
lower():-
Return the argument in lowercase.
Syntax:-
LOWER(string);

SQL> select lower ('SWARNANDHRA') from dual;

LOWER('SWARNANDHRA')
---------------------------------
swarnandhra

upper():-
Return the argument in uppercase.
Syntax:-
UPPER(string);

SQL> select upper('swarnandhra') from dual;

UPPER('SWARNANDHRA')
---------------------------------
SWARNANDHRA

length():-
Return the length of given string.
Syntax:-
LENGTH(String);

SQL> select length('Swarnandhra Institute') from dual;

LENGTH('SWARNANDHRAINSTITUTE')
------------------------------
21

initcap():-
Returns char with first letter of each word in uppercase.
Syntax:-
INITCAP(String);

SQL> select initcap('swarnandhra institute of engineering and technology') from dual;

INITCAP('SWARNANDHRAINSTITUTEOFENGINEERINGANDTECHNOLOGY')
--------------------------------------------------------------------------------
Swarnandhra Institute Of Engineering And Technology

substr():-

Department of Computer Science & Engineering 4


DATA BASE MANAGEMENT SYSTEM LAB

Return the substring as specified.


Syntax:-
SUBSTR(string,position,length);

SQL> select substr('swarnandhra',6,6) from dual;

SUBSTR('SWARNANDHRA')
------------------
andhra

instr():-
Return the index of the first occurrence of substring.
Syntax:-
INSTR(string,substring);

SQL> select instr('site','i') from dual;

INSTR('SITE','I')
-----------------
2
SQL> select instr('swarnandhra','n',1,2) from dual;

INSTR('SWARNANDHRA','N',1,2)
----------------------------
7

trim():-
Remove leading and trailing spaces.
Syntax:-
TRIM(string);

SQL> select trim(' swarnandhra ') from dual;

TRIM('SWARNANDHRA')
---------------------------------
swarnandhra

SQL> select trim(leading '*' from '***swarnandhra institute***') from dual;

TRIM(LEADING'*'FROM'***SWARNANDHRAINSTITUTE***')
------------------------------------------------------------------------
swarnandhra institute***

SQL> select trim(both '*' from '***swarnandhra institute***') from dual;

TRIM(BOTH'*'FROM'***SWARNANDHRAINSTITUTE***')
---------------------------------------------------------------
swarnandhra institute

ltrim():-

Department of Computer Science & Engineering 5


DATA BASE MANAGEMENT SYSTEM LAB

Remove leading spaces.


Syntax:-
LTRIM(string,remstring);

SQL> select ltrim('swarnandhra','s') from dual;

LTRIM('SWARNANDHRA','S')
------------------------------
warnandhra

SQL> select ltrim('swarnandhra','swar') from dual;

LTRIM('SWARNANDHRA','SWARN')
---------------------
andhra

rtrim():-
Remove trailing spaces.
Syntax:-
RTRIM(string,remstring);

SQL> select rtrim('swarnandhra','a') from dual;

RTRIM('SWARNANDHRA','A')
------------------------------
swarnandhr

SQL> select rtrim('swarnandhara','ra') from dual;

RTRIM('SWARNANDHARA','RA')
---------------------------
swarnandh

lpad():-
Return the string argument, left-padded with the specified string .
Syntax:-
LPAD(string,length,padstring);

SQL> select lpad('Siet',10,'*') from dual;

LPAD('SIET',10,'*')
------------------------------
******Siet

SQL> select lpad('Siet',10) from dual;

LPAD('SIET',10)
------------------------------
Siet
rpad():-

Department of Computer Science & Engineering 6


DATA BASE MANAGEMENT SYSTEM LAB

Append string the specified number of times.


Syntax:-
RPAD(string,length,padstring);

SQL> select rpad('Siet',10,'*') from dual;

RPAD('SIET',10,'*')
------------------------------
Siet******

SQL> select rpad('Siet',10,'Nsp') from dual;

RPAD('SIET',10,'NSP')
------------------------------
SietNspNsp

concat():-
Returns string1 concatenated with string2.
Syntax:-
CONCAT(string1,......stringn);

SQL> select concat('Swarnandhra','Institute') from dual;

CONCAT('SWARNANDHRA','INSTITUTE')
------------------------------------------------------------
SwarnandhraInstitute

Numeric functions:-

Department of Computer Science & Engineering 7


DATA BASE MANAGEMENT SYSTEM LAB

abs():-
Returns the absolute value of a number.
Syntax:-
ABS(value);

SQL> select abs(-25) "Absolute Value" from dual;

Absolute Value
--------------
25

SQL> select abs(-21) from dual;

ABS(-21)
----------
21

power():-
Power(m,n) function returns m raised to n.
Syntax:-
power(m,n);

SQL> select power(5,3) "5 power 3" from dual;

5 power 3
----------
125
SQL> select power(2,3) from dual;

POWER(2,3)
----------
8

sqrt():-
Returns the square root of a number.
Syntax:-
SQRT(value);

SQL> select sqrt(49) from dual;

SQRT(49)
----------
7

mod():-

Department of Computer Science & Engineering 8


DATA BASE MANAGEMENT SYSTEM LAB

It is the mathematical expression m MOD n.m MOD n returns remainder of m


divided by n.
Syntax:-
MOD(m,n);

SQL> select mod(32,3) from dual;

MOD(32,3)
----------
2

round():-
Round function for number rounded to specified integer to the right of the decimal
point.
Syntax:-
ROUND(value);

SQL> select round(23.29,1) from dual;

ROUND(23.29,1)
--------------
23.3

SQL> select round(23.29,2) from dual;

ROUND(23.29,2)
--------------
23.29

trunc():-
Returns n truncated to m decimal places.m can be omitted, to 0 places. m can be -
ve, to truncate(make zero) m digits left of the decimal point.
Syntax:-
TRUNC(n,m) ;

SQL> select trunc(125.815,1) from dual;

TRUNC(125.815,1)
----------------
125.8

SQL> select trunc(125.815,2) from dual;

TRUNC(125.815,2)
----------------
125.81

floor():-
Floor function returns previous whole number.

Department of Computer Science & Engineering 9


DATA BASE MANAGEMENT SYSTEM LAB

Syntax:-
FLOOR(value);

SQL> select floor(18.6) from dual;

FLOOR(18.6)
-----------
18

SQL> select floor(32.12) from dual;

FLOOR(32.12)
------------
32

ceil():-
Ceil function returns next whole number.
Syntax:-
CEIL(value);

SQL> select ceil(25.81) from dual;

CEIL(25.81)
-----------
26

SQL> select ceil(13.15) from dual;

CEIL(13.15)
-----------
14

exp():-
It Returns e raised to the nth power.
Syntax:-
EXP(n);

SQL> select exp(10) from dual;

EXP(10)
----------
22026.4658

greatest():-
Returns the largest of multiple values.

Department of Computer Science & Engineering 10


DATA BASE MANAGEMENT SYSTEM LAB

Syntax:-
GREATEST(VALUE1,.......VALUEN);

SQL> select greatest(23,67,45) from dual;

GREATEST(23,67,45)
------------------
67

SQL> select greatest('23','67','45') from dual;

GREATE
------
67

least():-
Returns the smallest of multiple values.
Syntax:-
LEAST(value1,......valuen);

SQL> select least(4,5,17) from dual;

LEAST(4,5,17)
-------------
4

SQL> select least ('4','5','17') from dual;

LEAST('4','5','17')
------
17

Date Functions():-

Department of Computer Science & Engineering 11


DATA BASE MANAGEMENT SYSTEM LAB

sysdate():-
It Returns the current date and time.
Syntax:-
sysdate();

SQL> select sysdate from dual;

SYSDATE
------------------
29-JUL-18

last_day():-
Return the last day of the month for the argument .
SQL> select last_day('21-Jun-18') from dual;

LAST_DAY('21-JUN-1
------------------
30-JUN-18

next_day():-
The Oracle NEXT_DAY() function returns the date of the first weekday specified
by day name that is later than a date.
Syntax:-
NEXT_DAY(date,weekday);

SQL> select next_day('25-Aug-18','Saturday') from dual;

NEXT_DAY('25-AUG-18','SATURDAY')
------------------
01-SEP-18

add_months():-
ADD_MONTHS() function returns a date with a given number of months added
(date plus integer months). A month is defined by the session parameter
NLS_CALENDAR.
Syntax:-
ADD_MONTHS(date, integer);

SQL> select add_months('12-Jun-18',3) from dual;

ADD_MONTHS('12-JUN-18',3)
------------------
12-SEP-18

months_between():-
The MONTHS_BETWEEN() function is used to get the number of months
between dates (date1, date2).

Department of Computer Science & Engineering 12


DATA BASE MANAGEMENT SYSTEM LAB

Syntax:-
MONTHS_BETWEEN(date1, date2);

SQL> select months_between('25-Jul-18','25-Apr-18') from dual;

MONTHS_BETWEEN('25-JUL-18','25-APR-18')
---------------------------------------
3
round():-
The ROUND() function is used to get the date rounded to the unit specified by the
format model. It operates according to the rules of the Gregorian calendar.
Syntax:-
ROUND(date , fmt )

SQL> select round(to_date('24-Jul-18'),'year')from dual;

ROUND(TO_DATE('24-JUL-18'),'YEAR)
------------------
01-JAN-19

SQL> select round(to_date('12-Mar-18'),'year') from dual;

ROUND(TO_DATE('12-MAR-18'),'YEAR)
------------------
01-JAN-18
SQL> select round(to_date('21-Jul-18'),'Q') from dual;

ROUND(TO_DATE('21-JUL-18'),'Q')
------------------
01-JUL-18

SQL> select round(to_date('21-Aug-18'),'Q') from dual;

ROUND(TO_DATE('21-AUG-18'),'Q')
------------------
01-OCT-18

SQL> select round(to_date('21-JUL-18'),'month') from dual;

ROUND(TO_DATE('21-JUL-18'),'month')
------------------
01-AUG-18

SQL> select round(to_date('21-JUL-18'),'day') from dual;

ROUND(TO_DATE('21-JUL-18'),'DAY')
------------------
22-JUL-18

trunc():-
The TRUNC (date) function returns date with the time portion of the day truncated
to the unit specified by the format model fmt. The value returned is always of datatype

Department of Computer Science & Engineering 13


DATA BASE MANAGEMENT SYSTEM LAB

DATE,even if you specify a different datetime datatype for date.


Syntax:-
TRUNC ( date , format ]);

SQL> select trunc(to_date('24-Jul-18'),'year') from dual;

TRUNC(TO_DATE('24-JUL-18'),'YEAR')
------------------
01-JAN-18

SQL> select trunc(to_date('24-Jul-18'),'month') from dual;

TRUNC(TO_DATE('24-JUL-18'),'YEAR')
------------------
01-JUL-18

SQL> select trunc(to_date('24-Jul-18'),'Q') from dual;

TRUNC(TO_DATE('24-JUL-18'),'YEAR')
------------------
01-JUL-18

greatest():-
Return the greatest date in a list of expressions.
Syntax:-
SELECT GREATEST(to_date(date1),to_date(date2),..);

SQL> select greatest(to_date('01-Jan-18'),to_date('01-feb-18'),to_date('20-Apr-18')) from dual;


GREATEST(TO_DATE('01-JAN-18'),TO_DATE('01-FEB-18'),TO_DATE('20-APR-18'))
------------------
20-APR-18

least():-
Return the smallest value in a list of expressions.
Syntax:-
SELECT LEAST(to_date(date1),to_date(date2),...);

SQL> select least(to_date('01-Jan-18'),to_date('01-feb-18'),to_date('20-Apr-18')) from dual;

LEAST(TO_DATE('01--JAN-18'),TO_DATE('01-FEB-18'),TO_DATE('20-APR-18'))
------------------
01-JAN-18

Conversion Functions():-

Department of Computer Science & Engineering 14


DATA BASE MANAGEMENT SYSTEM LAB

to_date():-
The TO_DATE function is used to convert a TEXT representation of a date into an
Oracle DATETIME value.By default, strings following the formats of DD-MON-YYYY,
DD-MON-YY, DD-MONTH-YYYY, DD-MONTH-YY can automatically be converted
without the need for a date_format.
Syntax:-
to_date(string, date_format);

SQL> select to_date('2018/07/29','yyyy/mm/dd') from dual;

TO_DATE('2018/07/2','YYYYMMDD)
------------------
29-JUL-18
SQL> select to_date('072917','mmddyy') from dual;

TO_DATE('072917','MMDDYY')
------------------
29-JUL-17
SQL> select to_date('20180729','yyyymmdd') from dual;

TO_DATE('20180729','YYYYMMDD')
------------------
29-JUL-18

to_char():-
The Oracle/PLSQL TO_CHAR function converts a number or date to a string.
Syntax:-
TO_CHAR( value , format_mask);
date to string:-
SQL> select to_char(sysdate,'yyyy/mm/dd') from dual;

TO_CHAR(SYSDATE,'YYYY/MM/DD')
------------------------------
2018/08/29
SQL> select to_char(sysdate,'month dd,yyyy') from dual;

TO_CHAR(SYSDATE,'MONTHDD,YYYY')
---------------------------------------------------
august 29,2018
SQL> select to_char(sysdate,'monddth,yyyy') from dual;

TO_CHAR(SYSDATE,'MONDDTH,YYYY')
------------------------------------
aug29th,2018
SQL> select to_char(to_date('24-Jul-18'),'dd-mm-yy') from dual;

TO_CHAR(TO_DATE('24-JUL-18'),'DD-MM-YY')
------------------------
24-07-18
Number to string:-

Department of Computer Science & Engineering 15


DATA BASE MANAGEMENT SYSTEM LAB

SQL> select to_char(1000,'9999') from dual;

TO_CHAR(1000,'9999')
---------------
1000

SQL> select to_char(1000,'9,999') from dual;

TO_CHAR(1000,'9,999)
------------------
1,000

SQL> select to_char(1000,'$9,999') from dual;

TO_CHAR(1000,'$9,999')
---------------------
$1,000

to_number():-
The Oracle TO_NUMBER function converts a string to a number.
Syntax:-
TO_NUMBER( string1 , format_mask);

SQL> select to_number('1000') from dual;

TO_NUMBER('1000')
-----------------
1000

SQL> select 1000+to_number('1000') from dual;

1000+TO_NUMBER('1000')
----------------------
2000

Queries using operators in SQL:

Department of Computer Science & Engineering 16


DATA BASE MANAGEMENT SYSTEM LAB

SQL> select * from Student;

SNO NAME CD DBMS OS


---------- --------------------------------------------- ---------- ---------- ----------
501 Rama 58 60 78
502 Sita 69 40 61
503 Lakshmi 76 18 87
504 Sai 23 84 51
505 Kumar 89 45 72
506 Satya 76 34 81
507 John 34 78 65
508 Yamini 76 56 23
509 Sushma 62 65 81
510 Lalitha 64 51 23
511 Rama 34 92 65
512 Sita 44 82 20

like operator():-

The LIKE operator is used in a WHERE clause to search for a specified pattern in a
column.
There are two wildcards used in conjunction with the LIKE operator:
% The percent sign represents zero, one, or multiple characters.
_ The underscore represents a single character.

Syntax:-
SELECT column_name(s) FROM table_name WHERE column_name LIKE pattern;

Display the students whose name beginning with letter 'S'.

SQL> select Sno,Name from Student where Name like 'S%';

SNO NAME
---------- ---------------------------------------------
502 Sita
504 Sai
506 Satya
509 Sushma
512 Sita

5 rows selected.

Display the students whose name ending with letter 'a'.

SQL> SELECT Sno,Name from Student where Name like '%a';

Department of Computer Science & Engineering 17


DATA BASE MANAGEMENT SYSTEM LAB

SNO NAME
---------- ---------------------------------------------
501 Rama
502 Sita
506 Satya
509 Sushma
510 Lalitha
511 Rama
512 Sita

7 rows selected.

Display the students whose names begin with letter 'R' and 'S'.

SQL> select Sno,Name from Student where Name like 'R%' or Name like 'S%';

SNO NAME
---------- ---------------------------------------------
501 Rama
502 Sita
504 Sai
506 Satya
509 Sushma
511 Rama
512 Sita

7 rows selected.

Display the studets whose names have second character as 'a'.

SQL> select Sno,Name from Student where Name like '_a%';

SNO NAME
---------- ---------------------------------------------
501 Rama
503 Lakshmi
504 Sai
506 Satya
508 Yamini
510 Lalitha
511 Rama

7 rows selected.

Display the students whose names having only 4 characters.

SQL> select Sno,Name from Student where Name like '____';

Department of Computer Science & Engineering 18


DATA BASE MANAGEMENT SYSTEM LAB

SNO NAME
---------- ---------------------------------------------
501 Rama
502 Sita
507 John
511 Rama
512 Sita

5 rows selected.

In operator:-
The IN operator allows you to specify multiple values in a WHERE clause.
The IN operator is a shorthand for multiple OR conditions.
Syntax:-
1) SELECT column_name(s) FROM table_name WHERE column_name IN
(value1, value2, ...);
2)select column1,...columnn from table_name where column in (condition);

SQL> select Sno,Name,DBMS from Student where Sno in(503,506,509);

SNO NAME DBMS


---------- --------------------------------------------- ----------
503 Lakshmi 18
506 Satya 34
509 Sushma 65

SQL> select * from Student where Sno in(504,508,512);

SNO NAME CD DBMS OS


---------- --------------------------------------------- ---------- ---------- ----------
504 Sai 23 84 51
508 Yamini 76 56 23
512 Sita 44 82 20

SQL> select * from Student where Name in('Yamini','Sushma','Lalitha');

SNO NAME CD DBMS OS


---------- --------------------------------------------- ---------- ---------- ----------
508 Yamini 76 56 23
509 Sushma 62 65 81
510 Lalitha 64 51 23

not in operator:-
The NOT IN operator allows you to specify multiple values in a WHERE clause.
Syntax:-

Department of Computer Science & Engineering 19


DATA BASE MANAGEMENT SYSTEM LAB

SELECT column_name(s) FROM table_name WHERE column_name NOT IN


(value1, value2, ...);

SQL> select * from Student where Sno not in (502,504,506,508,510,512);

SNO NAME CD DBMS OS


---------- --------------------------------------------- ---------- ---------- ----------
501 Rama 58 60 78
503 Lakshmi 76 18 87
505 Kumar 89 45 72
507 John 34 78 65
509 Sushma 62 65 81
511 Rama 34 92 65

6 rows selected.

SQL> select * from Student where Name not in('Rama','Sita');

SNO NAME CD DBMS OS


---------- --------------------------------------------- ---------- ---------- ----------
503 Lakshmi 76 18 87
504 Sai 23 84 51
505 Kumar 89 45 72
506 Satya 76 34 81
507 John 34 78 65
508 Yamini 76 56 23
509 Sushma 62 65 81
510 Lalitha 64 51 23

8 rows selected.

Between operator:-
The BETWEEN operator selects values within a given range. The values can be
numbers, text, or dates.
The BETWEEN operator is inclusive: begin and end values are included.
Syntax:-
SELECT column_name(s) FROM table_name WHERE column_name BETWEEN
value1 AND value2;

SQL> select Sno,Name,DBMS from Student where DBMS between 70 and 90;

SNO NAME DBMS


---------- --------------------------------------------- ----------
504 Sai 84
507 John 78
512 Sita 82

SQL> select * from Student where DBMS between 70 and 90;

SNO NAME CD DBMS OS

Department of Computer Science & Engineering 20


DATA BASE MANAGEMENT SYSTEM LAB

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


504 Sai 23 84 51
507 John 34 78 65
512 Sita 44 82 20

not between operator:-


The NOT BETWEEN operator selects values which are not in the given range. The
values can be numbers, text, or dates.
Syntax:-
SELECT column_name(s) FROM table_name WHERE column_name NOT
BETWEEN value1 AND value2;

SQL> select Sno,Name,DBMS from Student where DBMS not between 70 and 90;

SNO NAME DBMS


---------- --------------------------------------------- ----------
501 Rama 60
502 Sita 40
503 Lakshmi 18
505 Kumar 45
506 Satya 34
508 Yamini 56
509 Sushma 65
510 Lalitha 51
511 Rama 92

9 rows selected.

SQL> select * from Student where DBMS not between 70 and 90;

SNO NAME CD DBMS OS


---------- --------------------------------------------- ---------- ---------- ----------
501 Rama 58 60 78
502 Sita 69 40 61
503 Lakshmi 76 18 87
505 Kumar 89 45 72
506 Satya 76 34 81
508 Yamini 76 56 23
509 Sushma 62 65 81
510 Lalitha 64 51 23
511 Rama 34 92 65

9 rows selected.

Queries to Retrieve and Change Data: Select, Insert, Delete, and Update:

create command:-

Department of Computer Science & Engineering 21


DATA BASE MANAGEMENT SYSTEM LAB

A CREATE TABLE statement creates a table. Tables contain columns and


constraints, rules to which data must conform. Table-level constraints specify a column or
columns. Columns have a data type and can specify column constraints.
Defines each column of the table Uniquley. Each column has minimum of three attributes.
 Name
 Datatype
 Size
A name can have upto 30 Characters
Alphabets from A-Z,a-z and numbers from 0-9 are allowed.
A name should begin with an alphabet.
The use of special characters is allowed lile _ , $ , # .
SQL reserved words are not allowed.

Syntax:-
CREATE TABLE table_name (column_name1 datatype,column_name2 datatype,...
column_nameN datatype);

SQL> create table SIET (Sno number(2),


2 Department varchar2(15),
3 Sections number(2));

Table created.

insert statement:-
The INSERT statement adds one or more new rows of data to a database table.
If there are less values being described than there are columns in the table then it is
mandatory to indicate both the columns and there column values.
If there are exactly the same number of values as there are columns and the values
are sequenced in exactly in accordance with the data type of the table columns there is no
need to indicate the column names.

Syntax:-
INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1,
value2, value3, ...);

SQL> insert into SIET (Sno,Department,Sections) values


(&Sno,'&Department',&Sections);
Enter value for sno: 1
Enter value for department: EEE
Enter value for sections: 2
old 1: insert into SIET (Sno,Department,Sections) values
(&Sno,'&Department',&Sections)
new 1: insert into SIET (Sno,Department,Sections) values (1,'EEE',2)

1 row created.

SQL> /
Enter value for sno: 2
Enter value for department: Mechanical

Department of Computer Science & Engineering 22


DATA BASE MANAGEMENT SYSTEM LAB

Enter value for sections: 5


old 1: insert into SIET (Sno,Department,Sections) values
(&Sno,'&Department',&Sections)
new 1: insert into SIET (Sno,Department,Sections) values (2,'Mechanical',5)
1 row created.

SQL> /
Enter value for sno: 3
Enter value for department: ECE
Enter value for sections: 7
old 1: insert into SIET (Sno,Department,Sections) values
(&Sno,'&Department',&Sections)
new 1: insert into SIET (Sno,Department,Sections) values (3,'ECE',7)

1 row created.

SQL> /
Enter value for sno: 4
Enter value for department: CSE
Enter value for sections: 8
old 1: insert into SIET (Sno,Department,Sections) values
(&Sno,'&Department',&Sections)
new 1: insert into SIET (Sno,Department,Sections) values (4,'CSE',8)
1 row created.

SQL> /
Enter value for sno: 5
Enter value for department: MBA
Enter value for sections: 3
old 1: insert into SIET (Sno,Department,Sections) values
(&Sno,'&Department',&Sections)
new 1: insert into SIET (Sno,Department,Sections) values (5,'MBA',3)
1 row created.

select command:-
The SELECT statement is used to select data from a database.
Syntax:-
SELECT column1, column2, ... FROM table_name;
SELECT * FROM table_name;

SQL> select * from SIET;

SNO DEPARTMENT SECTIONS


---------- --------------------------------------------- ----------
1 EEE 2
2 Mechanical 5
3 ECE 7
4 CSE 8
5 MBA 3
delete command:-
The DELETE statement is used to delete existing records in a table.

Department of Computer Science & Engineering 23


DATA BASE MANAGEMENT SYSTEM LAB

Syntax:-
DELETE FROM table_name WHERE [condition];

SQL> delete from SIET where Department='MBA';

1 row deleted.

SQL> select * from SIET;

SNO DEPARTMENT SECTIONS


---------- --------------------------------------------- ----------
1 EEE 2
2 Mechanical 5
3 ECE 7
4 CSE 8

alter command:-
The ALTER TABLE statement is used to add, delete, or modify columns in an
existing table.
The ALTER TABLE statement is also used to add and drop various constraints on an
existing table.
Syntax:-
ALTER TABLE table_name ADD column_name datatype;
alter table table_name add(column datatype);

SQL> alter table Student add(Total number(3));

Table altered.

SQL> select * from Student;

SNO NAME CD DBMS OS TOTAL


---------- --------------------------------------------- ---------- ---------- ---------- ----------
501 Rama 58 60 78
502 Sita 69 40 61
503 Lakshmi 76 18 87
504 Sai 23 84 51
505 Kumar 89 45 72
506 Satya 76 34 81
507 John 34 78 65
508 Yamini 76 56 23
509 Sushma 62 65 81
510 Lalitha 64 51 23
511 Rama 34 92 65
512 Sita 44 82 20

12 rows selected.

update command:-
The UPDATE statement is used to modify the existing records in a table.

Department of Computer Science & Engineering 24


DATA BASE MANAGEMENT SYSTEM LAB

Syntax:-
UPDATE table_name SET column1 = value1, column2 = value2, ...
WHERE condition;
update table_name set condition;

SQL> update Student set Total=CD+DBMS+OS;

12 rows updated.

SQL> select * from Student;

SNO NAME CD DBMS OS TOTAL


---------- --------------------------------------------- ---------- ---------- ---------- ----------
501 Rama 58 60 78 196
502 Sita 69 40 61 170
503 Lakshmi 76 18 87 181
504 Sai 23 84 51 158
505 Kumar 89 45 72 206
506 Satya 76 34 81 191
507 John 34 78 65 177
508 Yamini 76 56 23 155
509 Sushma 62 65 81 208
510 Lalitha 64 51 23 138
511 Rama 34 92 65 191
512 Sita 44 82 20 146

12 rows selected.

Queries using Group By, Order By, and Having Clauses

Department of Computer Science & Engineering 25


DATA BASE MANAGEMENT SYSTEM LAB

SQL> select * from Employee;

ENO ENAME JOB SALARY


---------- --------------------------------------------- ------------------------------ ----------
1 Smith Clerk 2000
2 Ram Salesman 5000
3 Sita Manager 200000
4 James Analyst 5000
5 Kiran Clerk 3000
6 James Clerk 4000
7 Ram Manager 15000
8 Kumar Salesman 6000

8 rows selected.

group by clause:-

SELECT [DISTINCT] select-list


FROM from-list
WHERE qualification
GROUP BY grouping-list
HAVING group-qualification

 The select list in the SELECT clause contain


1. A list of column names
2. A list of terms having the form aggop( aggregate operators)
Every column that appear in (1) must also appear in grouping-list
The expression appearing in the group-qualification in the HAVING clause must have a
single value per group.
Syntax:-
SELECT column_name(s) FROM table_name WHERE condition GROUP BY
column_name(s);

Find the sum of salaries of employee for each job title.

SQL> select Job,Sum(Salary) from Employee group by Job;

JOB SUM(SALARY)
------------------------------ -----------
Clerk 9000
Manager 215000
Analyst 5000
Salesman 11000

Find the no of employees for each job title.

SQL> select Job,Count(Job) from Employee group by Job;

Department of Computer Science & Engineering 26


DATA BASE MANAGEMENT SYSTEM LAB

JOB COUNT(JOB)
------------------------------ ----------
Clerk 3
Manager 2
Analyst 1
Salesman 2

order by clause:-
Syntax:-
SELECT column_name(s) FROM table_name WHERE conditionORDER BY
column_name(s);

SQL> select * from Employee order by Ename;

ENO ENAME JOB SALARY


---------- --------------------------------------------- ------------------------------ ----------
4 James Analyst 5000
6 James Clerk 4000
5 Kiran Clerk 3000
8 Kumar Salesman 6000
7 Ram Manager 15000
2 Ram Salesman 5000
3 Sita Manager 200000
1 Smith Clerk 2000

8 rows selected.

SQL> select * from Employee order by Ename asc;

ENO ENAME JOB SALARY


---------- --------------------------------------------- ------------------------------ ----------
4 James Analyst 5000
6 James Clerk 4000
5 Kiran Clerk 3000
8 Kumar Salesman 6000
7 Ram Manager 15000
2 Ram Salesman 5000
3 Sita Manager 200000
1 Smith Clerk 2000

8 rows selected.

SQL> select * from Employee order by Ename desc;

ENO ENAME JOB SALARY

Department of Computer Science & Engineering 27


DATA BASE MANAGEMENT SYSTEM LAB

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


1 Smith Clerk 2000
3 Sita Manager 200000
7 Ram Manager 15000
2 Ram Salesman 5000
8 Kumar Salesman 6000
5 Kiran Clerk 3000
6 James Clerk 4000
4 James Analyst 5000

8 rows selected.

having clause:-
Syntax:-
SELECT column_name(s)FROM table_name WHERE condition GROUP BY
column_name(s) ;

Find the sum of salaries of all clerks.

SQL> select Job,Sum(Salary) from Employee group by Job having Job='Clerk';

JOB SUM(SALARY)
------------------------------ -----------
Clerk 9000

Find the sum of salaries of clerks where salary is above 3000.

SQL> select Job,Sum(Salary) from Employee where Salary>3000 group by Job having
Job='Clerk';

JOB SUM(SALARY)
------------------------------ -----------
Clerk 4000

Find the sum of salaries of employees for each job title whose maximum
salary exceeds 10000.

SQL> select Job,Sum(Salary) from Employee group by Job having max(Salary)>10000;

JOB SUM(SALARY)
------------------------------ -----------
Manager 215000

Queries on Controlling Data: Commit, Rollback, and Save point

commit command:-

Department of Computer Science & Engineering 28


DATA BASE MANAGEMENT SYSTEM LAB

Syntax:-
commit;
SQL> commit;
Commit complete.

rollback command:-
Syntax:-
ROLLBACK TO savepoint_name;

SQL> delete from Employee where Eno=1;

1 row deleted.

SQL> delete from Employee where Eno=2;

1 row deleted.

SQL> select * from Employee;

ENO ENAME JOB SALARY


---------- --------------------------------------------- ------------------------------ ----------
3 Sita Manager 200000
4 James Analyst 5000
5 Kiran Clerk 3000
6 James Clerk 4000
7 Ram Manager 15000
8 Kumar Salesman 6000

6 rows selected.

SQL> rollback;

Rollback complete.

SQL> select * from Employee;

ENO ENAME JOB SALARY


---------- --------------------------------------------- ------------------------------ ----------
1 Smith Clerk 2000
2 Ram Salesman 5000
3 Sita Manager 200000
4 James Analyst 5000
5 Kiran Clerk 3000
6 James Clerk 4000
7 Ram Manager 15000
8 Kumar Salesman 6000
8 rows selected.

SQL> delete from Employee;


8 rows deleted.

SQL> select * from Employee;

Department of Computer Science & Engineering 29


DATA BASE MANAGEMENT SYSTEM LAB

no rows selected

SQL> rollback;
Rollback complete.

SQL> select * from Employee;

ENO ENAME JOB SALARY


---------- --------------------------------------------- ------------------------------ ----------
1 Smith Clerk 2000
2 Ram Salesman 5000
3 Sita Manager 200000
4 James Analyst 5000
5 Kiran Clerk 3000
6 James Clerk 4000
7 Ram Manager 15000
8 Kumar Salesman 6000

8 rows selected.

savepoint command:-
Syntax:-
SAVEPOINT savepoint_name;

SQL> savepoint abc;


Savepoint created.

SQL> delete from Employee where Salary=2000;


1 row deleted.

SQL> savepoint xyz;


Savepoint created.

SQL> delete from Employee where Eno=2;


1row deleted.

SQL> select * from Employee;

ENO ENAME JOB SALARY


---------- --------------------------------------------- ------------------------------ ----------
3 Sita Manager 200000
4 James Analyst 5000
5 Kiran Clerk 3000
6 James Clerk 4000
7 Ram Manager 15000
8 Kumar Salesman 6000

6 rows selected.
SQL> rollback to xyz;
Rollback complete.

SQL> select * from Employee;

Department of Computer Science & Engineering 30


DATA BASE MANAGEMENT SYSTEM LAB

ENO ENAME JOB SALARY


---------- --------------------------------------------- ------------------------------ ----------
2 Ram Salesman 5000
3 Sita Manager 200000
4 James Analyst 5000
5 Kiran Clerk 3000
6 James Clerk 4000
7 Ram Manager 15000
8 Kumar Salesman 6000

7 rows selected.

SQL> rollback to abc;


Rollback complete.

SQL> select * from Employee;

ENO ENAME JOB SALARY


---------- --------------------------------------------- ------------------------------ ----------
1 Smith Clerk 2000
2 Ram Salesman 5000
3 Sita Manager 200000
4 James Analyst 5000
5 Kiran Clerk 3000
6 James Clerk 4000
7 Ram Manager 15000
8 Kumar Salesman 6000

8 rows selected.

Queries to Build Report in SQL *PLUS

REPFOOTER:-

Department of Computer Science & Engineering 31


DATA BASE MANAGEMENT SYSTEM LAB

SQL*Plus displays the constants and variables in the order you specify them,
positioning and formatting each constant or variable as specified by the printspec clauses
that precede it.

SQL> REPFOOTER PAGE CENTER 'SIET DEPARTMENT DETAILS'


TITLE RIGHT 'Page: 'FORMAT 999 SQL.PNO
SELECT Department,Sections
from SIET where Sections>5;

REPHEADER:-

SQL*Plus displays the constants and variables in the order you specify, positioning and
formatting each constant or variable as specified by the printspec clauses that precede it.

SQL>REPHEADER PAGE CENTER 'SIET DEPARTMENT DETAILS'


TTITLE RIGHT 'Page: ' FORMAT 999 SQL.PNO
SELECT Department,Sections from SIET where Sections>5;

RUN:-
RUN causes the last line of the SQL buffer to become the current line.
The slash command (/) functions similarly to RUN, but does not list the command in the
SQL buffer on your screen. The SQL buffer always contains the last SQL statement or PL/SQL

Department of Computer Science & Engineering 32


DATA BASE MANAGEMENT SYSTEM LAB

block entered.

SAVE:-
If you do not specify an extension, SQL*Plus assumes the default command-file
extension (normally SQL).

SET:-
SET CMDSEP + TTITLE LEFT 'SECTIONS' + COLUMN Sections FORMAT $99,999
SELECT Department,Sections FROM SIET WHERE Sections>6;

Department of Computer Science & Engineering 33


DATA BASE MANAGEMENT SYSTEM LAB

set serveroutput on;-

Show:-

SPOOL:-
Stores query results in a file, or optionally sends the file to a printer.
Represents the name of the file to which you wish to spool. SPOOL followed by
file_name begins spooling displayed output to the named file. If you do not specify an extension,
SPOOL uses a default extension (LST or LIS on most systems).

Department of Computer Science & Engineering 34


DATA BASE MANAGEMENT SYSTEM LAB

OFF

Stops spooling.

OUT
Stops spooling and sends the file to your host computer's standard (default) printer. This
option is not available on some operating systems.

Enter SPOOL with no clauses to list the current spooling status.

TIMING:-
Records timing data for an elapsed period of time, lists the current timer's name and
timing data, or lists the number of active timers.

WHENEVER OSERROR:-

Performs the specified action (stops the current script by default) and returns focus to the
Input area if an operating system error occurs.

Department of Computer Science & Engineering 35


DATA BASE MANAGEMENT SYSTEM LAB

If you do not enter the WHENEVER OSERROR command, the default behavior of
SQL*Plus is to continue and take no action when an operating system error occurs.

Example:
The commands in the following script cause SQL*Plus to exit and COMMIT any pend-
ing changes if a failure occurs when reading from the output file:

WHENEVER OSERROR EXIT


START no_such_file

Screen icon

OS Message: No such file or directory


Disconnected from Oracle......

WHENEVER SQLERROR:-

Performs the specified action (exits SQL*Plus by default) if a SQL command or PL/SQL
block generates an error.

Usage:
The WHENEVER SQLERROR command is triggered by SQL command or PL/SQL
block errors, and not by SQL*Plus command errors.

Example:
The commands in the following script cause SQL*Plus to exit and return the SQL error
code if the SQL UPDATE command fails:

Keyboard icon

WHENEVER SQLERROR EXIT SQL.SQLCODE


UPDATE EMP_DETAILS_VIEW SET SALARY = SALARY*1.1

CLEAR option ...:-

where option represents one of the following clauses:

BREAKS
BUFFER
COLUMNS
COMPUTES
SCREEN
SQL

TIMING:
Resets or erases the current value or setting for the specified option.

Terms:
Refer to the following list for a description of each term or clause:

BREAKS:

Department of Computer Science & Engineering 36


DATA BASE MANAGEMENT SYSTEM LAB

Removes the break definition set by the BREAK command.

BUFFER:
Clears text from the buffer. CLEAR BUFFER has the same effect as CLEAR SQL, un-
less you are using multiple buffers (see the SET BUFFER command in Appendix C, "Obsolete
SQL*Plus Commands").

COLUMNS:
Resets column display attributes set by the COLUMN command to default settings for all
columns. To reset display attributes for a single column, use the CLEAR clause of the COL-
UMN command. CLEAR COLUMNS also clears the ATTRIBUTEs for that column.

COMPUTES:
Removes all COMPUTE definitions set by the COMPUTE command.

SCREEN:
Clears your screen.

CLEAR SCREEN is not available in iSQL*Plus.

SQL:
Clears the text from SQL buffer. CLEAR SQL has the same effect as CLEAR BUFFER,
unless you are using multiple buffers (see the SET BUFFER command in Appendix C, "Obso-
lete SQL*Plus Commands").

TIMING:
Deletes all timers created by the TIMING command.
Examples
To clear breaks, enter
Keyboard icon

CLEAR BREAKS:
To clear column definitions, enter
Keyboard icon

CLEAR COLUMNS:

COLUMN:-

COLUMN [{column|expr} [option ...]]

Department of Computer Science & Engineering 37


DATA BASE MANAGEMENT SYSTEM LAB

Enter COLUMN followed by column or expr and no other clauses to list the current dis-
play attributes for only the specified column or expression. Enter COLUMN with no clauses to
list all current column display attributes.

Usage:
You can enter any number of COLUMN commands for one or more columns. All col-
umn attributes set for each column remain in effect for the remainder of the session, until you
turn the column OFF, or until you use the CLEAR COLUMN command. Thus, the COLUMN
commands you enter can control a column's display attributes for multiple SQL SELECT com-
mands.
When you enter multiple COLUMN commands for the same column, SQL*Plus applies
their clauses collectively. If several COLUMN commands apply the same clause to the same
column, the last one entered will control the output.

Examples:
To make the LAST_NAME column 20 characters wide and display EMPLOYEE NAME
on two lines as the column heading, enter

Keyboard icon

COLUMN LAST_NAME FORMAT A20 HEADING 'EMPLOYEE|NAME'

To format the SALARY column so that it shows millions of dollars, rounds to cents, uses
commas to separate thousands, and displays $0.00 when a value is zero, enter

Keyboard icon
COLUMN SALARY FORMAT $9,999,990.99

To assign the alias NET to a column containing a long expression, to display the result in a dol-
lar format, and to display <NULL> for null values, you might enter

Keyboard icon

COLUMN SALARY+COMMISSION_PCT+BONUS-EXPENSES-INS-TAX ALIAS NET


COLUMN NET FORMAT $9,999,999.99 NULL '<NULL>'

ACCEPT:-

To display the prompt "Enter weekly salary: " and place the reply in a NUMBER vari-
able named SALARY with a default of 000.0, enter

Department of Computer Science & Engineering 38


DATA BASE MANAGEMENT SYSTEM LAB

Keyboard icon

ACCEPT salary NUMBER FORMAT '999.99' DEFAULT '000.0' -


PROMPT 'Enter weekly salary: '

To display the prompt "Enter date hired: " and place the reply in a DATE variable named
HIRED with the format "dd/mm/yyyy" and a default of "01/01/2001", enter

Keyboard icon

ACCEPT hired DATE FORMAT 'dd/mm/yyyy' DEFAULT '01/01/2001'-


PROMPT 'Enter date hired: '

APPEND:-

To append a comma delimiter, a space and the column name CITY to the first line of the
buffer, make that line the current line by listing the line as follows:
Keyboard icon
1
Screen icon
1* SELECT DEPARTMENT_ID
Now enter APPEND:

Keyboard icon
APPEND , CITY
1
Screen icon
1* SELECT DEPARTMENT_ID, CITY

To append a semicolon to the line, enter


Keyboard icon
APPEND ;;

ARCHIVE LOG:-
Starts or stops automatic archiving of online redo log files, manually (explicitly) archives
specified redo log files, or displays information about redo log files.
To start up the archiver process and begin automatic archiving, using the archive destina-
tion specified in LOG_ARCHIVE_DEST, enter

Keyboard icon

ARCHIVE LOG START


To stop automatic archiving, enter

Keyboard icon

ARCHIVE LOG STOP


Queries for Creating, Dropping, and Altering Tables, Views, and Constraints

Creating table:-
Syntax:-

Department of Computer Science & Engineering 39


DATA BASE MANAGEMENT SYSTEM LAB

CREATE TABLE table_name (column1 datatype,


column2 datatype,
column3 datatype,
....);
SQL> create table SIET (Sno number(2),
2 Department varchar2(15),
3 Sections number(2));
Table created.

Dropping table:-
Syntax:-
DROP TABLE table_name;

SQL> drop table SIET;


Table dropped.
SQL> select * from SIET;

select * from SIET


*
ERROR at line 1:
ORA-00942: table or view does not exist

Altering table:-
Syntax:-
ALTER TABLE table_name ADD column_name datatype;

SQL> alter table Student add(Total number(3));


Table altered.

SQL> select * from Student;

SNO NAME CD DBMS OS TOTAL


---------- --------------------------------------------- ---------- ---------- ---------- ----------
501 Rama 58 60 78
502 Sita 69 40 61
503 Lakshmi 76 18 87
504 Sai 23 84 51
505 Kumar 89 45 72
506 Satya 76 34 81
507 John 34 78 65
508 Yamini 76 56 23
509 Sushma 62 65 81
510 Lalitha 64 51 23
511 Rama 34 92 65
512 Sita 44 82 20
12 rows selected.
Creating and dropping of views:-

Syntax:-
CREATE VIEW view_name AS SELECT column1, column2, ...

Department of Computer Science & Engineering 40


DATA BASE MANAGEMENT SYSTEM LAB

FROM table_name WHERE condition;

Creating Sailorsreserved view:-

SQL> create view Sailorsreserved (Sid,Sname,Bid) as select s.Sid,s.Sname,r.Bid from Sailors


s,Reserves r where s.Sid=r.Sid;

View created.

SQL> select * from Sailorsreserved;

SID SNAME BID


---------- ------------------------------ ----------
22 Dustin 101
22 Dustin 102
22 Dustin 103
22 Dustin 104
31 Lubber 102
31 Lubber 103
31 Lubber 104
64 Horatio 101
64 Horatio 102
74 Horatio 103

10 rows selected.

Creating Goodsailors view:-

SQL> create view Goodsailors (Sid,Sname,Rating) as select s.Sid,s.Sname,s.rating from Sailors


s where s.Rating>7;

View created.

SQL> select * from Goodsailors;

SID SNAME RATING


---------- ------------------------------ ----------
31 Lubber 8
32 Andy 8
58 Rusty 10
71 Zorba 10
74 Horatio 9

Dropping of views:-

Syntax:-

Department of Computer Science & Engineering 41


DATA BASE MANAGEMENT SYSTEM LAB

DROP VIEW view_name;

SQL> drop view Goodsailors;


View dropped.

SQL> select * from Goodsailors;

select * from Goodsailors


*
ERROR at line 1:
ORA-00942: table or view does not exist

Constraints;-

not null constraint:-

Department of Computer Science & Engineering 42


DATA BASE MANAGEMENT SYSTEM LAB

SQL> create table Details(Sno number(3),


2 Name varchar2(10),
3 Department varchar2(5) constraint Dept not null);
Table created.

SQL> insert into Details(Sno,Name,Department) values (&Sno,'&Name','&Department');


Enter value for sno: 1
Enter value for name: Satya
Enter value for department:
old 1: insert into Details(Sno,Name,Department) values (&Sno,'&Name','&Department')
new 1: insert into Details(Sno,Name,Department) values (1,'Satya','')

insert into Details(Sno,Name,Department) values (1,'Satya','')


*
ERROR at line 1:
ORA-01400: cannot insert NULL into ("MANUAL"."DETAILS"."DEPARTMENT")

unique constraint:-
column level:-

SQL> create table Department(Regno number(3) constraint Regnumber unique,


2 Name varchar2(15),
3 Year number(2,1));
Table created.

SQL> insert into Department (Regno,Name,Year) values (&Regno,'&Name',&Year);


Enter value for regno: 501
Enter value for name: Anand
Enter value for year: 4.1
old 1: insert into Department (Regno,Name,Year) values (&Regno,'&Name',&Year)
new 1: insert into Department (Regno,Name,Year) values (501,'Anand',4.1)
1 row created.

SQL> /
Enter value for regno: 501
Enter value for name: Devi
Enter value for year: 2
old 1: insert into Department (Regno,Name,Year) values (&Regno,'&Name',&Year)
new 1: insert into Department (Regno,Name,Year) values (501,'Devi',2)

insert into Department (Regno,Name,Year) values (501,'Devi',2)


*
ERROR at line 1:
ORA-00001: unique constraint (MANUAL.REGNUMBER) violated

Table
level:-

SQL> create table College(Admno number(5),


2 Regno number(5),

Department of Computer Science & Engineering 43


DATA BASE MANAGEMENT SYSTEM LAB

3 Name varchar2(10),
4 Branch varchar2(5),
5 unique(Admno,Regno));

Table created.

SQL> insert into College (Admno,Regno,Name,Branch) values


(&Admno,&Regno,'&Name','&Branch');
Enter value for admno: 101
Enter value for regno: 501
Enter value for name: Kiran
Enter value for branch: CSE
old 1: insert into College (Admno,Regno,Name,Branch) values
(&Admno,&Regno,'&Name','&Branch')
new 1: insert into College (Admno,Regno,Name,Branch) values (101,501,'Kiran','CSE')

1 row created.

SQL> /
Enter value for admno: 101
Enter value for regno: 401
Enter value for name: Radha
Enter value for branch: ECE
old 1: insert into College (Admno,Regno,Name,Branch) values
(&Admno,&Regno,'&Name','&Branch')
new 1: insert into College (Admno,Regno,Name,Branch) values(101,401,'Radha','ECE')

1 row created.

SQL> /
Enter value for admno: 101
Enter value for regno: 501
Enter value for name: Kumar
Enter value for branch: CSE
old 1: insert into College (Admno,Regno,Name,Branch) values
(&Admno,&Regno,'&Name','&Branch')
new 1: insert into College (Admno,Regno,Name,Branch) values
(101,501,'Kumar','CSE')

insert into College (Admno,Regno,Name,Branch) values (101,501,'Kumar','CSE')


*
ERROR at line 1:
ORA-00001: unique constraint (MANUAL.SYS_C004063) violated

Primary key:-

SQL> create table Sailors(Sid number(3) primary key,


2 Sname varchar2(10) not null,

Department of Computer Science & Engineering 44


DATA BASE MANAGEMENT SYSTEM LAB

3 Rating number(3),
4 Age number(3,1));

Table created.

SQL> insert into Sailors(Sid,Sname,Rating,Age) values (&Sid,'&Sname',&Rating,&Age);


Enter value for sid: 22
Enter value for sname: Dustin
Enter value for rating: 7
Enter value for age: 45
old 1: insert into Sailors(Sid,Sname,Rating,Age) values (&Sid,'&Sname',&Rating,&Age)
new 1: insert into Sailors(Sid,Sname,Rating,Age) values (22,'Dustin',7,45)

1 row created.

SQL> /
Enter value for sid: 22
Enter value for sname: Lubber
Enter value for rating: 8
Enter value for age: 25.5
old 1: insert into Sailors(Sid,Sname,Rating,Age) values (&Sid,'&Sname',&Rating,&Age)
new 1: insert into Sailors(Sid,Sname,Rating,Age) values (22,'Lubber',8,25.5)

insert into Sailors(Sid,Sname,Rating,Age) values (22,'Lubber',8,25.5)


*
ERROR at line 1:
ORA-00001: unique constraint (MANUAL.SYS_C004055) violated

SQL> /
Enter value for sid:
Enter value for sname: Horatio
Enter value for rating: 9
Enter value for age: 34.5
old 1: insert into Sailors(Sid,Sname,Rating,Age) values (&Sid,'&Sname',&Rating,&Age)
new 1: insert into Sailors(Sid,Sname,Rating,Age) values (,'Horatio',9,34.5)

insert into Sailors(Sid,Sname,Rating,Age) values (,'Horatio',9,34.5)


*
ERROR at line 1:
ORA-00936: missing expression

Department of Computer Science & Engineering 45


DATA BASE MANAGEMENT SYSTEM LAB

Foreign key constraint:-

SQL> create table Reserves(Sid number(3),


2 Bid number(3),
3 Day date,
4 primary key(Sid,Bid),
5 foreign key(Sid) references Sailors(Sid),
6 foreign key(Bid) references Boats(Bid));

Table created.

SQL> insert into Reserves(Sid,Bid,Day) values (&Sid,&Bid,'&Day');


Enter value for sid: 95
Enter value for bid: 104
Enter value for day: 10-Oct-17
old 1: insert into Reserves(Sid,Bid,Day) values (&Sid,&Bid,'&Day')
new 1: insert into Reserves(Sid,Bid,Day) values (95,104,'10-Oct-17')

1 row created.

SQL> /
Enter value for sid: 65
Enter value for bid: 102
Enter value for day: 09-Aug-17
old 1: insert into Reserves(Sid,Bid,Day) values (&Sid,&Bid,'&Day')

insert into Reserves(Sid,Bid,Day) values (65,102,'09-Aug-17')


*
ERROR at line 1:
ORA-02291: integrity constraint (MANUAL.SYS_C004059) violated - parent key not found

new 1: insert into Reserves(Sid,Bid,Day) values (65,102,'09-Aug-17')

SQL> /
Enter value for sid: 31
Enter value for bid: 106
Enter value for day: 25-Aug-17
old 1: insert into Reserves(Sid,Bid,Day) values (&Sid,&Bid,'&Day')
new 1: insert into Reserves(Sid,Bid,Day) values (31,106,'25-Aug-17')

insert into Reserves(Sid,Bid,Day) values (31,106,'25-Aug-17')


*
ERROR at line 1:
ORA-02291: integrity constraint (MANUAL.SYS_C004060) violated - parent key not found

Check constraint:-

SQL> create table Marksmemo(Sno number(3),

Department of Computer Science & Engineering 46


DATA BASE MANAGEMENT SYSTEM LAB

2 Name varchar2(10),
3 CD number(3) check(CD between 0 and 100),
4 DBMS number(3) check(DBMS between 0 and 100),
5 OS number(3) check(OS between 0 and 100));

Table created.

SQL> insert into Marksmemo(Sno,Name,CD,DBMS,OS) values


(&Sno,'&Name',&CD,&DBMS,&OS);
Enter value for sno: 501
Enter value for name: Raghu
Enter value for cd: 67
Enter value for dbms: 45
Enter value for os: 89
old 1: insert into Marksmemo(Sno,Name,CD,DBMS,OS) values
(&Sno,'&Name',&CD,&DBMS,&OS)
new 1: insert into Marksmemo(Sno,Name,CD,DBMS,OS) values (501,'Raghu',67,45,89)

1 row created.

SQL> /
Enter value for sno: 502
Enter value for name: Swamy
Enter value for cd: 81
Enter value for dbms: 102
Enter value for os: 56
old 1: insert into Marksmemo(Sno,Name,CD,DBMS,OS) values
(&Sno,'&Name',&CD,&DBMS,&OS)
new 1: insert into Marksmemo(Sno,Name,CD,DBMS,OS) values (502,'Swamy',81,102,56)

insert into Marksmemo(Sno,Name,CD,DBMS,OS) values (502,'Swamy',81,102,56)


*
ERROR at line 1:
ORA-02290: check constraint (MANUAL.SYS_C004065) violated

Default constraint:-

Department of Computer Science & Engineering 47


DATA BASE MANAGEMENT SYSTEM LAB

SQL> create table Studentinfo(Sno number(3),


2 Name varchar2(10),
3 Branch varchar2(5) default 'CSE');

Table created.

SQL> insert into Studentinfo(Sno,Name) values (&Sno,'&Name');


Enter value for sno: 501
Enter value for name: Geeta
old 1: insert into Studentinfo(Sno,Name) values (&Sno,'&Name')
new 1: insert into Studentinfo(Sno,Name) values (501,'Geeta')

1 row created.

SQL> /
Enter value for sno: 502
Enter value for name: Rani
old 1: insert into Studentinfo(Sno,Name) values (&Sno,'&Name')
new 1: insert into Studentinfo(Sno,Name) values (502,'Rani')

1 row created.

SQL> select * from Studentinfo;

SNO NAME BRANCH


---------- ------------------------------ ---------------
501 Geeta CSE
502 Rani CSE

Queries on Joins and Correlated Sub-Queries.

Department of Computer Science & Engineering 48


DATA BASE MANAGEMENT SYSTEM LAB

Queries on joins:-

Inner joins:-

SQL> select s.Sid,s.Sname,r.Day from Sailors s inner join Reserves r on s.Sid=r.Sid;

SID SNAME DAY


---------- ------------------------------ ------------------
22 Dustin 10-OCT-17
22 Dustin 10-OCT-17
22 Dustin 10-AUG-17
22 Dustin 10-JUL-17
31 Lubber 11-OCT-17
31 Lubber 11-JUN-17
31 Lubber 11-DEC-17
64 Horatio 09-MAY-17
64 Horatio 09-AUG-17
74 Horatio 09-AUG-17
95 Bob 10-OCT-17

11 rows selected.

Outer joins:-

Left outer join:-

SQL> select s.Sid,s.Sname,r.Day from Sailors s left join Reserves r on s.Sid=r.Sid;

SID SNAME DAY


---------- ------------------------------ ------------------
22 Dustin 10-OCT-17
22 Dustin 10-OCT-17
22 Dustin 10-AUG-17
22 Dustin 10-JUL-17
31 Lubber 11-OCT-17
31 Lubber 11-JUN-17
31 Lubber 11-DEC-17
64 Horatio 09-MAY-17
64 Horatio 09-AUG-17
74 Horatio 09-AUG-17
95 Bob 10-OCT-17
71 Zorba
85 Art
58 Rusty
32 Andy
29 Bretus

Right outer join:-

Department of Computer Science & Engineering 49


DATA BASE MANAGEMENT SYSTEM LAB

SQL> select s.Sid,s.Sname,r.Bid from Sailors s right join Reserves r on s.Sid=r.Sid;

SID SNAME BID


---------- ------------------------------ ----------
22 Dustin 104
22 Dustin 103
22 Dustin 102
22 Dustin 101
31 Lubber 104
31 Lubber 103
31 Lubber 102
64 Horatio 102
64 Horatio 101
74 Horatio 103
95 Bob 104

11 rows selected.

Full outer join:-

SQL> select s.Sid,s.Sname,r.Bid from Sailors s full join Reserves r on s.Sid=r.Sid;

SID SNAME BID


---------- ------------------------------ ----------
22 Dustin 101
22 Dustin 102
22 Dustin 103
22 Dustin 104
29 Bretus
31 Lubber 102
31 Lubber 103
31 Lubber 104
32 Andy
58 Rusty
64 Horatio 101
64 Horatio 102
71 Zorba
74 Horatio 103
85 Art
95 Bob 104

16 rows selected.

Cross join:-

Department of Computer Science & Engineering 50


DATA BASE MANAGEMENT SYSTEM LAB

SQL> select * from Boats b cross join Reserves r;

BID BNAME COLOUR SID BID DAY


---------- ------------------------------ ------------------------ ---------- ---------- ------------------
101 Interlake Blue 22 101 10-OCT-17
101 Interlake Blue 22 102 10-OCT-17
101 Interlake Blue 22 103 10-AUG-17
101 Interlake Blue 22 104 10-JUL-17
101 Interlake Blue 31 102 11-OCT-17
101 Interlake Blue 31 103 11-JUN-17
101 Interlake Blue 31 104 11-DEC-17
101 Interlake Blue 64 101 09-MAY-17
101 Interlake Blue 64 102 09-AUG-17
101 Interlake Blue 74 103 09-AUG-17
101 Interlake Blue 95 104 10-OCT-17

BID BNAME COLOUR SID BID DAY


---------- ------------------------------ ------------------------ ---------- ---------- ------------------
102 Interlake Red 22 101 10-OCT-17
102 Interlake Red 22 102 10-OCT-17
102 Interlake Red 22 103 10-AUG-17
102 Interlake Red 22 104 10-JUL-17
102 Interlake Red 31 102 11-OCT-17
102 Interlake Red 31 103 11-JUN-17
102 Interlake Red 31 104 11-DEC-17
102 Interlake Red 64 101 09-MAY-17
102 Interlake Red 64 102 09-AUG-17
102 Interlake Red 74 103 09-AUG-17
102 Interlake Red 95 104 10-OCT-17

BID BNAME COLOUR SID BID DAY


---------- ------------------------------ ------------------------ ---------- ---------- ------------------
103 Clipper Green 22 101 10-OCT-17
103 Clipper Green 22 102 10-OCT-17
103 Clipper Green 22 103 10-AUG-17
103 Clipper Green 22 104 10-JUL-17
103 Clipper Green 31 102 11-OCT-17
103 Clipper Green 31 103 11-JUN-17
103 Clipper Green 31 104 11-DEC-17
103 Clipper Green 64 101 09-MAY-17
103 Clipper Green 64 102 09-AUG-17
103 Clipper Green 74 103 09-AUG-17
103 Clipper Green 95 104 10-OCT-17

BID BNAME COLOUR SID BID DAY


---------- ------------------------------ ------------------------ ---------- ---------- ------------------
104 Marine Red 22 101 10-OCT-17
104 Marine Red 22 102 10-OCT-17
104 Marine Red 22 103 10-AUG-17
104 Marine Red 22 104 10-JUL-17
104 Marine Red 31 102 11-OCT-17
104 Marine Red 31 103 11-JUN-17

Department of Computer Science & Engineering 51


DATA BASE MANAGEMENT SYSTEM LAB

104 Marine Red 31 104 11-DEC-17


104 Marine Red 64 101 09-MAY-17
104 Marine Red 64 102 09-AUG-17
104 Marine Red 74 103 09-AUG-17
104 Marine Red 95 104 10-OCT-17

44 rows selected.

Self join:-

SQL> select * from Student s1,Student s2 where s1.DBMS=s2.OS;

SNO NAME CD DBMS OS TOTAL SNO NAME CD DBMS OS TOTAL


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

507 John 34 78 65 177 501 Rama 58 60 78 196


510 Lalitha 64 51 23 138 504 Sai 23 84 51 158
509 Sushma 62 65 81 208 507 John 34 78 65 177
509 Sushma 62 65 81 208 511 Rama 34 92 65 191

Sub-Queries:-

Department of Computer Science & Engineering 52


DATA BASE MANAGEMENT SYSTEM LAB

in operator:-

Find the names of sailors who have reserved a boat number 103.

SQL> select S.Sname from Sailors s where s.Sid in (select r.Sid from Reserves r
where r.Bid=103);

SNAME
------------------------------
Dustin
Lubber
Horatio

Find the names of sailors who have reserved a red boat.

SQL> select s.Sname from Sailors s where s.Sid in (select r.Sid from Reserves r,Boats b
where r.Bid=b.Bid and b.Colour='Red');

SNAME
------------------------------
Dustin
Lubber
Horatio
Bob

not in operator:-

Find the names of sailors who have not reserved a red boat.

SQL> select s.Sname from Sailors s where s.Sid not in (select r.Sid from Reserves r
where r.Bid in(select b.Bid from Boats b where b.Colour='Red'));

SNAME
------------------------------
Bretus
Andy
Rusty
Zorba
Horatio
Art

6 rows selected.

Correlated sub queries:-

Department of Computer Science & Engineering 53


DATA BASE MANAGEMENT SYSTEM LAB

exists operator:-

Find the names of sailors who have reserved a boat number 103

SQL> select s.Sname from Sailors s where exists(select * from Reserves r


where s.Sid=r.Sid and r.bid=103);

SNAME
------------------------------
Dustin
Lubber
Horatio

not exists operator:-

Find the names of the sailors who have not reserved a boat number 103.

SQL> select s.Sname from Sailors s where not exists (select * from Reserves r
where s.Sid=r.Sid and r.bid=103);

SNAME
------------------------------
Bretus
Andy
Rusty
Horatio
Zorba
Art
Bob

7 rows selected.

op any:-

Find the sid's of sailors where rating is better than some sailors called Horatio.

SQL> select s1.Sid from Sailors s1 where s1.Rating>any (select s2.Rating from Sailors
s2 where Sname='Horatio');

SID
----------
58
71
74
31
32

op all:-

Department of Computer Science & Engineering 54


DATA BASE MANAGEMENT SYSTEM LAB

Find the sailors whose rating is better than every sailor called Horatio.

SQL> select s1.Sid from Sailors s1 where s1.Rating>all (select s2.Rating from Sailors s2
where Sname='Horatio');

SID
----------
58
71

Pl/sql block using basic variables:

Department of Computer Science & Engineering 55


DATA BASE MANAGEMENT SYSTEM LAB

DECLARE
a integer := 10;
b integer := 20;
c integer;
f real;
BEGIN
c := a + b;
dbms_output.put_line('Value of c: ' || c);
f := 70.0/3.0;
dbms_output.put_line('Value of f: ' || f);
END;
/

OUTPUT:-

Pl/sql block for anchored declarations:

Department of Computer Science & Engineering 56


DATA BASE MANAGEMENT SYSTEM LAB

  DECLARE
   v_Name  Student.Name%TYPE;
  BEGIN
   SELECT Name INTO v_Name FROM Student WHERE sno = 503;
   DBMS_OUTPUT.PUT_LINE (v_Name);
  END;
/

OUTPUT:-

Pl/sql block for usage of assignment operation:

Department of Computer Science & Engineering 57


DATA BASE MANAGEMENT SYSTEM LAB

DECLARE
a number := 17;
b number := 42;
BEGIN
dbms_output.put_line('Before swap');
dbms_output.put_line( 'a = ' || a );
dbms_output.put_line( 'b = ' || b );
SELECT a, b INTO b, a FROM dual;
dbms_output.put_line('After swap');
dbms_output.put_line( 'a = ' || a );
dbms_output.put_line( 'b = ' || b );
END;
/

OUTPUT:-

Pl/sql block for bind vairables:

Department of Computer Science & Engineering 58


DATA BASE MANAGEMENT SYSTEM LAB

create or replace function myfun(p_Sno in number) return varchar2 is


v_Name varchar2(20);
begin
select Name into v_Name from Student where Sno = p_Sno;
return v_Name;
end;
/

OUTPUT:-

Department of Computer Science & Engineering 59


DATA BASE MANAGEMENT SYSTEM LAB

Pl/sql block for substitution of variables:

declare
c_stmt constant varchar2(100) := 'select sysdate from ~t';
v_stmt varchar2(200);
v_date date;
begin
v_stmt := replace(c_stmt, '~t', 'dual');
dbms_output.put_line(v_stmt);
execute immediate v_stmt into v_date;
dbms_output.put_line('Today date is:'|| v_date);
end;
/

OUTPUT:-

Department of Computer Science & Engineering 60


DATA BASE MANAGEMENT SYSTEM LAB

Pl/sql block for cursors:

declare
Total number;
Average number;
cursor c is select * from Student;
s Student %ROWTYPE;
begin
open c;
dbms_output.put_line('Name Sno CD DBMS OS Total Average Grade');
loop
fetch c into s;
Total:=s.CD+s.DBMS+s.OS;
Average:=floor(Total/3);
if(c % notfound)then
exit;
else
if(s.CD=90 and Average<=100)then
dbms_output.put_line(s.Name||' '||s.Sno||' '||s.CD||' '||s.DBMS||' '||s.OS|| ' '||Total||' '||Average||' '||'S');
elsif(Average>=80 and Average=70 and Average<90)then
dbms_output.put_line(s.Name||' '||s.Sno||' '||s.CD||' '||s.DBMS||' '||s.OS|| ' '||Total||' '||Average||' '||'A+');
elsif(Average>=70 and Average<80) then
dbms_output.put_line(s.Name||' '||s.Sno||' '||s.CD||' '||s.DBMS||' '||s.OS|| ' '||Total||' '||Average||' '||'B');
elsif(Average>=60 and Average<70) then
dbms_output.put_line(s.Name||' '||s.Sno||' '||s.CD||' '||s.DBMS||' '||s.OS|| ' '||Total||' '||Average||' '||'C');
else
dbms_output.put_line(s.Name||' '||s.Sno||' '||s.CD||' '||s.DBMS||' '||s.OS|| ' '||Total||' '||Average||' '||'D');
end if;
end if;
end loop;
close c;
end;
/
OUTPUT:-

Department of Computer Science & Engineering 61


DATA BASE MANAGEMENT SYSTEM LAB

Pl/sql block for exception:

DECLARE
S_id Student.Sno%type := 506;
S_name Student.Name%type;
S_DBMS Student.DBMS%type;
BEGIN
SELECT Name,DBMS INTO S_name, S_DBMS FROM Student WHERE Sno = S_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| S_name);
DBMS_OUTPUT.PUT_LINE ('DBMS: ' || S_dbms);

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

OUTPUT:-

Department of Computer Science & Engineering 62


DATA BASE MANAGEMENT SYSTEM LAB

pl/sql block for composit data types:

declare
type Student_list is table of Student.Sno%type;
Students Student_list;
Student_name Student.Name%type;
Student_id Student.Sno%type;
begin
Students := Student_list(501,503,505);
for i in Students.first .. Students.last loop
select Name,Sno into Student_name,Student_id from Student where
Student.Sno=Students(i);
DBMS_OUTPUT.PUT_LINE (TO_CHAR(Students(i)) || ': ' || Student_name || ', '
|| Student_id );
END LOOP;
END;
/

OUTPUT:-

Department of Computer Science & Engineering 63


DATA BASE MANAGEMENT SYSTEM LAB

Write a PL/SQL block using SQL and Control Structures in PL/SQL.

CONDITIONAL CONTROL STATEMNETS

In PL/SQL there are three types of conditional control : IF, ELSIF and CASE

IF – THEN Statement:

This is the most basic kind of a conditional control and has the following structure.

If Condition Then
Statement 1;
…. Statement 2;
End If;
The reserved word IF marks the beginning of the IF statement.

Example:

Write a PL/SQL block to swap two numbers when the first number is greater than second
number ?

SQL> declare
a number(10) := &a;
b number(10) := &b;
c number(10);
begin
dbms_output.put_line('a value ='||a||' b value ='||b);
if a>b then
c := a;
a := b;
b := c;
end if;
dbms_output.put_line('a value ='||a||' b value ='||b);
end;
/
OUTPUT:-

Department of Computer Science & Engineering 64


DATA BASE MANAGEMENT SYSTEM LAB

IF – THEN – ELSE:

This statement enables you to specify two groups of statements One group of statements
is executed when the condition evaluates to TRUE and the other group of statements is executed
when the condition evaluates to FALSE.

If Condition Then
Statement 1;
ELSE
Statement 2;
End If;
Statement 3;
Example:

Q) Write a PL/SQL block to test whether the given number is odd or even.

SQL> declare
a number(10) := &a;
begin
if mod(a,2)=0 then
dbms_output.put_line('a value is even');
else
dbms_output.put_line('a value is odd');
end if;
end;
/

OUTPUT:-

Department of Computer Science & Engineering 65


DATA BASE MANAGEMENT SYSTEM LAB

ELSIF Statement:

This statement has the following structure

If Condition 1 Then
Statement 1;
ELSIF Condition 2 Then
Statement 2;
ELSIF Condition 3 Then
Statement 3;

ELSE
Statement 4;
END IF;
Example:

Q) Write a PL/SQL block to find the grade of sailor for a given sid
10, 9, 8 – Grade A
7, 6, 5 – Grade B
other – Grade C.

SQL> declare
a number(10) := &a;
c number(10);
begin
select Rating into c from Sailors where Sid = a;
if c in (10,9,8) then
dbms_output.put_line('Sailor '||a||' has grade A');
elsif c in (7,6,5) then
dbms_output.put_line('Sailor '||a||' has grade B');
else
dbms_output.put_line('Sailor '||a||' has grade C');
end if;
end;
/

OUTPUT:-

Department of Computer Science & Engineering 66


DATA BASE MANAGEMENT SYSTEM LAB

CASE:
A case statement has the following structure:

CASE SELECTOR
WHEN EXPRESSION 1 STATEMENT 1;
WHEN EXPRESSION 1 STATEMENT 1;
…..
WHEN EXPRESSION 1 STATEMENT 1;
ELSE STATEMENT N+1;
END CASE;

The reserved word CASE marks the beginning of the case statement. A selector is a
value that determines which WHEN clause should be executed.

Example:
Q)Write a PL/SQL block to print the day name for a given date?

SQL> declare
a date := '&a';
b char(10);
begin
b := to_char(a,'D');
case b
when '1' then
dbms_output.put_line('today is sunday');
when '2' then
dbms_output.put_line('today is monday');
when '3' then
dbms_output.put_line('today is thuesday');
when '4' then
dbms_output.put_line('today is wednesday');
when '5' then
dbms_output.put_line('today is thrusday');
when '6' then
dbms_output.put_line('today is friday');
when '7' then
dbms_output.put_line('today is saturday');
end case;
end;
/
OUTPUT:-

Department of Computer Science & Engineering 67


DATA BASE MANAGEMENT SYSTEM LAB

ITERATIVE CONTROL:

In PL/SQL there are three types of loops : Simple LOOP, WHILE loops and Numeric FOR loop
A simple loop, as you can see from its name, is the most basic kind of loop and has the
following structure:

LOOP
STATEMENT 1;
STATEMENT 2;
…….
STATEMENT N;
END LOOP;

The reserved word LOOP marks the beginning of the simple loop. Statement 1 through N are a
sequence of statements that is executed repeatedly.
EXIT statement causes a loop to terminate when exit condition evaluates to TRUE.
Note: here numbers are printed 1 to 6 because this loop acts as do-while so it executes the statements
and then check the condition next.

LOOP
STATEMENT 1;
STATEMENT 2;
EXIT WHEN CONDITION;
…….
STATEMENT N;
END LOOP;

Q)Write a PL/SQL block to print number from 1 to 5 using loop statements.

SQL> declare
a number :=0;
begin
loop
a := a+1;
dbms_output.put_line('a value'||a);
exit when a>5 ;
end loop;
end;
/
OUTPUT:-

Department of Computer Science & Engineering 68


DATA BASE MANAGEMENT SYSTEM LAB

WHILE LOOPS:

A while loop has the following structure

WHILE CONDITION LOOP


STATEMNET 1;
STATEMNET 2;
……
STATEMNET N;
End loop;
The reserved word WHILE marks the beginning of a loop construct. The word CONDITION is
the test condition of the loop that evaluates to TRUE or FALSE.

Example:

Q)Write a PL/SQL block to print number from 1 to 5 using while loop statements

SQL> declare
a number:=1;
begin
while a<5 loop
dbms_output.put_line('a value'||a);
a := a+1;
end loop;
end;
/

OUTPUT:-

Department of Computer Science & Engineering 69


DATA BASE MANAGEMENT SYSTEM LAB

Q)To write a PL/SQL block to find Sum of Digits of a given Number.

SQL> DECLARE
num number(5);
rem number(5);
sm number(5):=0;
num1 number(5);
BEGIN
num :=&num;
num1 :=num;
while(num>0) loop
rem :=mod(num,10);
sm :=sm+rem;
num :=num/10;
end loop;
dbms_output.put_line('SUM OF DIGITS OF '||num1||' IS: '||sm);
end;
/

OUTPUT:-

Department of Computer Science & Engineering 70


DATA BASE MANAGEMENT SYSTEM LAB

NUMERIC FOR LOOP:

A numeric FOR loop is called numeric because it requires an integer as its terminating value. Its
structure is as follows.

FOR loop_counter IN[REVERSE] Lower_limit..upper_limit LOOP


STATEMENT 1;
STATEMENT 2;
……
STATEMENT N;
END LOOP;
The reversed word FOR marks the beginning of a FOR loop construct. The variable
loop_counter is an implicitly defined index variable. There is no need to define the loop counter in the
declaration section. The values of the lower_limit and upper_limit are evaluated once for the iteration of
the loop.

Example:

Q)Write a PL/SQL block to print number in reverse from 1 to 5 using for loop statements

SQL> begin
for a in reverse 1..5 loop

Department of Computer Science & Engineering 71


DATA BASE MANAGEMENT SYSTEM LAB

dbms_output.put_line('a value'||a);
end loop;
end;
/

OUTPUT:-

Write a PL/SQL Code using Procedures, Functions, and Packages FORMS


PROCEDUREDS:

Modular code :

A PL/SQL module is any complete logical unit of work. There are four types of PL/SQL
modules:
1) anonymous blocks that are run with a text script( you have used until now),
2) Procedures,
3) Functions,
4) Packages.

There are two main benefits to using modular code: 1) it is more reusable and 2) it is
more manageable.

A procedure is a module performing one or more actions: it does not need to return any
value. The syntax for creating a procedure is

CREATE OR REPLACE PROCEDURE name


[(PARAMETER 1 {IN,OUT,INOUT} DATATYPE(SIZE),
PARAMETER 2 {IN,OUT,INOUT} DATATYPE(SIZE),….

Department of Computer Science & Engineering 72


DATA BASE MANAGEMENT SYSTEM LAB

PARAMETER N {IN,OUT,INOUT} DATATYPE(SIZE))]


AS
[local declaration]
BEGIN
Executable statements
[EXCEPTION
exception handler]
END [name];

Example:
Create a procedure to add two number and call the block with a PL/SQL block?

SQL> create or replace procedure sum(a in number,b in number)


is
c number := 1;
begin
c := a+b;
dbms_output.put_line('c value '||c);
end;
/
OUTPUT:-

Department of Computer Science & Engineering 73


DATA BASE MANAGEMENT SYSTEM LAB

SQL> declare
a number := &a;
b number := &b;
begin
sum(a,b);
end;
/

OUTPUT:-

FUNCTION:

The syntax for creating a function is as follows:

CREATE OR REPLACE FUNCTION name


[(PARAMETER 1 {IN,OUT,INOUT} DATATYPE(SIZE),
PARAMETER 2 {IN,OUT,INOUT} DATATYPE(SIZE),….
PARAMETER N {IN,OUT,INOUT} DATATYPE(SIZE))]
RETURN datatype
IS
[local declaration]
BEGIN
Executable statements
[EXCEPTION
exception handler]
END [name];

The function does not necessarily have any parameters, but it must have a RETURN value
declared in the header, and it must return values for all the varying possible execution streams.

Department of Computer Science & Engineering 74


DATA BASE MANAGEMENT SYSTEM LAB

Create a function to add two number and return the value to a PL/SQL block.

SQL> create or replace function f(a in number)


return number
as
b number;
begin
b:=10;
b:=a+b;
return b;
end;
/

OUTPUT:-

Department of Computer Science & Engineering 75


DATA BASE MANAGEMENT SYSTEM LAB

declare
a number:=10;
c number;
begin
c := f(a);
dbms_output.put_line('c value'||c);
end;
/

OUTPUT:-

PACKAGES:

We can use package as a method to bundle your functions and procedures, the first being that a
well designed package is a logical grouping of objects – such as functions, procedures, global variables
and cursors.

The package specification

This contains information about the contents of the package, but not the code for the procedures
or functions. It also contains declarations of global/public variables. Anything placed in the declarative
section of a Pl/SQL block may be coded in a package specification.

The package Body

Department of Computer Science & Engineering 76


DATA BASE MANAGEMENT SYSTEM LAB

The package body contains the actual executable code for the objects described in the package
specification. The package body contains code for all procedures and functions described in the
specification and may additionally contain code for objects not declared in the specification.

Referencing Package Elements

Use the following notation when calling packaged elements from outside of the package:
package_name.elements.

Example:
Create a package which contains a procedure and a function which will add two numbers?

Creating package:
SQL> create or replace package ex
as
procedure sum3(a in number,b in number);
function f1(a in number) return number;
end ex;
/

OUTPUT:-

Department of Computer Science & Engineering 77


DATA BASE MANAGEMENT SYSTEM LAB

Creating package body:


SQL>create or replace package body ex
as
procedure sum3(a in number,b in number)
is
c number;
begin
c := a+b;
dbms_output.put_line('c value'||c);
end;
function f1(a in number) return number
is
d number;
begin
d :=10;
d :=a+d;
return d;
end;
end ex;
/
OUTPUT:-

Executing package:

SQL>declare
a number := &a;
c number;
begin
c := ex.f1(a);
ex.sum3(a,20);
dbms_output.put_line('c value'||c);
end;
/

Department of Computer Science & Engineering 78


DATA BASE MANAGEMENT SYSTEM LAB

OUTPUT:-

Pl/sql block for exception:

DECLARE
S_id Student.Sno%type := 506;
S_name Student.Name%type;
S_DBMS Student.DBMS%type;
BEGIN
SELECT Name,DBMS INTO S_name, S_DBMS FROM Student WHERE Sno = S_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| S_name);
DBMS_OUTPUT.PUT_LINE ('DBMS: ' || S_dbms);

EXCEPTION

Department of Computer Science & Engineering 79


DATA BASE MANAGEMENT SYSTEM LAB

WHEN no_data_found THEN


dbms_output.put_line('No such STUDENT!');
END;
/

OUTPUT:-

pl/sql block for composit data types:

declare
type Student_list is table of Student.Sno%type;
Students Student_list;
Student_name Student.Name%type;
Student_id Student.Sno%type;
begin
Students := Student_list(501,503,505);
for i in Students.first .. Students.last loop

Department of Computer Science & Engineering 80


DATA BASE MANAGEMENT SYSTEM LAB

select Name,Sno into Student_name,Student_id from Student where


Student.Sno=Students(i);
DBMS_OUTPUT.PUT_LINE (TO_CHAR(Students(i)) || ': ' ||
Student_name || ', ' || Student_id );
END LOOP;
END;
/

OUTPUT:-

Department of Computer Science & Engineering 81

You might also like