dbms theory
TRANSCRIPT
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS i
INDEX
CONTENTS PAGE NO STRUCTURED QUERY LANGUAGE (SQL) 1
BASIC SQL OPERATION 2
OPERATORS IN SQL 11
FUNCTIONS IN SQL 13
Single-Row Functions 13
Group-Value Functions 19
SET OPERATORS 20
JOIN OPERATION 21
Inner join 21
Outer joins 21
SUBQUERIES 24
VIEWS 25
Creating a read only view 26
Dropping a VIEW 26
INTEGRITY CONSTRAINTS IN CREATE TABLE COMMAND 26
PL/SQL 28
Anonymous block 29
Named block 29
Features of PL/SQL 29
Structure of a PL/SQL block 29
Conditional Logic 32
Cursor 34
Ref Cursors 38
Varying Arrays 38
Named Program Units 40
PROCEDURES 40
Parameter modes 40
Calling a Procedure 41
Dropping procedure 41
FUNCTIONS 41
PACKAGES 42
Create package Syntax 42
Package specification 43
Package body 43
TRIGGERS 44
Types of Triggers 44
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS ii
Enabling and Disabling Triggers 45
Dropping Triggers 45
TABLESPACE 46
Creating tablespace 46
VISUAL BASIC 48
The Visual Basic Environment 48
Properties Window 49
The tool box 49
Data source name 50
Creating a dsn 50
Open DataBase Connectivity 51
SQL SOLVED PROBLEMS 52
PL/SQL SOLVED PROBLEMS 89
DATABASE CONNECTIVITY SOLVED PROBLEMS 107
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 1
INTRODUCTION
A database management system (DBMS) is a collection of interrelated data and a set
of programs to access those data .The primary goal of DBMS is to provide a way to
store and retrieve database information that is both convenient and efficient.
The DBMS a general purpose software system that facilitates the process of
i) defining,
ii) constructing and
iii) manipulating database for various application. NEED FOR DATABASE SYSTEMS
DBMS has been developed to overcome the disadvantages with the conventional
systems like file-processing system, viz.
1. Data redundancy and inconsistency
2. Difficulty in accessing data
3. Data isolation
4. Integrity problems
5. Atomicity problems
6. Concurrent-access anomalies
7. Security problems THE RELATIONAL DATABASE: A relational database uses tables to store information. DATABASE OBJECTS: A database object is anything defined and stored in a
database.
Some of the database objects are:-tables, views, indexes etc
TABLES: Table is the basic unit of data storage in a relational database management
system. Every table has a table name and a set of columns and rows in which the data
is stored. Each column is given a column name, a datatype or domain type and a
width.
STRUCTURED QUERY LANGUAGE (SQL)
SQL is the standard relational database language. It includes features for defining the
structure of the data, for modifying data in the database and for specifying security
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 2
constraints. DDL and DML form part of SQL. Data Definition Language (DDL) provides
commands for defining the relation schemas. Data Manipulation Language (DML)
includes commands to insert tuples , delete tuples, and modify tuples in the database.
SQL language has the following parts:
* Data Definition Language (DDL)
* Data Manipulation Language (DML)
* Transaction Control Language (TCL)
* Data Control Language (DCL)
BASIC SQL OPERATION
SQL statements can be grouped into four general categories: Data definition language
(DDL), Data manipulation language (DML), Transaction control language (TCL), Data
control language (DCL).
1. DATA DEFINITION LANGUAGE (DDL)
The overall design of a database is called the database schema. A database schema is
specified by a set of definitions that are expressed using a data definition language. It
is used for structuring the database.
We use the data definition language statements CREATE, ALTER, DROP, TRUNCATE to
create new objects, alter the structure of existing objects, completely remove objects
from system, or delete all rows permanently from the table leaving the structure of the
table.
DDL COMMANDS
1.1 CREATE TABLE COMMAND
While naming a table,
i) First letter should be an alphabet ii) Reserved words cannot be used to name a table
iii) Maximum length for a table name is 30 character
iv) Table name should also be unique
v) Underscore, numerals and letters are allowed but not blank space and
single quotes Syntax:
Create table<table name> (attribute-1 domaintype-1,
attribute-2 domaintype-2…..
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 3
attribute-n domaintype-n,
integrity_CONSTRAINT<constraint_name-
1><constraints>,
CONSTRAINT<constraint_name-2><constraints>,
……,
CONSTRAINT<constraint name n><constraints>);
Example:
Create table manager (mnane varchar2(15), eno int, mid varchar2(10) primary key); Output:
Table created
COMMAND FOR A TABLE FROM AN EXISTING TABLE
A new table is created with attributes whose domain type and contents are same as
the existing table’s.
Syntax:
Create table <new table name> (<attribute1….attribute n>) as select attribute-1,
attribute-2 … attribute-n from <existing table name>
Example-1:
Create table branch_new(branchname, branchno) as select bname,bno from
branch_exist;
Output:
Table created
Example-2:
Create table basset(bname,asset) as select bname,assetfrom branch ;
Output:
Table created
1.2. DESC COMMAND
Command to see the structure of a table
Syntax:
desc<table name>
Example:
desc branch;
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 4
Output:
Name Null? Type
-------------------- ------------ ---------------
BNAME CHAR(15)
BNO NOT NULL VARCHAR2(15)
MANAGER VARCHAR2(15)
ASSET NUMBER
1.3. ALTER TABLE COMMAND
Command for modifying the fields in a table
This command is used to
1. Add a new column
2. Change the width of a data type or the data type itself
3. Include or drop integrity constraints
Syntax: - to add a new field into a table
alter table<table name> add(attribute-1 domintype, attribute-2 domaintype
…attribute-n domaintype-n);
Example:
alter table branch add (city varchar(15), state char(15));
Output:
Table altered.
Syntax: - To modify the domain type
alter table<table name>modify(attribute newdomaintype1, attribute2
newdomaintype2)
Example:
alter table branch modify (state varchar(15),city char(15));
Output:
Table altered
Syntax: - to add integrity constraint
alter table add integrity constraint (attribute)
Example:
alter table add primary key (bno);
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 5
alter table add unique (name, manager);
Output:
Table altered
Syntax: - to drop integrity constraint
alter table<table name>drop integrity constraints;
Example:
alter table breanch drop primary key;
alter table branch drop unique (name,manager);
Output:
Table altered
1.4. DROP TABLE COMMAND
Command to delete the entire schema of the table (table with its content is deleted)
Syntax:
drop table<table name>;
Example:
drop table basset;
Output:
Table dropped.
1.5. TRUNCATE TABLE COMMAND
This command is to delete the records in the table, while retaining the structure of the
table.
Syntax:
truncate table <table name> ;
Example:
truncate table basset;
Output:
Table truncated
2. DATA MANIPULATION LANGUAGE (DML)
These commands are used to query and manipulate existing objects like tables.
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 6
DML commands are: INSERT, SELECT, UPDATE, DELETE
DML COMMANDS
2.1 INSERT STATEMENT - To insert values into a table
To insert a single record
Syntax:
Insert into <table name> (attribute-1,attribute-2,…attribute-n) values (value-1,value-
2,…value-n);
Example:
insert into branch (bname,bno,manager,asset) values (‘tvmbranch’,’b1’,’Smith’,1000);
Output:
1 row created.
Mass insertion
Syntax:
insert into <table name> (attribute-1,attribute-2,…,attribute-n) values(‘&attribute-
1’,’&attribute-2’,…..’&attribute-n’);
Example:
Insert into branch(bname,bno,manager) values (‘&bname’,’&bno’,’&manager’);
Output:
Enter value for name: klmbranch
Enter value for bno: b2
Enter value for manager: Jones
Old 1:insert into branch(bname,bno,manager)
Values(‘&bname’,’&bno’,’&manager’)
New 1:insert into branch(bname,bno,manager)
Values(‘klmbranch’,’b2’,’Jones’)
1 row created
2.2 SELECT STATEMENT
Select command is used to retrieve information stored in the table.
Syntax:
select <column name> from <table name>;
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 7
Example:
Select * from branch; // Select all the columns of the table
VARIATIONS OF SELECT STATEMENT
� To see the values of specific attributes
Syntax:
Select attribute-1,attribute-2,….attribute-n from<table name>;
Example:
Select bname,bno from branch;
� Selecting distinct rows
Command to list the tuples in a table without duplication
Syntax:
select distinct attribute-1,attribute-2,…..from<table name> where<condition>;
Example:
Select distinct bname from branch;
� Command to list the tuples in a table in a sorted order based on some
attributes
Syntax:
Select attribute-1,attribute-2,……attribute-n from<table name> order by attribute-1
asc;
Select attribute-1,attribute-2,……attribute-n from<table name> order by attribute-1
desc;
Example:
Select * from branch order by asset asc;
Select * from branch order by asset desc;
� Select command with ‘where’ clause
To select specific rows or records which satisfy some specific conditions, we can use
‘where’ clause in the select command.
Syntax:
select <attribute> from <table name> where <conditions>;
Example:
Select bname from branch where bno=123;
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 8
� Select command to create a table
User can include a ‘select’ clause in a create table command to create table and copy
the records into it.
Syntax:
create table <table name> as select <column names> from <existing table name>;
Example:
create table branch_new as select * from branch;
‘where’ clause can be included to create table with those records which satisfy the
‘where’ condition
Example:
create table branch_new as select * from branch where bno>200;
� Select command to insert records
This command either create a table or consider an existing table prior to insertion, with
the same structure as the other table and then performs the insertion command.
Syntax:
insert in to <table name> (select column_name from <existing table name>);
Example:
insert into branch select * from branch_usa;
insert into branch(branchname,branchno) select bname,bno from branch_usa;
2.3 UPDATE STATEMENT
command to modify the value of records in a table
Syntax:
update<table-name>set <change-value-of-attribute> where<condition>;
Example:
update brach set city=’tvm’ where bno=’b1’;
Output:
1 row updated
update comfort set midnight = (select temperature from weather where city =
'manchester') where city = 'walpole' and sampledate = to_date('22-dec-1999','dd-
mon-yyyy');
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 9
1 row updated.
2.4 DELETE STATEMENT
Command for deletion of rows
� Deletion of specified rows
Syntax:
Delete from<table name>where<condition>;
Example:
delete from branch1 where asset>2000;
Output:
0 rows deleted
� Deletion of entire rows
Syntax:
delete from<table name>;
Example:
Delete from branch1;
Output:
4 rows deleted
3. TRANSACTION CONTROL LANGUAGE (TCL)
The various commands in TCL are
� COMMIT
� SAVEPOINT
� ROLLBACK
3.1 COMMIT COMMAND
Transaction changes can be made permanent to the database by commit command.
Syntax:
commit work;
or
commit;
user can set auto commit option by using the command ‘set autocommit on’
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 10
3.2 SAVEPOINT COMMAND
These are markers to divide a very lengthy transaction into smaller ones. They are
used to identify a point in a transaction to which we can later roll back. This is used
along with roll back.
Syntax:
savepoint savepoint_id;
3.3 ROLLBACK
It is used to undo the work done in the current transaction. We can either rollback the
entire transaction or to a savepoint so that statements after the savepoint are rolled
back.
Syntax:
rollback work;
or
rollback;
Syntax to rollback to a particular stage in a transaction:
rollback to savepoint save_pt;
where save_pt is the savepoint.
4. DATA CONTROL LANGUAGE (DCL)
Data Control Language is used to manage user access to a database. DCL statements
such as GRANT, REVOKE control access to database and affirm or revoke database
transactions. It provides the user with privilege commands. The owner of the database
can grant privileges or withdraw (revoke) privilege to other database.
4.1 GRANT
An object privilege specifies what a user can do with a database object such as a table,
a sequence or a view. The privileges are granted using GRANT statement.
Syntax:
grant privileges on <object_name> to <username>;
Example:
grant select, update on branch to new_branch;
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 11
grant all on customers to ashraf; // Grants all permissions on the table customers to
the user who logs in as 'ashraf'.
grant select on customers to sunil; // Grants SELECT permission on the table
customers to the user 'sunil'. User 'sunil' does not have permission to insert, update,
delete or perform any other operation on customers table.
grant select on customers to sunil with grant option; // Enables user 'sunil' to give
SELECT permission on customers table to other users
4.2 REVOKE
The privileges, once granted, can be taken away. REVOKE statement takes privileges
not only from the grantee but also from users who are granted privileges by the
grantee.
Syntax:
revoke privileges on <object_name> from <username>;
Example:
revoke select, update on branch from mca;
revoke delete on customers from ashraf
OPERATORS IN SQL
The operators supported by SQL are
1. Arithmetic operators
2. Comparison operators
3. Logical operators
4. Pattern matching operators 1. Arithmetic operators
The various arithmetic operators are
Function Definition
value1 + value2 Addition
value1 - value2 Subtraction
value1 * value2 Multiplication
value1 / value2 Division
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 12
Example:
select * from pnum;
NAME NO1 NO2
---------- ---------- ----------
os 60 70
nm 70 40
ds 60 90
select name, no1 + no2 as Additon, no1 - no2 as Substraction, no1 / no2 as Division,
no1 * no2 as Multiplication from pnum;
Output:
NAME ADDITON SUBSTRACTION DIVISION MULTIPLICATION
---------- ---------- ------------------ -------------- -------------------
os 130 -10 .857142857 4200
nm 110 30 1.75 2800
ds 150 -30 .666666667 5400
2. Comparison operators
The various comparison operators are:
=, !=, <, >, <=, >=,
between ( to check between any two values)
in (to match with any of the values in the list) //not in – opposite of the in function
result.
like (to match a character pattern)
is null (to check whether it is Null) // is not null - opposite of the is null function
result.
Example:
Select bname from branch where bno > 100;
Select bname from branch where bno is null;
3. Logical Operators
These are used to combine the results of two conditions to produce a single result. The
logical operators are:
AND, NOT, OR
Example:
select regno from car where colour = 'blue' and regno = 1230
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 13
4. Pattern matching operators
Pattern matching operators are like, %, _ (under score)
LIKE is useful for slightly more complex queries, in which a non-exact match is
required. it can be used to select data in which the column entry matches a pattern
containing the wildcards % or _
� % matches 1 or more characters of any type � _ matches any single character
Example:
Select bname,asset from branch where bname like ‘tv%’;
Select bname from branch where bname like ‘tv_%’;
FUNCTIONS IN SQL
These are built-in functions for performing operations using the Data Manipulation
commands.
Single-Row Functions
Single-row functions return a single result row for every row of a queried table or view.
These functions can appear in select lists, WHERE clauses, START WITH and CONNECT
BY clauses, and HAVING clauses.
Group Functions (Aggregate functions)
Group Functions Returns a result based on a group of rows.
Single-Row functions
1. Numeric function
2. Character function
3. Date function
4. Conversion function
1. Numeric Functions
Numeric functions accept numeric input and return numeric values. Most numeric
functions that return NUMBER values that are accurate to 38 decimal digits.
Function Definition
ABS(value) ABSolute value
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 14
ACOS(value) Arc COSine of value, in radians
ASIN(value) Arc SINe of value, in radians
ATAN(value) Arc TANgent of value, in radians
CEIL(value) Numeric CEILing: the smallest integer larger than
or equal to value
COS(value) COSine of value
COSH(value) Hyperbolic COSine of value
EXP(value) e raised to value EXPonent
FLOOR(value) Largest integer smaller than or equal to value
LN(value) Natural Logarithm of value
LOG(value) Base 10 LOGarithm of value
MOD(value, divisor) MODulus
NVL(value, substitute) substitute for value if value is NULL
POWER(value, exponent) value raised to an exponent POWER
ROUND(value, precision) ROUNDing of value to precision
SIGN(value) 1 if value is positive, –1 if negative, 0 if zero
SIN(value) SINe of value
SINH(value) Hyperbolic SINe of value
Example:
select * from emp;
ENO SAL COMM
---------- ---------- ----------
101 4000 2.2
102 8000 1.76
select sal + nvl(comm,0) from emp;
SAL+NVL(COMM,0)
---------------------
4002.2
8001.76
8000
0
select abs(-123) from dual;
ABS(-123)
------------
123
select ceil(1.9),ceil(2),ceil(1.3),floor(1.4),floor(1.9),floor(2) from dual;
CEIL(1.9) CEIL(2) CEIL(1.3) FLOOR(1.4) FLOOR(1.9) FLOOR(2)
---------- --------- ---------- ------------- ------------- -----------
2 2 2 1 1 2
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 15
SQL> select mod(6,5),mode(6,2) from dual;
MOD(6,5) MOD(6,2)
---------- ----------
1 0
select power(3,2),sqrt(64),round(1.2),round(1.9) from dual;
POWER(3,2) SQRT(64) ROUND(1.2) ROUND(1.9)
------------- ---------- -------------- --------------
9 8 1 2
2. Character Functions
These are functions operated on characters. Input will be character and output will be
either character or number values. Character functions that return character values
return values of the same datatype as the input argument. The length of the value
returned by the function is limited by the maximum length of the datatype returned.
Function Name Use
|| Glues or concatenates two strings together. The | symbol is called
a vertical bar or pipe.
CONCAT CONCATenates two strings together (same as | |).
INITCAP INITial CAPital. Capitalizes the first letter of a word or series of
words.
INSTR Finds the location of a character IN a STRing.
LENGTH Tells the LENGTH of a string.
LOWER Converts every letter in a string to LOWERcase.
LPAD Left PAD. Makes a string a certain length by adding a certain set
of characters to the left.
RPAD Right PAD. Makes a string a certain length by adding a certain set
of characters to the right.
RTRIM Right TRIM. Trims all the occurrences of any one of a set of
characters off of the right side of a string.
SOUNDEX Finds words that SOUND like the EXample specified.
SUBSTR SUBSTRing. Clips out a piece of a string.
UPPER Converts every letter in a string into UPPERcase.
Examples
select * from location;
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 16
CITY COUNTRY
--------------- -----------
athens greece
trivandrum inda
southwales Australia
select upper(city),initcap(country),length(city),city||country from location;
UPPER(CITY) INITCAP(COUNTRY) LENGTH(CITY) CITY||COUNTRY
--------------- ---------------------- ---------------- -----------------------
ATHENS Greece 6 athensgreece
TRIVANDRUM Inda 10 trivandruminda
SOUTHWALES Australia 10 southwalesaustralia
select lower(city) from location;
LOWER(CITY)
---------------
athens
trivandrum
southwales
select concat(city,country) from location;
CONCAT(CITY,COUNTRY)
-----------------------------
athensgreece
trivandruminda
southwalesaustralia
select rpad(city,10,'*') from location;
RPAD(CITY,10,'*')
---------------------
athens****
trivandrum
southwales
select lpad(city,15,'*') from location;
LPAD(CITY,15,'*')
---------------------
*********athens
*****trivandrum
*****southwales
select substr(city,2,4) from location;
SUBSTR(CITY,2,4)
---------------------
then
riva
outh
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 17
select city,instr(city,'t') from location;
CITY INSTR(CITY,'T')
--------------- ------------------
athens 2
trivandrum 1
southwales 4
select * from location where soundex(city)=soundex('athans');
CITY COUNTRY
--------------- ---------------
athens Greece
soundex – has the unusual ability to find words that sound like other
3. Date Functions
Date functions operate on date (DATE), and interval (INTERVAL YEAR TO MONTH)
values.
Function Use
ADD_MONTHS(date,count) Adds count months to date.
GREATEST(date1,date2,date3,...) Picks latest date from list of dates.
LEAST(date1,date2,date3,...) Picks earliest date from list of dates.
LAST_DAY(date) Gives date of last day of month that date is
in.
MONTHS_BETWEEN(date2,date1) Gives date2−date1 in months
(can be fractional months).
NEXT_DAY(date,’day’) Gives date of next day after date, where
‘day’is ‘Monday’, ‘Tuesday’, and so on.
Example:
select add_months(sysdate,3) from dual;
ADD_MONTH
--------------
27-JUL-08
select sysdate,last_day(sysdate) "last",last_day(sysdate) - sysdate "days left" from
dual;
SYSDATE Last Days Left
------------- ------------- ----------
30-MAY-01 31-MAY-01 1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 18
select next_day('02-feb-2001','tuesday') "next day" from dual;
NEXT DAY
-----------
06-FEB-2001
select months_between (t_date,n_date ) from ex;
select greatest('10-mar-2008','2-apr-2008') from dual;
GREATEST('
--------------
2-apr-2008
SQL> select least('10-mar-2008','2-apr-2008') from dual;
LEAST('10-M
---------------
10-mar-2008
Note: SYSDATE
SYSDATE returns the current date and time set for the operating system on which the
database resides.
select sysdate from dual;
SYSDATE
-----------
27-APR-08
4. Conversion Functions
Conversion functions convert a value from one datatype to another. Generally, the
form of the function names follows the convention datatype TO datatype. The first
datatype is the input datatype. The second datatype is the output datatype.
The SQL conversion functions are:
Function Use
TO_CHAR transforms a DATE or NUMBER into a character string.
TO_DATE transforms a NUMBER, CHAR, or VARCHAR2 into a DATE.
TO_NUMBER transforms a CHAR or VARCHAR2 into a NUMBER.
Example:
select to_char(sysdate,'yy>>MM>>dd') from dual;
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 19
TO_CHAR(SY
---------------
08>>03>>07
select to_char(sysdate,'dd month year') from dual;
TO_CHAR(SYSDATE,'DDMONTHYEAR')
-------------------------------------------
07 march two thousand eight
select to_date('01032008','mm dd yyyy') from dual;
TO_DATE('
------------
03-JAN-08
Group-Value Functions
Group value functions return a single result row based on groups of rows, rather than
on single rows. Group-Value functions can appear in select lists and in ORDER BY and
HAVING clauses. They are commonly used with the GROUP BY clause in a SELECT
statement.
Function Definition
AVG(value) Average of value for group of rows
COUNT(value) COUNT of rows for column
GROUPING(expression) Used in conjunction with ROLLUP and CUBE functions to
detect NULLs
MAX(value) MAXimum of all values for group of rows
MIN(value) MINimum of all values for group of rows
STDDEV(value) STanDard DEViation of all values for group of rows
SUM(value) SUM of all values for group of rows
VARIANCE(value) VARIANCE of all values for group of rows
Example:
select avg(salary) from employees;
select min(salary) from employees;
select max(salary) from employees;
select sum(salary) from employees;
select count(name) from employees;
select count(*) from emp;
select count(empno) from emp;
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 20
Count(distinct attribute) – count all rows except null valued rows but eliminates
duplicates while counting.
select count(distinct empno) from emp;
Group By
GROUP BY is used in conjunction with aggregating functions to group the results by the
unaggregated columns.
Example:
select deptno,sum(sal) from emp group by deptno;
DEPTNO SUM(SAL)
----------- ---------------
1 11000
2 5000
select deptno,sum(sal) from emp group by deptno order by deptno desc;
DEPTNO SUM(SAL)
------------ ---------------
2 5000
1 11000
Group By With Having
HAVING is used to perform an action on groups created by GROUP BY similar to that of
the WHERE clause on rows in a basic SQL statement. The WHERE clause limits the
rows evaluated. The HAVING clause limits the grouped rows returned.
Example:
select deptno,sum(sal) from emp group by deptno having sum(sal) > 9000;
DEPTNO SUM(SAL)
---------- -----------
1 11000
SET OPERATORS
The four set operators union, union all, intersects and minus allows to serially combine
more than one select statements. Although more than one select statement will then
be present, only one result set is then returned.
Operators Use
union all selects all rows from all select statements
union union all is very similar to union, however, it dismisses duplicate
rows found across different select statements
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 21
intersect returns the rows that are found in all select statements
minus minus returns all rows from the first select statements except
those who are duplicated in a following select statement
Example:
Select ename, empno from emp Union all Select mname, eno from manager;
Select ename,empno from emp Union Select mname,eno from manager;
Select ename,empno from emp Intersect Select mname,eno from manager;
Select ename,empno from emp Minus Select mname,eno from manager;
JOIN OPERATION
An SQL JOIN clause combines records from two tables in a relational database,
resulting in a new, temporary table, sometimes called a "joined table".
Inner join
� Equi-join
� Natural join
� Cross join
Outer joins
� Left outer join
� Right outer join
� Full outer join
An inner join requires each record in the two joined tables to have a matching record.
An inner join essentially combines the records from two tables (A and B) based on a
given join-predicate.
Example of an explicit inner join
select * from employee inner join department on employee.departmentid =
department.departmentid
Example of an implicit inner join
select * from employee, department where employee.departmentid =
department.departmentid
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 22
Types of inner joins
Equi-join
An equi-join is a specific type of comparator-based join, or theta join, that uses only
equality comparisons in the join-predicate. Using other comparison operators (such as
<) disqualifies a join as an equi-join.
The query shown above has already provided an example of an equi-join
select * from employee inner join department on employee.departmentid =
department.departmentid
Natural join
A natural join offers a further specialization of equi-joins. The join predicate arises
implicitly by comparing all columns in both tables that have the same column-name in
the joined tables. The resulting joined table contains only one column for each pair of
equally-named columns.
The above sample query for inner joins can be expressed as a natural join in the
following way:
select * from employee natural join department
Cross join
A cross join, cartesian join or product provides the foundation upon which all types
of inner joins operate. A cross join returns the cartesian product of the sets of records
from the two joined tables. Thus, it equates to an inner join where the join-condition
always evaluates to True or join-condition is absent in statement.
If A and B are two sets, then cross join = A × B.
Example of an explicit cross join
select * from employee cross join department
Example of an implicit cross join:
select * from employee, department;
Outer joins
An outer join does not require each record in the two joined tables to have a matching
record. The joined table retains each record—even if no other matching record exists.
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 23
Outer joins subdivide further into left outer joins, right outer joins, and full outer joins,
depending on which table(s) one retains the rows from (left, right, or both).
Left outer join
The result of a left outer join for tables A and B always contains all records of the
"left" table (A), even if the join-condition does not find any matching record in the
"right" table (B). This means that if the ON clause matches 0 (zero) records in B, the
join will still return a row in the result—but with NULL in each column from B. This
means that a left outer join returns all the values from the left table, plus matched
values from the right table (or NULL in case of no matching join predicate).
Example:
select * from employee left outer join department on employee.departmentid =
department.departmentid
Right outer join
A right outer join closely resembles a left outer join, except with the tables reversed.
Every record from the "right" table (B) will appear in the joined table at least once. If
no matching row from the "left" table (A) exists, NULL will appear in columns from A
for those records that have no match in A.
A right outer join returns all the values from the right table and matched values from
the left table (NULL in case of no matching join predicate).
Example:
select * from employee right outer join department on employee.departmentid =
department.departmentid
Full outer join
A full outer join combines the results of both left and right outer joins. The joined
table will contain all records from both tables, and fill in NULLs for missing matches on
either side.
Example:
select * from employee full outer join department on employee.departmentid =
department.departmentid
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 24
SUBQUERIES
Nesting of queries, one within another is termed as a subquery. Subqueries allow to
realize complex queries which would normally require several queries with storage of
the intermediate results.
Example: Determine the name, sex and age of the oldest student.
select nometu, cdsexe, ( current_date-dtnaiss)/365 as age from etudiant
where (current_date-dtnaiss) /365 = ( select max(( current_date-dtnaiss) /365) from
etudiant );
Predicates - IN, ANY, ALL, EXISTS
A subquery can return a subset of zero to n values. According to the conditions which
one wants to express, one can use the predicates IN, ANY, ALL or EXISTS.
Predicate Meaning
IN The comparison operatror is the equality and the logical
operation between values is OR.
ANY Allows to check if at least a value of the list satisfies condition.
ALL Allows to check if condition is realized for all the values of the list.
EXISTS If the subquery returns a result, the value returned is True otherwise the value returned is False.
Example: Display the marks of the student number 1 which are equal to the marks of
the student number 2.
select note from notes where numetu=1 and note in ( select note from notes where
numetu=2);
Example: Display the marks of the student number 1 which are greater than the
marks of the student number 2.
select note from notes where numetu=1 and note > any ( select note from notes
where numetu=2);
Example: Display the marks of the student number 1 which are lower than all the
marks of the student number 9.
select note from notes where numetu=1 and note < all ( select note from notes where
numetu=9);
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 25
Example: Display all information on the students who do not have any mark.
select * from etudiant e where not exists ( select numetu from notes where
numetu=e.numetu);
VIEWS
A view is a customized presentation of the data from one or more tables. Views derive
their data from tables on which they are based, which are known as base tables. All
operations performed on a view actually affect the base tables of the view.
Views can be used for several purposes:
� To give you an additional level of table security by restricting access to a
predetermined set of table rows and columns.
� To hide data complexity. Oracle 8 databases usually include many tables, and
by creating a view combining information from two or more tables,you make it
easier for other users to access information from your database.
� To present the data in a different perspective from that of the base table.Views
provide a means to rename columns without affecting the base table.
� To store complex queries.
Syntax:
create [or replace] view <view-name> [(<column(s)>)] as <select-statement> [with
check option [constraint <name>]][with read only];
Example:
create view DEPT20 (ENAME, JOB, ANNUAL SALARY) as select ENAME, JOB, SAL * 12
from EMP where DEPTNO = 20;
OUTPUT:
View created.
To list the view:
Select * from DEPT20;
ENAME JOB SALARY
------------ ------------- ----------
SMITH 111 2000
HAYES 123 7000
JOHNES 221 8000
TURNE 241 1000
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 26
Creating a read only view
To prevent modifications to the base tables via view, user can use with read only
clause of the create view command.
Create or replace view RAIN as select * from TROUBLE with read only;
Dropping a VIEW
Syntax:
drop view view_name;
example:
drop view rain;
INTEGRITY CONSTRAINTS IN CREATE TABLE COMMAND
A constraint is a rule that restricts the values for one or more columns in a table.
Constraints are of two types. Table constraints and Column constrains.
Some of the constraints are:
1. Primary key: It is the minimal combination of attribute in the table, which is used
to uniquely identify the rows of the table.
2. Foreign key: This is a key to join a table to another table. Foreign in a table is an
attribute, which is a primary key of another table. If an attribute A1 in table R1 is a
primary key in another table R2, the A1 is the Foreign key in R1 and A1 refers R2.
3. Unique: If some attribute (column) combination is said to be unique, then their
combination cannot have duplicate values in the table.
4. Not Null: If a column is assigned to be not null then it cannot have null values.
5. Check: This constraint is used to specify some condition for the columns.
6. Default: This constraint is used to specify a default value for a specific column.
Examples:
primary key
create table emp(empno number(3 ) primary key, ename varchar2(20));
create table emp(empno number(3),ename varchar2(20), primary key(empno));
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 27
NOT NULL
create table emp(empno number(3), ename vrchar2(15) not null);
unique
create table emp(empno number(3) unique,ename varchar(20))
create table emp (empno number(3),ename varchar(20),unique(empno)));
check
create table emp(empno number(3),sal number(8) check(sal>0), ename varchar(20));
create table emp5(empno number(3),sal number(8), ename
varchar(20),check(sal>0));
foreign key
cretate table maneger table(mname varchar(15), eno int references emp(empno),mid
varchar(10)primary key);
default
create table worker(wname varchar(15) default (‘not entered’), dob date,salary
numeric(6,2) default(3000));
USAGE OF CONSTRIANT keyword for implementing integrity constraints in a
CREATE TABLE command
Syntax:
Create table<table name>(<attribute-1 domain type-1,….attribute-n domain type-n,
CONSTRAINT<constaintname1>,constraints>,….CONSTRAINT<constraintname2><con
straints>, …CONSTRAINT<constaintnamren><constraints>);
Example:
Create table borrower(loanno varchar(10),amount number(10), CONSTRAINT chk1
check(amount>=0), CONSTRIAINT conpri primary key(loanno));
Note: Here the name of constraint is chk1
To remove the constraint chk1 command is:- alter table borrower drop constraint
chk1;
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 28
PL/SQL
(PROCEDURAL LANGUAGE/ STRUCTURED QUERY LANGUAGE)
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 29
PL/SQL stands for Procedural Language/SQL. PL/SQL is super set of the Structured
Query Language. Using PL/SQL user can do things like codify business rules through
the creation of stored procedures and packages, trigger database events to occur, or
add programming logic to the execution of SQL commands.
PL/SQL code is grouped into structures called blocks.
Anonymous block - If the block of PL/SQL code is not given a name then it is called
anonymous block.
Named block - block with a code with a name. Procedures and Functions are
examples.
Features of PL/SQL
� Block(modular) structures
� Flow-control statements and loops
� Variables, constants and types
� Structured data
� Customized error handling
� Allows to store compiled code directly in the database
PL/SQL datatypes include all of the valid SQL datatypes as well as complex datatypes
based on query structures.
A block of PL/SQL contains three sections (for anonymous PL/SQL block)
Section Description
Declarations Defines and initializes the variable and cursors used in the
block
Executable commands Uses flow-control commands (such as if commands and
loops) to execute the commands and assign values to the
declared variables
Exception Handling Provides customized handling of error conditions
Structure of a PL/SQL block
declare
<declarations section>
begin
<executable commands>
exception
<exception handling>
end;
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 30
Declarations Section
The Declarations section begins a PL/SQL block. The Declarations section starts with
the declare keyword, followed by a list of variable and cursor definitions.
User can define variables to have constant values, and variables can inherit datatypes
from existing columns and query results.
Example:
declare
pi constant NUMBER(9,7) := 3.1415926;
radius INTEGER(5);
area NUMBER(14,2);
begin
<executable commands>
end;
/
%TYPE and %ROWTYPE
Both %TYPE and %ROWTYPE are used to define variables in PL/SQL as it is defined
within the database. If the datatype or precision of a column changes, the program
automically picks up the new definition from the database without having to make any
code changes. The %TYPE and %ROWTYPE constructs allows programs to adapt as the
database changes to meet new business needs.
%TYPE
%TYPE is used to declare a field with the same type as that of a specified table's
column.
Example:
DECLARE
v_EmpName emp.ename%TYPE;
BEGIN
SELECT ename INTO v_EmpName FROM emp WHERE ROWNUM = 1;
DBMS_OUTPUT.PUT_LINE('Name = ' || v_EmpName);
END;
/
%ROWTYPE
%ROWTYPE is used to declare a record with the same types as found in the specified
database table, view or cursor. Examples:
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 31
DECLARE
v_emp emp%ROWTYPE;
BEGIN
v_emp.empno := 10;
v_emp.ename := 'JOY';
END;
/
Executable Commands Section
In the Executable Commands section, user can manipulate the variables and cursors
declared in the Declarations section of your PL/SQL block. The Executable Commands
section always starts with the keyword begin.
Example:
declare
pi constant NUMBER(9,7) := 3.1415926;
radius INTEGER(5);
area NUMBER(14,2);
begin
radius := 3;
area := pi*power(radius,2);
insert into AREAS values (radius, area);
end;
/
Exception Handling Section
When user-defined or system-related exceptions (errors) are encountered, the control
of the PL/SQL block shifts to the Exception Handling section. Within the Exception
Handling section, the when clause is used to evaluate which exception is to be
“raised”—that is, executed.
If an exception is raised within the Executable Commands section of your PL/SQL
block, the flow of commands immediately leaves the Executable Commands section
and searches the Exception Handling section for an exception matching the error
encountered. PL/SQL provides a set of system-defined exceptions and allows you to
add your own exceptions.
Every exception in PL/SQL has an error number and error message; some exceptions
also have names.
Declaring Exceptions
DECLARE
exception_name EXCEPTION;
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 32
User can associate an error number with a declared exception with the PRAGMA
EXCEPTION_INIT statement:
DECLARE
exception_name EXCEPTION;
PRAGMA EXCEPTION_INIT (exception_name, error_number);
where error_number is a literal value (variable references are not allowed). This
number can be an Oracle error, such as -1855, or an error in the user-definable -
20000 to -20999 range.
Raising Exceptions
An exception can be raised in three ways:
� By the PL/SQL runtime engine
� By an explicit RAISE statement in your code
� By a call to the built-in function RAISE_APPLICATION_ERROR
The syntax for the RAISE statement is:
RAISE exception_name;
Example:
Raise_application_error
It is used to create user defined error messages.
Syntax:
raise_application_error( error number, error message);
where , error number – between –20,000 and –20,999.
Error message – text associated with this error.
Example:
exception lo_bal then
raise_application_error(-20001, ‘ balance is low’);
--
end;
Conditional Logic
Within PL/SQL, user can use if, else, and elsif commands to control the flow of
commands within the Executable Commands section
Syntax:
if <some condition>
then <some command>
elsif <some condition>
then <some command>
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 33
else <some command>
end if;
Example:
if area >30
then
insert into AREAS values (rad_val.radius, area);
end if;
Loops
User can use loops to process multiple records within a single PL/SQL block. PL/SQL
supports three types of loops
Simple loops
A loop that keeps repeating until an exit or exit when statement is reached within the
loop. The loop is started by the loop keyword, and the exit when clause determines
when the loop should be exited. An end loop clause signals the end of the loop.
Example:
declare
pi constant NUMBER(9,7) := 3.1415926;
radius INTEGER(5);
area NUMBER(14,2);
begin
radius := 3;
loop
area := pi*power(radius,2);
insert into AREAS values (radius, area);
radius := radius+1;
exit when area >100;
end loop;
end;
/
FOR Loops
A loop that repeats a specified number of times. The FOR loop’s start is indicated by
the keyword for, followed by the criteria used to determine when the processing
should exit the loop. Since the number of times the loop is executed is set when the
loop is begun, an exit command isn’t needed within the loop.
Example:
declare
pi constant NUMBER(9,7) := 3.1415926;
radius INTEGER(5);
area NUMBER(14,2);
begin
for radius in 1..7 loop
area := pi*power(radius,2);
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 34
insert into AREAS values (radius, area);
end loop;
end;
/
WHILE Loops
In a WHILE loop, the loop is processed until an exit condition is met. Instead of
specifying the exit condition via an exit command within the loop, the exit condition is
specified in the while command that initiates the loop.
Example:
declare
pi constant NUMBER(9,7) := 3.1415926;
radius INTEGER(5);
area NUMBER(14,2);
begin
radius := 3;
while radius<=7
loop
area := pi*power(radius,2);
insert into AREAS values (radius, area);
radius := radius+1;
end loop;
end;
/
Cursor
A cursor is handle or pointer to the context area. The PL/SQL program can control the
context area by using the cursor. There can be either static cursors, whose SQL
statement is determined at compile time, or dynamic cursors, whose SQL statement is
determined at runtime.
Types of Cursors
PL/SQL uses two types of cursors: explicit and implicit
Explicit Cursors
Explicit cursors are SELECT statements that are DECLAREd explicitly in the declaration
section of the current block or in a package specification. Use OPEN, FETCH, and
CLOSE in the execution or exception sections of your programs.
Declaring explicit cursors
To use an explicit cursor, first declare it in the declaration section of a block or
package. There are three types of explicit cursor declarations:
A cursor without parameters
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 35
cursor company_cur is select company_id from company;
A cursor that accepts arguments through a parameter list
cursor company_cur (id_in in number) is select name from company where
company_id = id_in;
A cursor header that contains a RETURN clause in place of the SELECT statement:
cursor company_cur (id_in in number) return company%rowtype is select * from
company;
Opening explicit cursors
To open a cursor, use the following syntax:
OPEN cursor_name [(argument [,argument ...])];
where cursor_name is the name of the cursor as declared in the declaration section.
The arguments are required if the definition of the cursor contains a parameter list.
DECLARE
CURSOR c1 IS SELECT ename, job FROM employee WHERE sal < 7000;
...
BEGIN
OPEN c1;
...
END;
Fetching from explicit cursors
The FETCH statement places the contents of the current row into local variables. To
retrieve all rows in a result set, each row needs to be fetched.
The syntax for a FETCH statement is:
FETCH cursor_name INTO record_or_variable_list;
where cursor_name is the name of the cursor as declared and opened. Closing explicit
cursors
The syntax of the CLOSE statement is:
CLOSE cursor_name;
where cursor_name is the name of the cursor declared and opened.
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 36
Explicit cursor attributes
Attribute Description
%ISOPEN
TRUE if cursor is open. FALSE if cursor is not open.
%FOUND
Returns true if the last fetch returned a row else a false
%NOTFOUND
Returns true if the last fetch did not return a row else a false
%ROWCOUNT
The number of rows fetched from the cursor.
INVALID_CURSOR if cursor has been CLOSEd.
Example:
declare
pi constant NUMBER(9,7) := 3.1415926;
area NUMBER(14,2);
cursor rad_cursor is
select * from RADIUS_VALS;
rad_val rad_cursor%ROWTYPE;
begin
open rad_cursor;
loop
fetch rad_cursor into rad_val;
exit when rad_cursor%NOTFOUND;
area := pi*power(rad_val.radius,2);
insert into AREAS values (rad_val.radius, area);
end loop;
close rad_cursor;
end;
/
Implicit Cursors
Whenever a SQL statement is directly in the execution or exception section of a PL/SQL
block, you are working with implicit cursors. These statements include INSERT,
UPDATE, DELETE, and SELECT INTO statements. Unlike explicit cursors, implicit
cursors do not need to be declared, OPENed, FETCHed, or CLOSEd.
SELECT statements handle the %FOUND and %NOTFOUND attributes differently from
explicit cursors. When an implicit SELECT statement does not return any rows, PL/SQL
immediately raises the NO_DATA_FOUND exception and control passes to the
exception section. When an implicit SELECT returns more than one row, PL/SQL
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 37
immediately raises the TOO_MANY_ROWS exception and control passes to the
exception section.
implicit cursor attributes
Attribute Description
%ISOPEN
Always false as it is closed immediately after executing its
associated SQL statement
%FOUND
Returns true if the last DML statement returned a row else
a false
%NOTFOUND
Returns true if the last DML statement did not return any
row else a false
%ROWCOUNT
Returns the total number of rows returned.
cursor for loop
In a Cursor FOR loop, the results of a query are used to dynamically determine the
number of times the loop is executed. In a Cursor FOR loop, the opening, fetching, and
closing of cursors is performed implicitly.
Example:
declare
pi constant NUMBER(9,7) := 3.1415926;
area NUMBER(14,2);
cursor rad_cursor is
select * from RADIUS_VALS;
begin
for rad_val in rad_cursor
loop
area := pi*power(rad_val.radius,2);
insert into AREAS values (rad_val.radius, area);
end loop;
end;
/
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 38
Ref Cursors
To create cursor variables, you take two steps. First, you define a REF CURSOR type,
then declare cursor variables of that type. You can define REF CURSOR types in any
PL/SQL block, subprogram, or package using the syntax
TYPE ref_type_name IS REF CURSOR RETURN return_type;
Declaring Cursor Variables
Once you define a REF CURSOR type, you can declare cursor variables of that type in
any PL/SQL block or subprogram. In the following example, you declare the cursor
variable dept_cv:
DECLARE
TYPE DeptCurTyp IS REF CURSOR RETURN dept%ROWTYPE;
dept_cv DeptCurTyp; -- declare cursor variable
Opening a Cursor Variable
The OPEN-FOR statement associates a cursor variable with a multi-row query,
executes the query, and identifies the result set. Here is the syntax:
OPEN {cursor_variable_name | :host_cursor_variable_name}
FOR select_statement;
where host_cursor_variable_name identifies a cursor variable declared in a PL/SQL
host environment such as an OCI or Pro*C program.
Closing a Cursor Variable
The CLOSE statement disables a cursor variable. After that, the associated result set is
undefined. Here is the syntax:
CLOSE {cursor_variable_name | :host_cursor_variable_name);
Varying Arrays
A varying array allows you to store repeating attributes of a record in a single row.
Creating a Varying Array
SQL> create or replace type mark as varray(5) of number;
/
Type created.
SQL> create table varr(no number,marks mark);
Table created.
SQL> desc varr;
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 39
Name Null? Type
----------------------------------------- -------- -----------------
NO NUMBER
MARKS MARK
SQL> select * from varr;
NO
----------
MARKS
-------------------------
101
MARK(33, 44, 55, 66)
Example:
declare
cursor borrower_cursor is
select * from varr;
begin
for borrower_rec in borrower_cursor
loop
for i in 1..borrower_rec.marks.count
loop
dbms_output.put_line(borrower_rec.marks(i));
end loop;
end loop;
end;
/
33
44
55
66
PL/SQL procedure successfully completed.
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 40
Named Program Units
The PL/SQL programming language allows you to create a variety of named program
units they include:
Procedure - A program that executes one or more statements
Function - A program that returns a value
Package - A container for procedures, functions, and data structures
Triggers - Programs that execute in response to database changes
PROCEDURES
Procedures are program units that execute one or more statements and can receive or
return zero or more values through their parameter lists.
The syntax of a procedure is:
CREATE [OR REPLACE] PROCEDURE procedure_name
[ (parameter [,parameter]) ]
IS
[declaration_section]
BEGIN
executable_section
[EXCEPTION
exception_section]
END [procedure_name];
Example:
create procedure NEW_WORKER (Person_Name IN varchar2)
AS
BEGIN
insert into WORKER
(Name, Age, Lodging)
values
(Person_Name, null, null);
END;
/
In the above example the NEW_WORKER procedure will accept a person’s name as its
input. It can be called from any application. It inserts a record into the WORKER table,
with NULL values for the Age and Lodging columns.
Parameter modes
When you create a procedure or function, you may define parameters. There are three
types of parameters that can be declared:
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 41
IN The parameter can be referenced by the procedure or function. The
value of the parameter can not be overwritten by the procedure or
function.
OUT The parameter can not be referenced by the procedure or function, but
the value of the parameter can be overwritten by the procedure or
function.
IN OUT The parameter can be referenced by the procedure or function and the
value of the parameter can be overwritten by the procedure or function.
Calling a Procedure
A call to the procedure is made through an executable PL/SQL statement. The
procedure has the following syntax:
Procedure_Name [(parameters)];
The procedure can be executed from SQL environment with the execute command as
follows:
EXECUTE Procedure_Name [ (parameters) ];
Dropping procedure
To drop a procedure, use the drop procedure command, as follows:
drop procedure NEW_WORKER;
FUNCTIONS
Unlike procedures, functions can return a value to the caller (procedures cannot return
values). This value is returned through the use of the return keyword within the
function.
A function is characterized as follows:
• A function can be with one, more or no parameters.
• A function must have an explicit RETURN statement in the executable section to
return a value.
• The data type of the return value must be declared in the function’s header.
• A function cannot be executed as a standalone program.
The syntax for a function is:
CREATE [OR REPLACE] FUNCTION function_name
[ (parameter [,parameter]) ]
RETURN return_datatype
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 42
IS | AS
[declaration_section]
BEGIN
executable_section
[EXCEPTION
exception_section]
END [function_name];
Example:
create function BALANCE_CHECK (Person_Name IN varchar2)
RETURN NUMBER
IS
balance NUMBER(10,2);
BEGIN
select SUM(DECODE(Action,'BOUGHT',Amount,0))
- SUM(DECODE(Action,'SOLD',Amount,0))
INTO balance
from LEDGER
where Person = Person_Name;
RETURN(balance);
END;
/
Dropping function
To drop a function, use the drop function command, as follows:
drop function BALANCE_CHECK;
PACKAGES
A package is a database object, which is an encapsulation of related PL/SQL types,
subprograms, cursors, exceptions, variables and constants.
Packages have
package specification: PL/SQL types, subprograms, cursors, exceptions, variables
and constants are declared here.
package body: implements cursors, subprograms defined in package specification.
Note:
packages can not be called
we can not pass parameters to packages
nesting of packages is not possible
Create package Syntax
When creating packages, the package specification and the package body are created
separately. Thus, there are two commands to use: create package for the package
specification, and create package body for the package body.
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 43
Syntax for creating package specifications:
create [or replace] package [user.] package
{IS | AS}
[AUTHID {DEFINER | CURRENT_USER} ]
package specification;
A package specification consists of the list of functions, procedures, variables,
constants, cursors, and exceptions that will be available to users of the package.
creating package bodies is as follows:
create [or replace] package body [user.] package body
{IS | AS}
package body;
The name of the package body should be the same as the name of the package
specification.
Example:
Package specification:
create or replace package LEDGER_PACKAGE
AS
function BALANCE_CHECK(Person_Name VARCHAR2) return NUMBER;
procedure NEW_WORKER(Person_Name IN VARCHAR2);
end LEDGER_PACKAGE;
/
Package body:
create package body LEDGER_PACKAGE
AS
function BALANCE_CHECK (Person_Name IN varchar2)
RETURN NUMBER
IS
balance NUMBER(10,2);
BEGIN
select SUM(DECODE(Action,'BOUGHT',Amount,0)) -
SUM(DECODE(Action,'SOLD',Amount,0))
INTO balance from LEDGER where Person = Person_Name;
RETURN(balance);
EXCEPTION
WHEN NO_DATA_FOUND THEN
RAISE_APPLICATION_ERROR (-20100, 'No BOUGHT or SOLD entries for that Person.');
END BALANCE_CHECK;
procedure NEW_WORKER (Person_Name IN varchar2)
AS
BEGIN
insert into WORKER (Name, Age, Lodging) values (Person_Name, null, null);
END NEW_WORKER;
END LEDGER_PACKAGE;
/
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 44
Executing the function
execute LEDGER_PACKAGE.BALANCE_CHECK('ADAH TALBOT');
Dropping Packages
To drop a package, use the drop package command, as follows:
drop package LEDGER_PACKAGE;
TRIGGERS
Trigger defines an action the database should take when some database-related event
occurs. Triggers are executed by the database when specific types of data
manipulation commands are performed on specific tables. Such commands may
include inserts, updates, and deletes. Updates of specific columns may also be used
as triggering events.
Types of Triggers
A trigger’s type is defined by the type of triggering transaction and by the level at
which the trigger is executed.
Row-Level Triggers
Row-level triggers execute once for each row in a transaction.
Row-level triggers are created using the for each row clause in the create trigger
command.
Statement-Level Triggers
Statement-level triggers execute once for each transaction. Statement-level triggers
are the default type of trigger created via the create trigger command.
The general syntax of the trigger is:
Create [or replace] trigger Trigger_name
[Before / after] [Insert/update/delete]
On Table_name
[For each row]
[When condition]
Declare
Declaration statements
Begin
Executable statements
Exception
Exception handling statements
End;
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 45
The before and after keywords indicate whether the trigger should be executed
before or after the triggering transaction.
The delete, insert, and update keywords (the last of which may include a column
list) indicate the type of data manipulation that will constitute a triggering event. When
referring to the old and new values of columns, you can use the defaults (“old” and
“new”) or you can use the referencing clause to specify other names.
When the for each row clause is used, the trigger will be a row-level trigger;
otherwise, it will be a statement-level trigger.
The when clause is used to further restrict when the trigger is executed. The
restrictions enforced in the when clause may include checks of old and new data
values.
Example:
create trigger ledger_bef_upd_row
before update on LEDGER
for each row
when (new.Amount/old.Amount>1.1)
begin
insert into LEDGER_AUDIT values (:old.ActionDate, :old.Action, :old.Item,
:old.Quantity, :old.QuantityType, :old.Rate, :old.Amount, :old.Person);
end;
Enabling and Disabling Triggers
A trigger can be either enabled or disabled. By default, triggers are enabled To enable
a trigger, use the alter trigger command with the enable keyword
Syntax for disabling a trigger:
alter trigger <Trigger_name> disable;
Syntax for disabling all triggers:
alter table <Table_name> disable all triggers;
Syntax for enabling a disabled trigger:
alter table <Table_name> enable <Trigger_name>;
Syntax for enabling all the disabled triggers:
alter table <Table_name> enable all Triggers;
Dropping Triggers
Triggers may be dropped via the drop trigger command.
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 46
Syntax for dropping triggers:
Drop Trigger <Trigger_name>;
TABLESPACE
A tablespace is an area of disk consisting of one or more disk files. A tablespace can
contain many tables, indexes, or clusters. Because a tablespace has a fixed size, it can
get full as rows are added to its tables.
Creating tablespace
The create tablespace command allows one or more files to be assigned immediately to
the tablespace. It also specifies a default space for any tables created without an
explicit storage clause mentioned in the create table statement.
SQL> create tablespace TALBOT datafile '/oraclexe/oradata/talbot.dbf' size 5000k
default storage (initial 1M next 1M minextents 1 maxextents 100 pctincrease 0)
permanent;
Tablespace created.
The permanent keyword in the create tablespace command tells Oracle that you
will be storing permanent objects (such as tables) in the tablespace. If the tablespace
is only used for temporary segments, then you can specify the temporary keyword
instead. The default value is permanent.
The initial default extent is 1M bytes (not blocks) and the next (incremental) extent is
1M bytes.
minextents allows you to set aside additional extents beyond the first at the time a
table is created. These additional extents will not necessarily be contiguous (physically
adjacent) with the initial extent, or with each other, but the space will at least be
reserved.
maxextents is the limit of additional extents allowed. You can specify
maxextents unlimited, in which case there is no limit to the number of extents
allowed for the table or index.
pctincrease is a growth factor for extents. When set to a non-zero value, each
incremental extent will be the specified percentage larger than the one before it. This
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 47
has the effect of reducing the number of extents, and noncontiguous space, used by a
table that grows large. However, it causes the space allocated to the table to grow
exponentially. If the data volume in the table grows at a constant rate, you should set
pctincrease to 0.
SQL> create table emp(name varchar2(10),age number) tablespace talbot;
Table created.
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 48
VISUAL BASIC is a high level programming language which was evolved from the
earlier DOS version called BASIC. VISUAL BASIC is a VISUAL and events driven
Programming Language. In VISUAL BASIC, programming is done in a graphical
environment.
a VISUAL BASIC Program is made up of many subprograms, each has its own program
codes, and each can be executed independently and at the same time each can be
linked together in one way or another.
The Visual Basic Environment
The above diagram shows the development environment with all the important points
labeled. You can choose to start a new project, open an existing project or select a list
of recently opened programs.
A project is a collection of files that make up your application. There are various types
of applications we could create.
The Project explorer window gives you a tree-structured view of all the files inserted
into the application. The project explorer window displays forms, modules or other
separators which are supported by the visual basic like class'es and Advanced Modules.
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 49
Properties Window
By default, the properties window displays its properties alphabetically (with the
exception of the name value) when you click on the categorized button the window
changes to left picture.
The tool box
Example:
Vertical Scroll bar Horizontal Scroll bar
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 50
Data source name
A data source name (DSN) is a data structure that contains the information about a
specific database that an Open Database Connectivity (ODBC) driver needs in order to
connect to it. Included in the DSN, which resides either in the registry or as a separate
text file, is information such as the name, directory and driver of the database, and,
depending on the type of DSN, the ID and password of the user.
User and system DSNs are specific to a particular computer, and store DSN
information in the registry. A user DSN allows database access for a single user on a
single computer, and a system DSN for any user of a particular computer. A file DSN
contains the relevant information within a text file with a .DSN file extension, and can
be shared by users of different computers who have the same drivers installed.
Creating a dsn
Control panel -> Administrative tools -> Data Sources (ODBC)
Click add
Choose the driver ‘Oracle in XE’ (for Oracle 10g)
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 51
Give the data source name and click ok, as show in the above picture dsn ‘rvs’ will be
created.
Open DataBase Connectivity
Open DataBase Connectivity, a standard database access method developed by the
SQL Access group in 1992. The goal of ODBC is to make it possible to access any data
from any application, regardless of which database management system (DBMS) is
handling the data. ODBC manages this by inserting a middle layer, called a database
driver, between an application and the DBMS. The purpose of this layer is to translate
the application's data queries into commands that the DBMS understands.
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 52
SQL
SOLVED PROBLEMS
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 53
Exercise no 1
1. Write an SQL statement to create an employee table with following details:
a. empno number(4)
b. empname varchar2(30)
c. doj date
d. manager number(4)
e. salary number(7,2)
f. commission number(5,2)
g. deptnumber number(2)
2. Write an SQL statement to create a department with following details.
a. deptnumber number(2)
b. deptname varchar2(20)
c. location varchar2(20)
3. Write an SQL statement to insert records into employee table.
4. Insert two rows into employee table for all columns except manager and
commission.
1. Write an SQL statement to insert values into the department table dynamically
at runtime.
2. Write an SQL statement to copy all the values from already existing employee
table to new table.
3. Write an SQL statement to insert two records into the employee table by giving
null values for doj and deptnumber column.
4. Write an SQL statement to insert some records with doj varying 1st jan 1980 to
31st dec 2010
5. Write an SQL statement to insert 5 records with salary and commission column
Varying from 1500 to 15000 and 150 to 3000 respectively
6. Write an SQL statement to alter the employee table by adding a column ‘sex’
with datatype char(1).
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 54
Oueries and Outputs:
Ans Ans Ans Ans 1111 SQL> create table emp (
empno number(4), ename varchar2(30), doj date, mgrssn number(4), sal number(7,2), comm number(5,2), dno number(2) );
Table created. Ans Ans Ans Ans 2222 SQL> create table dept ( dno number(2), dname varchar2(15), loc varchar2(10) ); Table created. Ans Ans Ans Ans 3333 SQL> insert into emp values(1101,'Smith','1-jan-84','1120',14000,200,20); 1 row created. SQL> insert into emp values(1102,'john','10-march-95','1121',8000,100,15); 1 row created. SQL> insert into emp values(1120,'william','20-may-2005',1122,15000,500,10); 1 row created. Ans Ans Ans Ans 4444 SQL> insert into emp values('1122','james','20-july-1985',null,20000,null,10); 1 row created. SQL> insert into emp values('1121','johnson','20-july-1990',null,20000,null,20); 1 row created. Ans Ans Ans Ans 5555 SQL> insert into dept values(&dno,'&dname','&loc'); Enter value for dno: 20 Enter value for dname: research Enter value for loc: california
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 55
old 1: insert into dept values(&dno,'&dname','&loc'); new 1: insert into dept values(20,'research','california'); 1 row created. SQL> / Enter value for dno: 10 Enter value for dname: sales Enter value for loc: washington old 1: insert into dept values(&dno,'&dname','&loc'); new 1: insert into dept values(10,'sales','washington'); 1 row created. SQL> / Enter value for dno: 15 Enter value for dname: marketing Enter value for loc: newyork old 1: insert into dept values(&dno,'&dname','&loc'); new 1: insert into dept values(15,'marketing','newyork'); 1 row created. AnsAnsAnsAns 6666 SQL> create table newemp as (select * from emp); Table created. AnsAnsAnsAns 7777 SQL> insert into emp values(1126,'james',null,1121,10000,95,null); 1 row created. SQL> insert into emp values(1127,'zam dem',null,1122,10000,85,null); 1 row created. Ans 8Ans 8Ans 8Ans 8 SQL> insert into emp values(1129,'mone jo','20-april-85',1122,15000,500,10); 1 row created. SQL> insert into emp values(1130,'xelestina','20-april-95',1121,16000,200,15); 1 row created. Ans 9Ans 9Ans 9Ans 9 SQL> insert into emp values(&empno,'&ename','&date','&mgrssn',&sal,&comm,&dno); Enter value for empno: 1140 Enter value for ename: satheesh Enter value for date: 12-june-1999 Enter value for mgrssn: 1120 Enter value for sal: 2500 Enter value for comm: 150 Enter value for dno: 20 old 1: insert into emp values(&empno,'&ename','&date','&mgrssn',&sal,&comm,&dn o) new 1: insert into emp values(1140,'satheesh','12-june-1999' ,'1120',2500,150,20) 1 row created.
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 56
SQL> / Enter value for empno: 1141 Enter value for ename: santhosh Enter value for date: 12-march-2002 Enter value for mgrssn: 1120 Enter value for sal: 6000 Enter value for comm: 160 Enter value for dno: 20 old 1: insert into emp values(&empno,'&ename','&date','&mgrssn',&sal,&comm,&dn o) new 1: insert into emp values(1141,'santhosh','12-march-2002' ,'1120',6000,160,20) 1 row created. SQL> / Enter value for empno: 1142 Enter value for ename: jonathen Enter value for date: 12-april-1998 Enter value for mgrssn: 1120 Enter value for sal: 8000 Enter value for comm: 190 Enter value for dno: 20 old 1: insert into emp values(&empno,'&ename','&date','&mgrssn',&sal,&comm,&dn o) new 1: insert into emp values(1142,'jonathen','12-april-1998','1120',8000,190,20) 1 row created. SQL> / Enter value for empno: 1143 Enter value for ename: sam Enter value for date: 18-march-2007 Enter value for mgrssn: 1120 Enter value for sal: 8000 Enter value for comm: 200 Enter value for dno: 20 old 1: insert into emp values(&empno,'&ename','&date','&mgrssn',&sal,&comm,&dn o) new 1: insert into emp values(1143,'sam','18-march-2007', '1120',8000,200,20) 1 row created. SQL> / Enter value for empno: 1144 Enter value for ename: husain Enter value for date: 17-dec-2005 Enter value for mgrssn: 1120 Enter value for sal: 9000 Enter value for comm: 300 Enter value for dno: 20 old 1: insert into emp values(&empno,'&ename','&date','&mgrssn',&sal,&comm,&dn o) new 1: insert into emp values(1144,'husain','17-dec-2005', '1120',9000,300,20) 1 row created.
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 57
Ans 10Ans 10Ans 10Ans 10 SQL> alter table emp add sex char(1); Table altered. SQL> select * from emp; EMPNO ENAME DOJ MGRSSN SAL COMM DNO S ---------- ------------- --------- ---------- ---------- ---------- ---------- - 1101 Smith 01-JAN-84 1120 14000 200 20 1102 john 10-MAR-95 1121 8000 100 15 1120 william 20-MAY-05 1122 15000 500 10 1122 james 20-JUL-85 20000 10 1121 johnson 20-JUL-90 20000 20 1126 james 1121 10000 95 1127 zam dem 1122 10000 85 1129 mone jo 20-APR-85 1122 15000 500 10 1130 xelestina 20-APR-95 1121 16000 200 15 1140 satheesh 12-JUN-99 1120 2500 150 20 1141 santhosh 12-MAR-02 1120 6000 160 20 1142 jonathen 12-APR-98 1120 8000 190 20 1143 sam 18-MAR-07 1120 8000 200 20 1144 husain 17-DEC-05 1120 9000 300 20 14 rows selected.
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 58
Exercise no 2
1. Write an SQL statement to display all the records from an employee table
2. Write an SQL statement to display all the records from department table
3. Write an SQL statement to display empno,empname,salary,deptno from
employee table
4. Write an SQL statement to display deptno, deptname from department
table.
5. Write an SQL statement display the empname who are getting salary more
than 5000
6. Write an SQL statement to display the employees who are getting salary=0
7. Write an SQL statement to display the employee who are getting null
commission
8. Write an SQL statement to display employee whose name starts with ‘s’
9. Write an SQL statement to display employee details who are getting salary
between 5000 & 15000
10. Write an SQL statement to display employee who join organization
between 01-jan-1980 and 31-mar-2006.
11. Write an SQL statement to display employees who are getting commission
less than 1000 only.
12. Write an SQL statement to display the employee working in department
number 12 & 30.
13. Write an SQL statement to display employees working in all department
except deptno 20 and 30
14. Write an SQL statement to display employees who are getting salaries not
equal to 1000
15. Write an SQL statement to display the employee details who are getting
salary more than 1000(1000 inclusive).
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 59
Oueries and Outputs: Ans 1Ans 1Ans 1Ans 1 SQL> column ename format a12; SQL> select * from emp; EMPNO ENAME DOJ MGRSSN SAL COMM DNO S ---------- ------------ --------- ---------- ---------- ---------- ---------- - 1101 Smith 01-JAN-84 1120 14000 200 20 1102 john 10-MAR-95 1121 8000 100 15 1120 william 20-MAY-05 1122 15000 500 10 1122 james 20-JUL-85 20000 10 1121 johnson 20-JUL-90 20000 20 1126 james 1121 10000 95 1127 zam dem 1122 10000 85 1129 mone jo 20-APR-85 1122 15000 500 10 1130 xelestina 20-APR-95 1121 16000 200 15 1140 satheesh 12-JUN-99 1120 2500 150 20 1141 santhosh 12-MAR-02 1120 6000 160 20 EMPNO ENAME DOJ MGRSSN SAL COMM DNO S ---------- ------------ --------- ---------- ---------- ---------- ---------- - 1142 jonathen 12-APR-98 1120 8000 190 20 1143 sam 18-MAR-07 1120 8000 200 20 1144 husain 17-DEC-05 1120 9000 300 20 14 rows selected. Ans 2Ans 2Ans 2Ans 2 SQL> select * from dept; DNO DNAME LOC ---------- --------------- ---------- 20 research california 10 sales washington 15 marketing newyork Ans 3Ans 3Ans 3Ans 3 SQL> select empno,ename,sal,dno from emp; EMPNO ENAME SAL DNO ---------- ------------ ---------- ---------- 1101 Smith 14000 20 1102 john 8000 15
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 60
1120 william 15000 10 1122 james 20000 10 1121 johnson 20000 20 1126 james 10000 1127 zam dem 10000 1129 mone jo 15000 10 1130 xelestina 16000 15 1140 satheesh 2500 20 1141 santhosh 6000 20 EMPNO ENAME SAL DNO ---------- ------------ ---------- ---------- 1142 jonathen 8000 20 1143 sam 8000 20 1144 husain 9000 20 14 rows selected. Ans 4Ans 4Ans 4Ans 4 SQL> select dno,dname from dept; DNO DNAME ---------- --------------- 20 research 10 sales 15 marketing Ans 5Ans 5Ans 5Ans 5 SQL> select ename from emp where sal>5000; ENAME ------------ Smith john william james johnson james zam dem mone jo xelestina santhosh jonathen ENAME ------------ sam husain 13 rows selected. AnsAnsAnsAns 6666 SQL> select * from emp where sal=0; no rows selected AnsAnsAnsAns 7777 SQL> select * from emp where comm is null;
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 61
EMPNO ENAME DOJ MGRSSN SAL COMM DNO S ---------- ------------ --------- ---------- ---------- ---------- ---------- - 1122 james 20-JUL-85 20000 10 1121 johnson 20-JUL-90 20000 20 Ans Ans Ans Ans 8888 SQL> select * from emp where ename like 's%'; EMPNO ENAME DOJ MGRSSN SAL COMM DNO S ---------- ------------ --------- ---------- ---------- ---------- ---------- - 1140 satheesh 12-JUN-99 1120 2500 150 20 1141 santhosh 12-MAR-02 1120 6000 160 20 1143 sam 18-MAR-07 1120 8000 200 20 Ans Ans Ans Ans 9999 SQL> select * from emp where sal between 5000 and 15000; EMPNO ENAME DOJ MGRSSN SAL COMM DNO S ---------- ------------ --------- ---------- ---------- ---------- ---------- - 1101 Smith 01-JAN-84 1120 14000 200 20 1102 john 10-MAR-95 1121 8000 100 15 1120 william 20-MAY-05 1122 15000 500 10 1126 james 1121 10000 95 1127 zam dem 1122 10000 85 1129 mone jo 20-APR-85 1122 15000 500 10 1141 santhosh 12-MAR-02 1120 6000 160 20 1142 jonathen 12-APR-98 1120 8000 190 20 1143 sam 18-MAR-07 1120 8000 200 20 1144 husain 17-DEC-05 1120 9000 300 20 10 rows selected. Ans: 10Ans: 10Ans: 10Ans: 10 SQL> select ename from emp where doj between '01-jan-1980' and '31-march-2006'; ENAME ------------ Smith john william
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 62
james johnson mone jo xelestina satheesh santhosh jonathen husain 11 rows selected. Ans:Ans:Ans:Ans: 11111111 SQL> select * from emp where nvl(comm,0)<1000; EMPNO ENAME DOJ MGRSSN SAL COMM DNO S ---------- ------------ --------- ---------- ---------- ---------- ---------- - 1101 Smith 01-JAN-84 1120 14000 200 20 1102 john 10-MAR-95 1121 8000 100 15 1120 william 20-MAY-05 1122 15000 500 10 1122 james 20-JUL-85 20000 10 1121 johnson 20-JUL-90 20000 20 1126 james 1121 10000 95 1127 zam dem 1122 10000 85 1129 mone jo 20-APR-85 1122 15000 500 10 1130 xelestina 20-APR-95 1121 16000 200 15 1140 satheesh 12-JUN-99 1120 2500 150 20 1141 santhosh 12-MAR-02 1120 6000 160 20 EMPNO ENAME DOJ MGRSSN SAL COMM DNO S ---------- ------------ --------- ---------- ---------- ---------- ---------- - 1142 jonathen 12-APR-98 1120 8000 190 20 1143 sam 18-MAR-07 1120 8000 200 20 1144 husain 17-DEC-05 1120 9000 300 20 14 rows selected. Ans:Ans:Ans:Ans: 12121212 SQL> select * from emp where dno in(12,30); no rows selected Ans:Ans:Ans:Ans: 13131313 SQL> select * from emp where dno not in(20,30); EMPNO ENAME DOJ MGRSSN SAL COMM DNO S
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 63
---------- ------------ --------- ---------- ---------- ---------- ---------- - 1102 john 10-MAR-95 1121 8000 100 15 1120 william 20-MAY-05 1122 15000 500 10 1122 james 20-JUL-85 20000 10 1129 mone jo 20-APR-85 1122 15000 500 10 1130 xelestina 20-APR-95 1121 16000 200 15 Ans :14Ans :14Ans :14Ans :14 SQL> select * from emp where sal!=1000; EMPNO ENAME DOJ MGRSSN SAL COMM DNO S ---------- ------------ --------- ---------- ---------- ---------- ---------- - 1101 Smith 01-JAN-84 1120 14000 200 20 1102 john 10-MAR-95 1121 8000 100 15 1120 william 20-MAY-05 1122 15000 500 10 1122 james 20-JUL-85 20000 10 1121 johnson 20-JUL-90 20000 20 1126 james 1121 10000 95 1127 zam dem 1122 10000 85 1129 mone jo 20-APR-85 1122 15000 500 10 1130 xelestina 20-APR-95 1121 16000 200 15 1140 satheesh 12-JUN-99 1120 2500 150 20 1141 santhosh 12-MAR-02 1120 6000 160 20 EMPNO ENAME DOJ MGRSSN SAL COMM DNO S ---------- ------------ --------- ---------- ---------- ---------- ---------- - 1142 jonathen 12-APR-98 1120 8000 190 20 1143 sam 18-MAR-07 1120 8000 200 20 1144 husain 17-DEC-05 1120 9000 300 20 14 rows selected.
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 64
Ans :15Ans :15Ans :15Ans :15 SQL> select * from emp where sal>=1000; EMPNO ENAME DOJ MGRSSN SAL COMM DNO S ---------- ------------ --------- ---------- ---------- ---------- ---------- - 1101 Smith 01-JAN-84 1120 14000 200 20 1102 john 10-MAR-95 1121 8000 100 15 1120 william 20-MAY-05 1122 15000 500 10 1122 james 20-JUL-85 20000 10 1121 johnson 20-JUL-90 20000 20 1126 james 1121 10000 95 1127 zam dem 1122 10000 85 1129 mone jo 20-APR-85 1122 15000 500 10 1130 xelestina 20-APR-95 1121 16000 200 15 1140 satheesh 12-JUN-99 1120 2500 150 20 1141 santhosh 12-MAR-02 1120 6000 160 20 EMPNO ENAME DOJ MGRSSN SAL COMM DNO S ---------- ------------ --------- ---------- ---------- ---------- ---------- - 1142 jonathen 12-APR-98 1120 8000 190 20 1143 sam 18-MAR-07 1120 8000 200 20 1144 husain 17-DEC-05 1120 9000 300 20 14 rows selected.
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 65
Exercise no 3
1. Write an SQL statement to display the employee details who are working in
deptno 10 and 30, who are getting salary more than 3000
2. Write an SQL statement to display the employee details who are working in
deptno 10 and 30 or who are drawing salary more than 3000
3. Write an SQL statement to display the employee details who joined before 01-
jan-2000 and salary <5000
4. Write an SQL statement to display the employee whose names sounds like
‘zam’
5. Write an SQL statement to sort the employee details in an alphabetical order
name wise
6. Write an SQL statement to sort the employee name department wise and each
department alphabetical wise
7. Write an SQL statement to give the employee details in descending order of
employee names.
8. Write an SQL statement to give the employee details in ascending order of
department number wise and in each department descending order of salary
wise
9. Write an SQL statement to give the employee details and arrange them inorder
based on position.
10. Write an SQL statement to display empno, name, salary and deptno and display
the records in the ascending order based on position.
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 66
AnsAnsAnsAns:::: 1 1 1 1 SQL> select * from emp where dno in(10,30) and sal>3000; EMPNO ENAME DOJ MGRSSN SAL COMM DNO S ---------- ------------ --------- ---------- ---------- ---------- ---------- - 1120 william 20-MAY-05 1122 15000 500 10 1122 james 20-JUL-85 20000 10 1129 mone jo 20-APR-85 1122 15000 500 10 AnsAnsAnsAns:::: 2 2 2 2 SQL> select * from emp where dno in(10,30) or sal>3000; EMPNO ENAME DOJ MGRSSN SAL COMM DNO S ---------- ------------ --------- ---------- ---------- ---------- ---------- - 1101 Smith 01-JAN-84 1120 14000 200 20 1102 john 10-MAR-95 1121 8000 100 15 1120 william 20-MAY-05 1122 15000 500 10 1122 james 20-JUL-85 20000 10 1121 johnson 20-JUL-90 20000 20 1126 james 1121 10000 95 1127 zam dem 1122 10000 85 1129 mone jo 20-APR-85 1122 15000 500 10 1130 xelestina 20-APR-95 1121 16000 200 15 1141 santhosh 12-MAR-02 1120 6000 160 20 1142 jonathen 12-APR-98 1120 8000 190 20 EMPNO ENAME DOJ MGRSSN SAL COMM DNO S ---------- ------------ --------- ---------- ---------- ---------- ---------- - 1143 sam 18-MAR-07 1120 8000 200 20 1144 husain 17-DEC-05 1120 9000 300 20 13 rows selected. AnsAnsAnsAns:::: 3 3 3 3 SQL> select * from emp where doj < '1-jan-2000' and sal < 5000; EMPNO ENAME DOJ MGRSSN SAL COMM DNO S ---------- ------------ --------- ---------- ---------- ---------- ---------- - 1140 satheesh 12-JUN-99 1120 2500 150 20
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 67
AnsAnsAnsAns:::: 4 4 4 4 SQL> select * from emp where soundex(ename)=soundex('zam'); no rows selected SQL> select * from emp where soundex(ename)=soundex('sam'); EMPNO ENAME DOJ MGRSSN SAL COMM DNO S ---------- ------------ --------- ---------- ---------- ---------- ---------- - 1143 sam 18-MAR-07 1120 8000 200 20 AnsAnsAnsAns:::: 5 5 5 5 SQL> select * from emp order by ename asc; EMPNO ENAME DOJ MGRSSN SAL COMM DNO S ---------- ------------ --------- ---------- ---------- ---------- ---------- - 1101 Smith 01-JAN-84 1120 14000 200 20 1144 husain 17-DEC-05 1120 9000 300 20 1122 james 20-JUL-85 20000 10 1126 james 1121 10000 95 1102 john 10-MAR-95 1121 8000 100 15 1121 johnson 20-JUL-90 20000 20 1142 jonathen 12-APR-98 1120 8000 190 20 1129 mone jo 20-APR-85 1122 15000 500 10 1143 sam 18-MAR-07 1120 8000 200 20 1141 santhosh 12-MAR-02 1120 6000 160 20 1140 satheesh 12-JUN-99 1120 2500 150 20 EMPNO ENAME DOJ MGRSSN SAL COMM DNO S ---------- ------------ --------- ---------- ---------- ---------- ---------- - 1120 william 20-MAY-05 1122 15000 500 10 1130 xelestina 20-APR-95 1121 16000 200 15 1127 zam dem 1122 10000 85 14 rows selected. AnsAnsAnsAns:::: 6 6 6 6 SQL> select ename,dno from emp order by dno asc,ename asc; ENAME DNO ------------------------------ ---------- james 10 mone jo 10 william 10
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 68
john 15 xelestina 15 Smith 20 husain 20 johnson 20 jonathen 20 sam 20 santhosh 20 ENAME DNO ------------------------------ ---------- satheesh 20 james zam dem 14 rows selected. AnsAnsAnsAns:::: 7 7 7 7 SQL> select * from emp order by ename desc; EMPNO ENAME DOJ MGRSSN SAL COMM DNO S ---------- ------------ --------- ---------- ---------- ---------- ---------- - 1127 zam dem 1122 10000 85 1130 xelestina 20-APR-95 1121 16000 200 15 1120 william 20-MAY-05 1122 15000 500 10 1140 satheesh 12-JUN-99 1120 2500 150 20 1141 santhosh 12-MAR-02 1120 6000 160 20 1143 sam 18-MAR-07 1120 8000 200 20 1129 mone jo 20-APR-85 1122 15000 500 10 1142 jonathen 12-APR-98 1120 8000 190 20 1121 johnson 20-JUL-90 20000 20 1102 john 10-MAR-95 1121 8000 100 15 1126 james 1121 10000 95 EMPNO ENAME DOJ MGRSSN SAL COMM DNO S ---------- ------------ --------- ---------- ---------- ---------- ---------- - 1122 james 20-JUL-85 20000 10 1144 husain 17-DEC-05 1120 9000 300 20 1101 Smith 01-JAN-84 1120 14000 200 20 14 rows selected. AnsAnsAnsAns:::: 8 8 8 8 SQL> select * from emp order by dno asc, sal desc; EMPNO ENAME DOJ MGRSSN SAL COMM DNO S
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 69
---------- ------------ --------- ---------- ---------- ---------- ---------- - 1122 james 20-JUL-85 20000 10 1120 william 20-MAY-05 1122 15000 500 10 1129 mone jo 20-APR-85 1122 15000 500 10 1130 xelestina 20-APR-95 1121 16000 200 15 1102 john 10-MAR-95 1121 8000 100 15 1121 johnson 20-JUL-90 20000 20 1101 Smith 01-JAN-84 1120 14000 200 20 1144 husain 17-DEC-05 1120 9000 300 20 1142 jonathen 12-APR-98 1120 8000 190 20 1143 sam 18-MAR-07 1120 8000 200 20 1141 santhosh 12-MAR-02 1120 6000 160 20 EMPNO ENAME DOJ MGRSSN SAL COMM DNO S ---------- ------------ --------- ---------- ---------- ---------- ---------- - 1140 satheesh 12-JUN-99 1120 2500 150 20 1126 james 1121 10000 95 1127 zam dem 1122 10000 85 14 rows selected. AnsAnsAnsAns:::: 9 9 9 9 SQL> select * from emp order by sal desc,mgrssn desc; EMPNO ENAME DOJ MGRSSN SAL COMM DNO S ---------- ------------ --------- ---------- ---------- ---------- ---------- - 1122 james 20-JUL-85 20000 10 1121 johnson 20-JUL-90 20000 20 1130 xelestina 20-APR-95 1121 16000 200 15 1120 william 20-MAY-05 1122 15000 500 10 1129 mone jo 20-APR-85 1122 15000 500 10 1101 Smith 01-JAN-84 1120 14000 200 20 1127 zam dem 1122 10000 85 1126 james 1121 10000 95 1144 husain 17-DEC-05 1120 9000 300 20 1102 john 10-MAR-95 1121 8000 100 15 1142 jonathen 12-APR-98 1120 8000 190 20
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 70
EMPNO ENAME DOJ MGRSSN SAL COMM DNO S ---------- ------------ --------- ---------- ---------- ---------- ---------- - 1143 sam 18-MAR-07 1120 8000 200 20 1141 santhosh 12-MAR-02 1120 6000 160 20 1140 satheesh 12-JUN-99 1120 2500 150 20 14 rows selected. AnsAnsAnsAns:::: 10 10 10 10 SQL> select empno, ename, sal,dno from emp order by sal desc,mgrssn asc; EMPNO ENAME SAL DNO ---------- ------------ ---------- ---------- 1122 james 20000 10 1121 johnson 20000 20 1130 xelestina 16000 15 1120 william 15000 10 1129 mone jo 15000 10 1101 Smith 14000 20 1126 james 10000 1127 zam dem 10000 1144 husain 9000 20 1142 jonathen 8000 20 1143 sam 8000 20 EMPNO ENAME SAL DNO ---------- ------------ ---------- ---------- 1102 john 8000 15 1141 santhosh 6000 20 1140 satheesh 2500 20 14 rows selected.
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 71
Exercise no 4
1. Write an SQL statement to display empno, empname, salary and deptnumber
with appropriate headings.
2. Write an SQL statement to display empname, salary and commission without
any duplicates
3. Write an SQL statement to display empno, empname and total salary. Total
salary is calculated by adding salary and commission.
4. Write an SQL statement to display empno, name, their total salary and total
annual salary of all employees.
5. Write an SQL statement to display the empno, empname and their
experience. Experience is calculated based upon the ((todays date-doj)/12).
6. Write an SQL statement to display empno, empname, salary, 10% of salary,
50% of salary, 30% of commission, 110% of commission and commission of
all employees.
7. Write an SQL statement to display the empno, empname, total salary, 10% of
total salary, 50% of total salary of all the employees.
8. Write an SQL statement to display the employee details who is getting the
highest salary.
9. Write an SQL statement to display the employee details with lowest salary
10. Write an SQL statement to display empno and empname in 1st column and
total salary in another column.
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 72
Queries and Outputs: AnsAnsAnsAns:::: 1 1 1 1 SQL> select ename as employee_name,empno as dept_no,sal as payment, dno as depa rtment_no from emp; EMPLOYEE_NAME DEPT_NO PAYMENT DEPARTMENT_NO ------------------------------ ---------- ---------- ------------- Smith 1101 14000 20 john 1102 8000 15 william 1120 15000 10 james 1122 20000 10 johnson 1121 20000 20 james 1126 10000 zam dem 1127 10000 mone jo 1129 15000 10 xelestina 1130 16000 15 satheesh 1140 2500 20 santhosh 1141 6000 20 EMPLOYEE_NAME DEPT_NO PAYMENT DEPARTMENT_NO ------------------------------ ---------- ---------- ------------- jonathen 1142 8000 20 sam 1143 8000 20 husain 1144 9000 20 14 rows selected. AnsAnsAnsAns:::: 2 2 2 2 SQL> select distinct ename,sal,comm from emp; ENAME SAL COMM ------------ ---------- ---------- Smith 14000 200 james 20000 xelestina 16000 200 john 8000 100 satheesh 2500 150 sam 8000 200 zam dem 10000 85 william 15000 500 james 10000 95 mone jo 15000 500 santhosh 6000 160 ENAME SAL COMM ------------ ---------- ---------- husain 9000 300 johnson 20000 jonathen 8000 190 14 rows selected. AnsAnsAnsAns:::: 3 3 3 3 SQL> select empno,ename,(sal+comm) as total_salary from emp; EMPNO ENAME TOTAL_SALARY ---------- ------------ ------------ 1101 Smith 14200
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 73
1102 john 8100 1120 william 15500 1122 james 1121 johnson 1126 james 10095 1127 zam dem 10085 1129 mone jo 15500 1130 xelestina 16200 1140 satheesh 2650 1141 santhosh 6160 EMPNO ENAME TOTAL_SALARY ---------- ------------ ------------ 1142 jonathen 8190 1143 sam 8200 1144 husain 9300 14 rows selected. AnsAnsAnsAns:::: 4 4 4 4 SQL> select empno,ename,((sal+comm)*12) as total_annual_salary from emp; EMPNO ENAME TOTAL_ANNUAL_SALARY ---------- ------------ ------------------- 1101 Smith 170400 1102 john 97200 1120 william 186000 1122 james 1121 johnson 1126 james 121140 1127 zam dem 121020 1129 mone jo 186000 1130 xelestina 194400 1140 satheesh 31800 1141 santhosh 73920 EMPNO ENAME TOTAL_ANNUAL_SALARY ---------- ------------ ------------------- 1142 jonathen 98280 1143 sam 98400 1144 husain 111600 14 rows selected. AnsAnsAnsAns:::: 5 5 5 5 SQL> select empno,ename,((sysdate-doj)/12) as experience from emp order by exper ience desc; EMPNO ENAME EXPERIENCE ---------- ------------ ---------- 1127 zam dem 1126 james 1101 Smith 707.788011 1129 mone jo 668.204678 1122 james 660.621345 1121 johnson 508.454678 1102 john 367.288011 1130 xelestina 363.871345 1142 jonathen 273.204678 1140 satheesh 237.704678 1141 santhosh 154.038011
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 74
EMPNO ENAME EXPERIENCE ---------- ------------ ---------- 1120 william 56.9546779 1144 husain 39.3713445 1143 sam 1.37134452 14 rows selected. AnsAnsAnsAns:::: 6 6 6 6 SQL> select empno, ename, sal,(sal*10/100) as salper10,(sal*50/100) as salper50 ,(comm*30/100) as commper30,(comm*110/100)as commper110 from emp; EMPNO ENAME SAL SALPER10 SALPER50 COMMPER30 COMMPER110 ---------- ------------ ---------- ---------- ---------- ---------- ---------- 1101 Smith 14000 1400 7000 60 220 1102 john 8000 800 4000 30 110 1120 william 15000 1500 7500 150 550 1122 james 20000 2000 10000 1121 johnson 20000 2000 10000 1126 james 10000 1000 5000 28.5 104.5 1127 zam dem 10000 1000 5000 25.5 93.5 1129 mone jo 15000 1500 7500 150 550 1130 xelestina 16000 1600 8000 60 220 1140 satheesh 2500 250 1250 45 165 1141 santhosh 6000 600 3000 48 176 EMPNO ENAME SAL SALPER10 SALPER50 COMMPER30 COMMPER110 ---------- ------------ ---------- ---------- ---------- ---------- ---------- 1142 jonathen 8000 800 4000 57 209 1143 sam 8000 800 4000 60 220 1144 husain 9000 900 4500 90 330 14 rows selected. AnsAnsAnsAns:::: 7 7 7 7 SQL> select empno,ename,(sal+comm) as total_salary,((sal+comm)*10/100) as total_ sal10,((sal+comm)*50/100) as total_sal50 from emp; EMPNO ENAME TOTAL_SALARY TOTAL_SAL10 TOTAL_SAL50 ---------- ------------ ------------ ----------- ----------- 1101 Smith 14200 1420 7100 1102 john 8100 810 4050 1120 william 15500 1550 7750 1122 james 1121 johnson 1126 james 10095 1009.5 5047.5
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 75
1127 zam dem 10085 1008.5 5042.5 1129 mone jo 15500 1550 7750 1130 xelestina 16200 1620 8100 1140 satheesh 2650 265 1325 1141 santhosh 6160 616 3080 EMPNO ENAME TOTAL_SALARY TOTAL_SAL10 TOTAL_SAL50 ---------- ------------ ------------ ----------- ----------- 1142 jonathen 8190 819 4095 1143 sam 8200 820 4100 1144 husain 9300 930 4650 14 rows selected. AnsAnsAnsAns:::: 8 8 8 8
SQL> select * from emp where sal in (select max(sal) from emp); EMPNO ENAME DOJ MGRSSN SAL COMM DNO S ---------- ------------ --------- ---------- ---------- ---------- ---------- - 1122 james 20-JUL-85 20000 10 1121 johnson 20-JUL-90 20000 20 AnsAnsAnsAns:::: 9999 SQL> select * from emp where sal in (select min(sal) from emp); EMPNO ENAME DOJ MGRSSN SAL COMM DNO S ---------- ------------ --------- ---------- ---------- ---------- ---------- - 1140 satheesh 12-JUN-99 1120 2500 150 20
AnsAnsAnsAns:::: 10 10 10 10
SQL> column no_name format a16; SQL> select empno||ename as no_name,(sal+comm) as total from emp; NO_NAME TOTAL ---------------- ---------- 1101Smith 14200 1102john 8100 1120william 15500 1122james 1121johnson 1126james 10095 1127zam dem 10085 1129mone jo 15500 1130xelestina 16200 1140satheesh 2650 1141santhosh 6160 NO_NAME TOTAL ---------------- ---------- 1142jonathen 8190 1143sam 8200 1144husain 9300 14 rows selected.
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 76
Exercise no 5
1. Write an SQL plus statement to create a new employee table with following
details
Empno number(5) primary key
ename varchar2(15) default 'Not Null'
doj date
bp number default 5000
desg varchar2(15) default 'Not Entered'.
2. Display the experience of each employee in the descending order of
experience (in years)
3. Display empno, empname, basic pay, da, hra and netsalary of all employees
with suitable heading as DA, HRA,…etc.DA=7.5% of basic, HRA=9% of basic,
netsal=basic+HRA+DA.
4. Insert some values of empno, doj, empname.
5. Display the total basic salary given to employees to each designation which is
greater than 10000.
6. Display the empno, name and basic of all employees for either manager or
clerk and basic salary in the range of 6000 and 11000
7. Display the empno, empname, designation and salary of employee with
largest salary
8. Alter the table employee by dropping the primary key
9. Alter the table employee by adding a new field ssn as primary key.
10. Create a table emp_sal with fields empno ,empname, bp, da using new
employee table.
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 77
Ans:Ans:Ans:Ans: 1 1 1 1 SQL> create table emp1 2 ( 3 empno number(5) primary key, 4 ename varchar2(15) default 'Not Null', 5 doj date , 6 bp number default 5000, 7 desg varchar2(15) default 'Not Entered' 8 ); Table created. SQL> insert into emp1 values(&empno,'&ename','&doj',&bp,'&desg'); Enter value for empno: 1101 Enter value for ename: smith Enter value for doj: 12-mar-2000 Enter value for bp: 5000 Enter value for desg: manager old 1: insert into emp1 values(&empno,'&ename','&doj',&bp,'&desg') new 1: insert into emp1 values(1101,'smith','12-mar-2000',5000,'manager') 1 row created. SQL> / Enter value for empno: 1102 Enter value for ename: john Enter value for doj: 12-april-1985 Enter value for bp: 3000 Enter value for desg: clerk old 1: insert into emp1 values(&empno,'&ename','&doj',&bp,'&desg') new 1: insert into emp1 values(1102,'john','12-april-1985',3000,'clerk') 1 row created. SQL> / Enter value for empno: 1103 Enter value for ename: willian Enter value for doj: 12-dec-1999 Enter value for bp: 8000 Enter value for desg: MD old 1: insert into emp1 values(&empno,'&ename','&doj',&bp,'&desg') new 1: insert into emp1 values(1103,'willian','12-dec-1999',8000,'MD') 1 row created. SQL> / Enter value for empno: 1104 Enter value for ename: james Enter value for doj: 14-feb-1988 Enter value for bp: 11000 Enter value for desg: director old 1: insert into emp1 values(&empno,'&ename','&doj',&bp,'&desg') new 1: insert into emp1 values(1104,'james','14-feb-1988',11000,'director') 1 row created. AnsAnsAnsAns:::: 2 2 2 2 SQL> select ename,round(months_between(sysdate,doj)/12) as exp from
emp1 order by exp desc;
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 78
ENAME EXP ------------ ---------- john 22 james 19 willian 7 smith 7 Ans: 3Ans: 3Ans: 3Ans: 3 SQL> select empno,bp,ename,bp,0.075*bp as DA,0.09*bp as
HRA,bp+(0.075*bp)+(0.09*bp)as NET from emp1;
EMPNO BP ENAME BP DA HRA NET ---------- ---------- ------------ ---------- ---------- ---------- ---------- 1101 5000 smith 5000 375 450 5825 1102 3000 john 3000 225 270 3495 1103 8000 willian 8000 600 720 9320 1104 11000 james 11000 825 990 12815 Ans: 4Ans: 4Ans: 4Ans: 4 SQL> insert into emp1(empno,ename,doj) values (1110,'mathew','02-dec-
2006');
1 row created. Ans: 5Ans: 5Ans: 5Ans: 5 SQL> select desg,sum(bp) as NET_SALARY from emp1 group by desg having
sum(bp)> 10000;
DESG NET_SALARY --------------- ---------- director 11000 Ans: 6Ans: 6Ans: 6Ans: 6 SQL> select desg,bp from emp1 where desg in('manager','clerk') and bp
between 6000 and 11000;
no rows selected Ans: 7Ans: 7Ans: 7Ans: 7 SQL> select empno,ename,bp from emp1 where bp=(select max(bp) from
emp1);
EMPNO ENAME BP ---------- ------------ ----------
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 79
1104 james 11000 Ans: 8Ans: 8Ans: 8Ans: 8 SQL> alter table emp1 drop primary key; Table altered. SQL> select * from emp1; EMPNO ENAME DOJ BP DESG ---------- ------------ --------- ---------- --------------- 1101 smith 12-MAR-00 5000 manager 1102 john 12-APR-85 3000 clerk 1103 willian 12-DEC-99 8000 MD 1104 james 14-FEB-88 11000 director 1110 mathew 02-DEC-06 5000 Not Entered SQL> desc emp1; Name Null? Type ----------------------------------------- -------- ----------------------- EMPNO NUMBER(5) ENAME VARCHAR2(15) DOJ DATE BP NUMBER DESG VARCHAR2(15) Ans: 9Ans: 9Ans: 9Ans: 9 SQL> alter table emp1 add ssn number(5); Table altered. SQL> update emp1 set ssn=empno; 5 rows updated. SQL> alter table emp1 add primary key(ssn); Table altered. SQL> select * from emp1; EMPNO ENAME DOJ BP DESG SSN ---------- ------------ --------- ---------- --------------- ---------- 1101 smith 12-MAR-00 5000 manager 1101 1102 john 12-APR-85 3000 clerk 1102 1103 willian 12-DEC-99 8000 MD 1103 1104 james 14-FEB-88 11000 director 1104 1110 mathew 02-DEC-06 5000 Not Entered 1110 SQL> desc emp1; Name Null? Type ----------------------------------------- -------- ----------------------------
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 80
EMPNO NUMBER(5) ENAME VARCHAR2(15) DOJ DATE BP NUMBER DESG VARCHAR2(15) SSN NOT NULL NUMBER(5) Ans: 1Ans: 1Ans: 1Ans: 10000 SQL> create table emp_salary (empno,ename,bp,da) as (select
empno,ename,bp,bp*7/100 from emp1);
Table created. SQL> select * from emp_salary; EMPNO ENAME BP DA ---------- ------------ ---------- ---------- 1101 smith 5000 350 1102 john 3000 210 1103 willian 8000 560 1104 james 11000 770 1110 mathew 5000 350 SQL> desc emp_salary; Name Null? Type ---------------------------- ------------------ -------------- EMPNO NUMBER(5) ENAME VARCHAR2(15) BP NUMBER DA NUMBER
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 81
Exercise no 6
1. Write an SQL statement to display the employee details who are working for
accounts department.
2. Write an SQL statement to display the department details for who are getting
salary >10000.
3. Write an SQL statement to display, who is reporting to whom (ie manager_no,
name, worker_no, name of all employees.
4. Write an SQL statement to display all employees who are not associated with
any department.
5. Write an SQL statement to display all departments without any employees.
6. Write an SQL statement to display employee details who are working for
department sales and not getting any commission.
7. Display the employee details who are working for the marketing department
and salary > 5000.
8. Display the employees who are working for accounts department getting salary
between 5000 and 10000.
9. Display the employees who are working in loation 'Dallas’ and getting salary
between 5000 and 10000.
10. Display the employees who are getting commission as null and working for the
sales department in location ‘Texas’.
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 82
SQL> create table emp ( EMPNO NUMBER(3) primary key, ENAME VARCHAR2(30) not null, JOB VARCHAR2(20), MGR NUMBER(3), DOJ DATE, SAL NUMBER(7,2), COMM NUMBER(5,2), DEPTNO NUMBER(2) ); Table created. SQL> create table dept ( DEPTNO NUMBER(2) primary key, DNAME VARCHAR2(20), LOC VARCHAR2(20) ); Table created.
THE TABLE CONTENTS AFTER INSERTION OPERATIONS ---------------------------------------------
EMPNO ENAME JOB MGR DOJ SAL COMM DEPTNO ---------- ---------- ----------------- ---------- --------- ---------- ---------- ---------- 222 mahesh analyst 333 31-JAN-84 5000 500 10 333 john project_leader 444 31-JAN-83 7000 20 444 satheesh manager 555 31-JAN-82 10000 30 555 mathew managing director 26-JAN-82 15000 30 112 ajay operator 222 22-FEB-84 2000 111 suresh programmer 222 22-FEB-84 3000 300 10 6 rows selected. SQL> select * from dept; DEPTNO DNAME LOC ---------- -------------------- -------------------- 10 accounts texas 20 sales dallas 30 marketing california 40 production miniapolis Ans:Ans:Ans:Ans: 1111 SQL> select emp.ename,emp.empno,emp.sal,emp.doj,emp.job from emp,dept
where emp.deptno=dept.deptno and dept.dname='accounts';
ENAME EMPNO SAL DOJ JOB ---------- ---------- ---------- --------- -------------------- mahesh 222 5000 31-JAN-84 analyst suresh 111 3000 22-FEB-84 programmer
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 83
AnAnAnAnssss:::: 2 2 2 2 SQL> select distinct dept.deptno,dept.dname,dept.loc from dept ,emp
where emp.sal>=10000 and emp.deptno=dept.deptno;
DEPTNO DNAME LOC ---------- -------------------- -------------------- 30 marketing california Ans: 3Ans: 3Ans: 3Ans: 3 SQL> select e1.ename as "employee",e2.ename as "manager" from emp e1,emp e2 wher e e1.mgr=e2.empno; employee manager ------------------------------ ------------------------------ mahesh john john satheesh satheesh mathew ajay mahesh suresh mahesh Ans: 4Ans: 4Ans: 4Ans: 4 SQL> (select emp.ename from emp,dept where emp.deptno=dept.deptno(+))
minus (select emp.ename from emp,dept where emp.deptno=dept.deptno);
ENAME ---------- ajay Ans: 5Ans: 5Ans: 5Ans: 5 SQL> (select dept.dname from emp,dept where emp.deptno(+)=dept.deptno)
minus (select dept.dname from emp,dept where emp.deptno=dept.deptno);
DNAME -------------------- production AnAnAnAnssss:::: 6 6 6 6 SQL> select emp.ename from emp,dept where emp.deptno=dept.deptno and
dept.dname='sales' and emp.comm is null;
ENAME ---------- john SQL> Ans: 7Ans: 7Ans: 7Ans: 7 SQL> select emp.empno,emp.ename,emp.job from emp,dept where
emp.deptno=dept.deptno and dept.dname='marketing' and emp.sal>5000;
EMPNO ENAME JOB
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 84
---------- ---------- -------------------- 444 satheesh manager 555 mathew managing director AnsAnsAnsAns:::: 8 8 8 8 SQL> select emp.ename from emp,dept where emp.deptno=dept.deptno and
dept.dname='accounts' and emp.sal between 5000 and 10000;
ENAME ---------- mahesh AnsAnsAnsAns:::: 9 9 9 9 SQL> select emp.ename from emp,dept where emp.deptno=dept.deptno and
dept.loc='dallas' and emp.sal between 5000 and 10000;
ENAME ---------- john AnsAnsAnsAns: 10: 10: 10: 10 SQL> select emp.ename from emp,dept where emp.deptno=dept.deptno and
dept.loc='texas' and emp.sal between 5000 and 10000;
ENAME ---------- mahesh
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 85
Exercise no 7
1. Write an SQL statement to create a view to display employee number,
employee name, job, salary, department number based on the employee table
2. Write an SQL statement to create view to display employee number, employee
name, job, salary, department number based on employee table who are
getting a salary greater than 5000
3. Write an SQL statement to create a view to display employee number,
employee name, department no, department name from employee table and
department table of all employees.
4. Write an SQL statement to insert records into the view created on the basis of
question 1 and 2.
THE TABLE CONTENTS -------------------
EMPNO ENAME JOB MGR DOJ SAL COMM DEPTNO ---------- ---------- ----------------- ---------- --------- ---------- ---------- ---------- 222 mahesh analyst 333 31-JAN-84 5000 500 10 333 john project_leader 444 31-JAN-83 7000 20 444 satheesh manager 555 31-JAN-82 10000 30 555 mathew managing director 26-JAN-82 15000 30 112 ajay operator 222 22-FEB-84 2000 111 suresh programmer 222 22-FEB-84 3000 300 10 6 rows selected. SQL> select * from dept; DEPTNO DNAME LOC ---------- -------------------- -------------------- 10 accounts texas 20 sales dallas 30 marketing california 40 production miniapolis Ans: 1Ans: 1Ans: 1Ans: 1 SQL> create or replace view empview as select empno, ename, job, sal,
deptno from emp;
View created. SQL> SELECT * FROM EMPVIEW; EMPNO ENAME JOB SAL DEPTNO
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 86
---------- ---------- -------------------- ---------- ---------- 222 mahesh analyst 5000 10 333 john project_leader 7000 20 444 satheesh manager 10000 30 555 mathew managing director 15000 30 112 ajay operator 2000 111 suresh programmer 3000 10 6 rows selected. AnsAnsAnsAns: 2: 2: 2: 2 SQL> create or replace view empview2 as select empno, ename, job,
sal, deptno from emp where sal>5000;
View created. SQL> SELECT * FROM EMPVIEW2; EMPNO ENAME JOB SAL DEPTNO ---------- ---------- -------------------- ---------- ---------- 333 john project_leader 7000 20 444 satheesh manager 10000 30 555 mathew managing director 15000 30 Ans: Ans: Ans: Ans: 3333 SQL> create or replace view empdeptview as select emp.empno,
emp.ename,emp.deptno,dept.dname from emp,dept where
emp.deptno=dept.deptno;
View created. SQL> SELECT * FROM EMPDEPTVIEW; EMPNO ENAME DEPTNO DNAME ---------- ---------- ---------- -------------------- 222 mahesh 10 accounts 333 john 20 sales 444 satheesh 30 marketing 555 mathew 30 marketing 111 suresh 10 accounts Ans: 4Ans: 4Ans: 4Ans: 4 SQL> DESC EMPVIEW; Name Null? Type ----------------------------------------- -------- ---------------------------- EMPNO NOT NULL NUMBER(3) ENAME NOT NULL VARCHAR2(30) JOB VARCHAR2(20) SAL NUMBER(7,2) DEPTNO NUMBER(2) SQL> DESC EMPVIEW2; Name Null? Type ----------------------------------------- -------- ----------------------------
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 87
EMPNO NOT NULL NUMBER(3) ENAME NOT NULL VARCHAR2(30) JOB VARCHAR2(20) SAL NUMBER(7,2) DEPTNO NUMBER(2) SQL> INSERT INTO EMPVIEW VALUES(666,'hari','programmer',4000,40); 1 row created. SQL> INSERT INTO EMPVIEW VALUES(667,'sarath','programmer',5000,40); 1 row created. SQL> INSERT INTO EMPVIEW2 VALUES(668,'hilary','analyst',5000,10); 1 row created. SQL> INSERT INTO EMPVIEW2 VALUES(669,'sardar g','operator',4000,40); 1 row created. SQL> select * from empview; EMPNO ENAME JOB SAL DEPTNO ---------- ---------- -------------------- ---------- ---------- 222 mahesh analyst 5000 10 333 john project_leader 7000 20 444 satheesh manager 10000 30 555 mathew managing director 15000 30 112 ajay operator 2000 111 suresh programmer 3000 10 666 hari programmer 4000 40 667 sarath programmer 5000 40 668 hilary analyst 5000 10 669 sardar g operator 4000 40 10 rows selected. SQL> select * from empview2; EMPNO ENAME JOB SAL DEPTNO ---------- ---------- -------------------- ---------- ---------- 333 john project_leader 7000 20 444 satheesh manager 10000 30 555 mathew managing director 15000 30
THE BASE TABLE AFTER INSERTING VALUES INTO THE VIEWS SQL> select empno,ename,job,mgr,doj,sal from emp; EMPNO ENAME JOB MGR DOJ SAL COMM DEPTNO ---------- ---------- -------------------- ---------- --------- ---------- ---------- ---------- 222 mahesh analyst 333 31-JAN-84 5000 500 10 333 john project_leader 444 31-JAN-83 7000 20 444 satheesh manager 555 31-JAN-82 10000 30
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 88
555 mathew managing director 26-JAN-82 15000 30 112 ajay operator 222 22-FEB-84 2000 111 suresh programmer 222 22-FEB-84 3000 300 10 666 hari programmer 4000 40 667 sarath programmer 5000 40 668 hilary analyst 5000 10 669 sardar g operator 4000 40 10 rows selected.
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 89
PL/SQL
SOLVED PROBLEMS
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 90
Exercise no 1
Aim:
To find the greatest among three numbers
.
Algorithm:
Step 1: Start.
Step 2: Declare variables a,b and c as integers and initialize them.
Step 3: Check whether:
a > b and a > c, then print a is greater
elsif check b>c then b is greater
else c is greater
Step 5: Stop.
Program:
Declare
a number(10):='&a';
b number(10):='&b';
c number(10):='&c';
Begin
if ((a>b) and (a>c)) then
dbms_output.put_line('a is greater');
elsif (b>c) then
dbms_output.put_line('b is greater');
else
dbms_output.put_line('c is greater');
end if;
End;
/
Output:
Enter value for a: 4
old 2: a number(10):='&a';
new 2: a number(10):='4';
Enter value for b: 3
old 3: b number(10):='&b';
new 3: b number(10):='3';
Enter value for c: 2
old 4: c number(10):='&c';
new 4: c number(10):='2';
a is greater
PL/SQL procedure successfully completed.
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 91
Exercise no 2
Aim:
To write a PL/SQL code for factorial of a number.
Algorithm:
Step 1: Start.
Step 2: Declare variables n(the number),i(initialized to 1) and f(initialized to 1) get
value to n.
Step 3: Check if i is lesser than or equal to n, if not then goto Step 6.
Step 4: Set f as product of current f and i.
Increment value to i by 1.
Step 5: Goto Step 3.
Step 6: Print factorial(f) of n.
Step 7: Stop.
Program:
Declare
n number(2):='&n';
i number(2):=1;
f number(30):=1;
Begin
while (i<=n)
Loop
f:=f*i;
i:=i+1;
End Loop;
dbms_output.put_line('Factorial of '|| n ||' :-'||f);
End;
/
Output:
Enter value for n: 3
old 2: n number(2):='&n';
new 2: n number(2):='3';
Factorial of 3 :-6
PL/SQL procedure successfully completed.
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 92
Exercise no 3
Aim:
To write a PL/SQL block to generate Fibonacci series.
Algorithm:
Step 1: Start.
Step 2: Declare variables.
n – for limit
a =0
b=1
c=1
Step 3: Check if c lesser than n, if false then goto Step 5.
Print value to c. Set c as sum of a and b.
Set a = b .
Set b = c.
Step 4: goto step 3
Step 5: stop
Program:
Declare
n number(8):='&n';
a number(8):=0;
b number(8):=1;
c number(8):=1;
Begin
dbms_output.put_line('Limit is '||n||'');
dbms_output.put_line('**************');
dbms_output.put_line('The series is');
dbms_output.put_line('**************');
dbms_output.put_line(a);
while (c<n)
Loop
dbms_output.put_line(c);
c:=a+b;
a:=b;
b:=c;
End Loop;
End;
/
Output:
Enter value for n: 4
old 2: n number(8):='&n';
new 2: n number(8):='4';
Limit is 4
**************
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 93
The series is
**************
0
1
1
2
3
PL/SQL procedure successfully completed.
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 94
Exercise no 4
Table Used
EMPNO EMPNAME SAL DEPTNO COMM
------- ---------- ------ ----------- --------
1111 AISWARYA 5000 5 300.5
1112 EISHA 6000 8 342.15
1113 NASHA 7000 4 242.15
1114 ABHIJEET 1000 10 150
1115 CLARK 10000 9 350
Aim:
Write a PL/SQL block to display empno, empname, deptno and salary of employee no
is 1113.
Algorithm:
Step1: Start
Step2: declare variables en(empno),
name(empname), sal(sal) ,dno(deptno),
com(comm) of %type.
Step3: select the values for en,name,sal,dno,com from EMP table with empno=1113
Step4: print the values of en,name,sal,dno
Step5: stop
Program:
declare
en emp.empno%type;
name emp.empname%type;
sal emp.sal%type;
dno emp.deptno %type;
com emp.comm%type;
begin
select empno, empname, sal, deptno into en, name,
sal, dno from emp where empno=1113;
dbms_output.put_line(‘employee no is’|| en);
dbms_output.put_line(‘name ’||name);
dbms_output.put_line(‘salary’|| to_char(sal));
dbms_output.put_line(‘dept-no’|| to-char(dno));
end;
/
Output:
EMPLOYEE NO IS 1113
NAME NASHA
SALARY 7000
DEPT-NO 4
PL/SQL procedure successfully completed.
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 95
Exercise no 5
Aim:
Write a PL/SQL block to display empno, empname and salary of employee who is
getting salary 1000 and who is working in department no 10.
Algorithm:
Step1: Start
Step2: declare variables en(empno),
name(empname), sal(sal) ,dno(deptno),
com(comm) of %type.
Step3: select the values for en,name,sal,dno,com from EMP table with empno=1000
and deptno = 10
Step4: print the values of en,name,sal,dno
Step5: stop
Program:
declare
en emp.empno%type;
name emp.empname%type;
sal emp.sal%type;
dno emp.deptno %type;
com emp.comm%type;
begin
select empno, empname, sal, deptno into en, name, sal, dno from
emp where sal=1000 and deptno=10;
dbms_output.put_line(‘employee no is’|| en);
dbms_output.put_line(‘name ’||name);
dbms_output.put_line(‘salary’|| to_char(sal));
dbms_output.put_line(‘dept-no’|| to-char(dno));
end;
Output:
EMPLOYEE NO IS 1114
NAME ABHIJEET
SALARY 1000
DEPT-NO 10
PL/SQL procedure successfully completed.
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 96
Exercise no 6
Aim:
Write a PL/SQL block to display and calculate da, hra, ta for the employee CLARK. hra
is calculated based on 10% of basic, da is calculated based on 6% of basic and ta is
calculated based on 10% of commission. total salary is calculated based on the sum of
da, hra, ta and basic salary.
Algorithm:
Step1: Start
Step2: declare variables name,sl,cm,da,hra,ta,tsal
Step3: select the values for name,sl,cm from EMP table with empname=clerk
Step4: compute da= sl*0.06, hra=sl*.01,ta=cm*.01,tsal = sl+da+hra+ta
Step5: print the values of name,sl,da,hra,ta,tsal
Step5: stop
Program:
declare
name emp.empname%type;
sl emp.sal%type;
cm emp.comm%type;
da number(6,2);
hra number(6,2);
ta number(6,2);
tsal number(8,2);
begin
select empname, sal, comm into name, sl, cm from emp where
empname like ‘clark’;
da:=sl*0.06;
hra:=sl*0.1;
ta:=cm*0.1;
tsal:=sl+da+hra+ta;
dbms_output.put_line(‘name ’||name);
dbms_output.put_line(‘salary’|| to_char(sl));
dbms_output.put_line(‘da’|| to_char(da));
dbms_output.put_line(‘hra’|| to_char(hra));
dbms_output.put_line(‘ta’|| to_char(ta));
dbms_output.put_line(‘totalsalary’|| to_char(tsal));
end;
Output:
NAME CLARK
SALARY 10000
DA 600
HRA 1000
TA 50
TOTAL SALARY 11650
PL/SOL procedure successfully completed.
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 97
Exercise no 7
Aim:
Write a PL/SQL block to display total salary of all employees.
Algorithm:
Step1: Start
Step2: declare the variables n1(empno),sl(sal),na(empname),com(comm) of %type
Step3: Initialize the cursor c1 by selecting empno,empname,sal,comm from emp.
Step4: open the cursor c1
Step5: fetch the values of n1,na,sl,com into cursor c1.
Step6: calculate ts = sl + com
Step7: print the values of n1,na,ts
Step8: close the cursor c1
Step9: Stop
Program:
declare
n1 emp.empno%type;
sl emp.sal%type;
na emp.empname%type;
com emp.comm%type;
cursor c1 is select empno, empname, sal, comm from emp;
ts number(8,2);
begin
open c1;
dbms_output.put_line(‘……………………..’);
loop
fetch c1 into n1,na,sl,com;
exit when (c1%notfound);
ts:=sl+nvl(com,0);
dbms_output.put_line(‘empno’|| to_char(n1));
dbms_output.put_line(‘name ’||na);
dbms_output.put_line(‘total salary’|| to_char(ts));
dbms_output.put_line(‘……………………..’);
end loop;
close c1;
end;
Output:
EMPNO 1111
NAME AISHWARYA
TOTAL SALARY 5300.5
……………………………………………
EMPNO 1112
NAME EISHA
TOTAL SALARY 6772.5
……………………………………………
EMPNO 1113
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 98
NAME NASHA
TOTAL SALARY 15300.5
……………………………………………
EMPNO 1114
NAME ABHIJEETH
TOTAL SALARY 8307.5
……………………………………………
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 99
Exercise no 8
Aim:
Create a procedure to evaluate student grade by accepting student name.
Algorithm:
Step 1: Start procedure.
Step 2: Define procedure sgrade taking parameter name and program variable
mk(mark).
Step 3: Select mark of student into an integer(mk) whose name had been passed.
Step 4: If mk greater than 90 then
Print “Grade:=X”.
Else if mk greater than 80 then
Print “Grade:=A”.
Else if mk greater than 60 then
Print “Grade:=B”.
Else if mk greater than 50 then
Print “Grade:=C”.
Else
Print “Grade:=F”.
Step 5: Stop procedure.
Program:
create or replace procedure sgrade(n_name IN varchar2)
IS
mk number(3);
Begin
select mark into mk from student where name=n_name;
if mk>90 then
dbms_output.put_line('Grade:=X');
else if mk>80 then
dbms_output.put_line('Grade:=A');
else if mk>60 then
dbms_output.put_line('Grade:=B');
else if mk>50 then
dbms_output.put_line('Grade:=C');
else
dbms_output.put_line('Grade:=F');
end if;
end if;
end if;
end if;
End sgrade;
/
Procedure created.
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 100
Output:
SQL> execute sgrade('rajesh');
Grade:=B
PL/SQL procedure successfully completed.
SQL> execute sgrade('jeevan');
Grade:=A
PL/SQL procedure successfully completed.
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 101
Exercise no 9
Table Used
ENO ENAME DNAME DOJ DESIG
----- --------- --------- ----------------- ----------------
100 rajesh MCA 25-MAY-05 lecturer
102 joy ME 20-APR-06 lecturer
104 ranjith EC 12-JAN-06 lecturer
105 mable CSE 12-JAN-04 lecturer
Aim:
Write a procedure in PL/SQL to check if employee is eligible for promotion depending
on his period of service.
Algorithm:
Step1: Start.
Step2: Define procedure des_ch taking parameter employee number (eid)
Step3: Declare variables dt (experience), jd(joining date), sd(system date).
Step4: Select doj field value from relation emp_proc into program variable jd for an
employee (whose employee id is eid).
Step5: Select system date into program variable sd.
Step6: Compute the number of months between jd and sd dates.
Step7: Check if dt greater than or equal to 3,
if true then update design=ass.prof
Print “Your designation changed”.
Else
Print “you have to wait”.
Step8: Stop.
Program:
create or replace procedure des_ch(eid IN varchar2)
IS
dt number;
jd date;
sd date;
Begin
select doj into jd from emp_proc where eno=eid;
select sysdate into sd from dual;
dt:=months_between(sd,jd) / 12;
if dt>=3 then
update emp_proc set desig='ass.prof' where eno=eid;
dbms_output.put_line('Your designation changed');
else
dbms_output.put_line('you have to wait');
end if;
End des_ch;
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 102
Output:
SQL> execute des_ch(100);
you have to wait
PL/SQL procedure successfully completed.
SQL> execute des_ch(102);
you have to wait
PL/SQL procedure successfully completed.
SQL> execute des_ch(104);
you have to wait
PL/SQL procedure successfully completed.
SQL> execute des_ch(105);
Your designation changed
PL/SQL procedure successfully completed.
select * from emp_proc;
ENO ENAME DNAME DOJ DESIG
----- --------- --------- ----------------- ----------------
100 rajesh MCA 25-MAY-05 lecturer
102 joy ME 20-APR-06 lecturer
104 ranjith EC 12-JAN-06 lecturer
105 mable CSE 12-JAN-04 ass.prof
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 103
Exercise no 10
Aim:
Write a function in PL/SQL to find student grade by accepting student name as
argument.
Algorithm:
Step 1: Start
Step 2: Define function Sff taking parameter as name.
Step 3: Declare variables mk(mark) and g(grade).
Step 4: Select mark of student into an mk whose name had been passed.
Step 5: If mk greater than 90 then
g=x
Print “Grade:=X”.
Else if mk greater than 80 then
g=A
Print “Grade:=A”.
Else if mk greater than 60 then
g=B
Print “Grade:=B”.
Else if mk greater than 50 then
g=C
Print “Grade:=C”.
Else g=C.
Print “Grade:=F”.
Step 6: Return value to grade g.
Step 7: Stop
Program:
create or replace function Sff(n_name IN varchar2) return varchar2
IS
g varchar2(1);
mk number(3);
Begin
select mark into mk from student where name=n_name;
if mk>90 then
g:='x';
dbms_output.put_line('Grade: ' || g );
else if mk>80 then
g:='A';
dbms_output.put_line('Grade: ' || g );
else if mk>60 then
g:='B';
dbms_output.put_line('Grade: ' || g );
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 104
else if mk>50 then
g:='C';
dbms_output.put_line('Grade: ' || g );
else
g:='F';
dbms_output.put_line('Grade: ' || g );
end if;
end if;
end if;
end if;
return g;
End Sff;
Output:
SQL> select Sff('ntini') from dual;
SFF('NTINI')
--------------------------------------
A
Grade: A
SQL> select Sff('rajesh') from dual;
SFF('RAJESH')
--------------------------------------
X
Grade: X
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 105
Exercise no 11
Tables Used
T4
NO CHARA
------ ---------
5 Rajesh
13 Rejeev
10 Reneesh
T5
NO CHARA
Aim:
Create a trigger that may insert a tuple into table5 when a tuple is inserted into table4,
the trigger has to check whether the new tuple has first component 10 or less, and if
so insert the tuple into table5.
Program:
create or replace trigger tr1
after insert on t4
referencing new as newrow
for each row when (newrow.no<11)
begin
insert into t5 values(:newrow.no,:newrow.chara);
end tr1;
Output:
SQL>run;
trigger created.
SQL>select * from T5;
NO CHARA
------ ---------
5 Rajeesh
10 Reneesh
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 106
Exercise no 12
Tables Used
manager
MANAGERID MNAME
--------------------- -------------
41 Sanjitha
101 Abro
1 Sameer
employee
EMPNO ENAME
Aim:
Create a trigger that may insert a tuple into EMPLOYEE(empno,ename) when a tuple is
updated into MANAGER(managerid,mname) the trigger has to check whether the new
tuple has a first component 50 or less, and if so insert the tuple into EMPLOYEE.
create or replace trigger tr2
after update on manager
referencing new as newrow
for each row when (newrow.manager<51)
begin
insert into employe values
(:newrow.managerid,:newrow.mname);
end tr2;
Output:
SQL>run;
trigger created.
SQL> update manager set managerid =50 where mname=’Sanjith’;
1 row updated.
SQL>select * from employe;
MANAGERID MNAME
------------- ----------
50 Sanjitha
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 107
Database connectivity
Solved Problems
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 108
Exercise no 1
Aim: Create a database application in visual basic to manipulate student’s information.
Option Explicit Public LoginSucceeded As Boolean Private Sub cmdCancel_Click() LoginSucceeded = False Me.Hide End Sub Private Sub cmdOK_Click() If txtPassword = "ide" Then LoginSucceeded = True Unload frmLogin ICEmain.Show Else MsgBox "Invalid Password, try again!", , "Login" txtPassword.Text = "" End If End Sub
Private Sub Form_Load() txtUserName = "IDE" End Sub
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 109
Private Sub emd_Click() editregfrm.Show End Sub Private Sub exit_Click() Unload ICEmain End Sub Private Sub memb_Click() viewfrm.Show End Sub Private Sub newreg_Click() regfrm.Show End Sub Private Sub rm_Click() deletefrm.Show End Sub
Dim db As ADODB.Connection Dim gender As String Private Sub cancelcmd_Click() Unload regfrm End Sub
Private Sub femaleopt_Click() If femaleopt.Value = True Then gender = femaleopt.Caption End If End Sub Private Sub Form_Load() Set db = New ADODB.Connection db.Open ("provider=MSDASQL.1;data source=rvs;user id=system;
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 110
password=sa") coursecmb.AddItem ("MCA") coursecmb.AddItem ("MBA") coursecmb.AddItem ("BTech CSE") coursecmb.AddItem ("BTech IT") coursecmb.AddItem ("BTech EEE") coursecmb.AddItem ("BTech EC") datetxt.Text = Date End Sub Private Sub maleopt_Click() If maleopt.Value = True Then gender = maleopt.Caption End If End Sub Private Sub savecmd_Click() db.Execute ("insert into lab(regno,name,course,gender) values('" & regtxt.Text & "','" & nametxt.Text & "','" & coursecmb.Text & "','" & gender & "')") MsgBox ("Thank You , Record saved") regtxt.Text = Clear nametxt.Text = Clear regtxt.Text = Clear End Sub
Dim s As String Private Sub cancelcmd_Click() Unload editregfrm End Sub Private Sub editcmd_Click() Editfrm.Show End Sub Private Sub Form_Load() Set db = New ADODB.Connection Set rs = New ADODB.Recordset db.Open ("provider=MSDASQL.1;data source=rvs;user id=system; password=sa") Set rs = db.Execute("select regno from lab") While rs.EOF <> True
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 111
editregcmb.AddItem (rs![regno]) rs.MoveNext Wend s = editregcmb.Text End Sub
Private Sub Form_Load() ecoursecmb.AddItem ("MCA") ecoursecmb.AddItem ("MBA") ecoursecmb.AddItem ("BTech CSE") ecoursecmb.AddItem ("BTech IT") ecoursecmb.AddItem ("BTech EEE") ecoursecmb.AddItem ("BTech EC") eregtxt.Text = editregfrm.editregcmb.Text eregtxt.Enabled = False Set db = New ADODB.Connection Set rs = New ADODB.Recordset db.Open ("provider=MSDASQL.1;data source=rvs;user id=system; password=sa") Set rs = db.Execute("select* from lab where regno='" & eregtxt.Text & "'") enametxt.Text = rs![Name] ecoursecmb.Text = rs![course] If rs![gender] = "Male" Then eoptionmale.Value = True Else eoptionfemale.Value = True End If End Sub Dim ecmb As String Dim egender As String Dim db As ADODB.Connection Dim rs As ADODB.Recordset Private Sub ecancelcmd_Click()
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 112
Unload Editfrm End Sub Private Sub eoptionfemale_Click() If eoptionmale.Value = True Then egender = eoptionmale.Caption End If End Sub Private Sub eoptionmale_Click() If eoptionfemale.Value = True Then egender = eoptionfemale.Caption End If End Sub Private Sub eupdatecmd_Click() If eoptionmale.Value = True Then egender = eoptionmale.Caption End If If eoptionfemale.Value = True Then egender = eoptionfemale.Caption End If ecmb = ecoursecmb.Text Set rs = db.Execute("update lab set name = '" & enametxt.Text & "', course ='" & ecmb & "',gender ='" & egender & "' where regno='" & eregtxt.Text & "' ") MsgBox ("your record is edited") Unload Editfrm End Sub
Private Sub Form_Load() Set db = New ADODB.Connection Set rs = New ADODB.Recordset db.Open ("provider=MSDASQL.1;data source=rvs;user id=system; password=sa") Set rs = db.Execute("select regno from lab") While rs.EOF <> True deleteregcmb.AddItem (rs![regno]) rs.MoveNext Wend End Sub
DATABASE MANAGEMENT SYSTEMS LAB MANUAL
DEPARTMENT OF COMPUTER APPLICATIONS 113
Dim db As ADODB.Connection Dim rs As ADODB.Recordset Private Sub cancelcmb_Click() Unload deletefrm End Sub Private Sub deletecmb_Click() db.Execute ("delete from lab where regno='" & deleteregcmb.Text & "' ") MsgBox ("your record with Regno '" & deleteregcmb.Text & "' is deleted") End Sub
Private Sub Form_Load() With Adodc1 .ConnectionString = "dsn=rvs" .UserName = "system" .Password = "sa" .RecordSource = "select * from lab" End With Set DataGrid1.DataSource = Adodc1 End Sub