Download CS2258 DATABASE MANAGEMENT SYSTEMS LAB MANUAL R.SAVITHRI

Document related concepts

Database wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

Clusterpoint wikipedia , lookup

Relational algebra wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

Ingres (database) wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

Open Database Connectivity wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Null (SQL) wikipedia , lookup

SQL wikipedia , lookup

Join (SQL) wikipedia , lookup

PL/SQL wikipedia , lookup

Relational model wikipedia , lookup

Database model wikipedia , lookup

Transcript
CS2258 DATABASE MANAGEMENT SYSTEMS
LAB MANUAL
Prepared by
R.SAVITHRI
Senior Lecturer – IT
Rajalakshmi Engineering College, Chennai
Visit us: www.rajalakshmi.org
CS2258 DATABASE MANAGEMENT SYSTEMS LAB MANUAL
CS1307
Exp.No
1
2
3
4
5
6
7
8
9
10
11
12
13
DATABASE MANAGEMENT SYSTEMS LAB
LIST OF EXPERIMENTS
Page.No
Data Definition, Table Creation, Constraints
Insert, Select Commands, Update & Delete Commands.
Inbuilt functions in RDBMS.
Nested Queries & Join Queries.
Set operators & Views.
Control structures.
Procedures and Functions.
Triggers
Front End Tool
Forms
Menu Design
Reports
Database Design and implementation – Employee database
SQL
SQL (Structured Query Language) is a database computer language designed for the retrieval and
management of data in relational database management systems (RDBMS), database schema creation
and modification, and database object access control management.SQL is a standard supported by all
the popular relational database management systems in the market place. The basis data structure in
RDBMS is a table. SQL provides you the features to define tables, define constraints on tables, query
for data in table, and change the data in table by adding, modifying, and removing data. SQL also
supports grouping of data in multiple rows, combining tables and other features. All these put together,
SQL is a high-level query language standard to access and alter data in RDBMS.
History of SQL:
The first version of SQL was developed at IBM by Donald D. Chamberlin and Raymond F. Boyce in
the early 1970s. This version, initially called SEQUEL, was designed to manipulate and retrieve data
stored in IBM's original relational database product, System R. IBM patented their version of SQL in
1985, while the SQL language was not formally standardized until 1986, by the American National
Standards Institute (ANSI) as SQL-86. Subsequent versions of the SQL standard have been released by
ANSI and as International Organization for Standardization (ISO) standards.
Originally designed as a declarative query and data manipulation language, variations of SQL have
been created by SQL database management system (DBMS) vendors that add procedural constructs,
control-of-flow statements, user-defined data types, and various other language extensions. With the
release of the SQL:1999 standard, many such extensions were formally adopted as part of the SQL
language via the SQL Persistent Stored Modules (SQL/PSM) portion of the standard.
Rajalakshmi Engineering college
Page 2
Rajalakshmi Engineering College
Querying can be used to: To retrieve existing data from database.
•
•
•
•
•
•
•
•
•
Get all data from the table
Get selected columns from the table.
Get selected rows from the table.
Get selected columns of selected rows from the table.
Get computed columns using char, number, data functions, general functions, and aggregating
functions.
Get data in multiple rows grouped on an aggregating function applied on one or more columns.
Select specific aggregating data on multiple rows using having clause. Apply set operations like
Union and Intersection on data sets of the same cardinality and type.
Get data from multiple tables using Cartesian product, equality join, un-equal join, and outer
join.
Create views on physical data.
Various Data Types :
1. Character Datatypes:
 Char – fixed length character string that can varies between 1-2000 bytes
 Varchar / Varchar2 – variable length character string, size ranges from 1-4000
bytes.it saves the disk space(only length of the entered value will be assigned as
the size of column)
 Long - variable length character string, maximum size is 2 GB
2. Number Datatypes : Can store +ve,-ve,zero,fixed point,floating point with 38 precission.
 Number – {p=38,s=0}
 Number(p) - fixed point
 Number(p,s) –floating point (p=1 to 38,s= -84 to 127)
3. Date Datatype: used to store date and time in the table.
 DB uses its own format of storing in fixed length of 7 bytes for
century,date,month,year,hour,minutes,seconds.
 Default data type is “dd-mon-yy”
4. Raw Datatype: used to store byte oriented data like binary data and byte string.
5. Other :
 CLOB – stores character object with single byte character.
 BLOB – stores large binary objects such as graphics,video,sounds.
 BFILE – stores file pointers to the LOB’s.
P.KUMAR, AP-IT, REC
Page 3
CS2258 DATABASE MANAGEMENT SYSTEMS LAB MANUAL
1. Data Definition Language (DDL) commands in RDBMS.
It is used to communicate with database. DDL is used to:
o Create an object
o Alter the structure of an object
o To drop the object created.
The commands used are:
o Create
o Alter
o Drop
o Truncate
CREATE TABLE
It is used to create a table
Syntax: Create table tablename (column_name1 data_ type constraints,
column_name2 data_ type constraints …)
Example:
1. CREATE TABLE Emp ( EmpNo number(5), EName VarChar(15), Job Char(10) CONSTRAINT
Unik1 UNIQUE, DeptNo number(3) CONSTRAINT FKey2 REFERENCES DEPT(DeptNo));
3.Create table prog20 (pname varchar2(20) not null, doj date not null,dob date not null,
sex varchar(1) not null, prof1 varchar(20),prof2 varchar(20),salary number(7,2) not null);
Rules:
1. Oracle reserved words cannot be used.
3. Underscore, numerals, letters are allowed but not blank space.
3. Maximum length for the table name is 30 characters.
4. 2 different tables should not have same name.
5. We should specify a unique column name.
6. We should specify proper data type along with width.
7. We can include “not null” condition when needed. By default it is ‘null’.
ALTER TABLE
Alter command is used to:
1. Add a new column.
3. Modify the existing column definition.
3. To include or drop integrity constraint.
Syntax: alter table tablename add/modify (attribute datatype(size));
Example:
1. Alter table emp add (phone_no char (20));
2. Alter table emp modify(phone_no number (10));
3. ALTER TABLE EMP ADD CONSTRAINT Pkey1 PRIMARY KEY (EmpNo);
Rajalakshmi Engineering college
Page 4
Rajalakshmi Engineering College
DROP TABLE
It will delete the table structure provided the table should be empty.
Example: drop table prog20;
Here prog20 is table name
TRUNCATE TABLE
If there is no further use of records stored in a table and the structure has to be retained
then the records alone can be deleted.
Syntax: TRUNCATE TABLE <TABLE NAME>;
Example: Truncate table customer;
DESC
This is used to view the structure of the table.
Example: desc emp;
Name
Null?
Type
--------------------------------- --------
----------------------------
EmpNo
number(5)
NOT NULL
EName
Job
DeptNo
PHONE_NO
VarChar(15)
NOT NULL
NOT NULL
Char(10)
number(3)
number (10)
INTEGRITY CONSTRAINT
An integrity constraint is a mechanism used by oracle to prevent invalid data entry into the
table. It has enforcing the rules for the columns in a table. The types of the integrity
constraints are:
a) Domain Integrity
b) Entity Integrity
c) Referential Integrity
a) Domain Integrity
this constraint sets a range and any violations that takes place will prevent the user from
performing the manipulation that caused the breach.It includes:
P.KUMAR, AP-IT, REC
Page 5
CS2258 DATABASE MANAGEMENT SYSTEMS LAB MANUAL
Not Null constraint:
While creating tables, by default the rows can have null value.the enforcement of not null
constraint in a table ensure that the table contains values.
Principle of null values:
o Setting null value is appropriate when the actual value is unknown, or when a value
would not be meaningful.
o A null value is not equivalent to a value of zero.
o A null value will always evaluate to null in any expression.
o When a column name is defined as not null, that column becomes a mandatory i.e.,
the user has to enter data into it.
o Not null Integrity constraint cannot be defined using the alter table command when
the table contain rows.
Example: Create table cust(custid number(6) not null, name char(10));
Alter table cust modify (name not null);
This command will ensure that the user enters a value for the custid,name columns on the
cust table, failing which it returns an error message.
Check Constraint:
Check constraint can be defined to allow only a particular range of values.when the
manipulation violates this constraint,the record will be rejected.Check condition cannot
contain sub queries.
Example:
Create table student (regno number (6), mark number (3) constraint b
(mark >=0 and mark <=100));
check
Alter table student add constraint b2 check (length(regno<=4));
b) Entity Integrity
Maintains uniqueness in a record. An entity represents a table and each row of a table
represents an instance of that entity. To identify each row in a table uniquely we need to
use this constraint. There are 2 entity constraints:
a) Unique key constraint
It is used to ensure that information in the column for each record is unique, as with
telephone or drivers license numbers. It prevents the duplication of value with rows of a
specified column in a set of column. A column defined with the constraint can allow null
value.
If unique key constraint is defined in more than one column i.e., combination of column
cannot be specified. Maximum combination of columns that a composite unique key can
contain is 16.
Rajalakshmi Engineering college
Page 6
Rajalakshmi Engineering College
Example:
Create table cust(custid number(6) constraint uni unique, name char(10));
Alter table cust add(constraint c unique(custid));
PRIMARY KEY CONSTRAINT
A primary key avoids duplication of rows and does not allow null values.can be defined on
one or more columns in a table and is used to uniquely identify each row in a table. These
values should never be changed and should never be null.
A table should have only one primary key. If a primary key constraint is assigned to more
than one column or combination of column is said to be composite primary key, which can
contain 16 columns.
Example;
Create table stud(regno number(6) constraint primary key, name char(20));
Note: Can’t be defined using alter command when there is records in the table having null
values.
c) Referential Integrity
It enforces relationship between tables. To establish parent-child relationship between 2
tables having a common column definition, we make use of this constraint. To implement
this, we should define the column in the parent table as primary key and same column in
the child table as foreign key referring to the corresponding parent entry.
Foreign key
A column or combination of column included in the definition of referential integrity, which
would refer to a referenced key.
Referenced key
It is a unique or primary key upon which is defined on a column belonging to the parent
table.
Problem 1.1: Create a table called EMP with the following structure.
Name
P.KUMAR, AP-IT, REC
Type
Page 7
CS2258 DATABASE MANAGEMENT SYSTEMS LAB MANUAL
-------------------------------EMPNO
ENAME
JOB
MGR
DEPTNO
SAL
------------------------NUMBER(6)
VARCHAR2(20)
VARCHAR2(10)
NUMBER(4)
NUMBER(3)
NUMBER(7,2)
Allow NULL for all columns except ename and job.
Solution:
1. Understand create table syntax.
2. Use the create table syntax to create the said tables.
3. Create primary key constraint for each table as understand from logical table
structure.
Ans:
Problem 1.2: Add a column commission to the emp table
Commission numeric null allowed.
Solution:
1. Learn alter table syntax.
2. Define the new column and its data type.
3. Use the alter table syntax.
Ans:
Problem 1.3: Modify the column width of the job field of emp table.
Solution:
1. Use the alter table syntax.
2. Modify the column width and its data type.
Ans:
Problem 1.4: Create dept table with the following structure.
Name
Type
Rajalakshmi Engineering college
Page 8
Rajalakshmi Engineering College
--------------------------------DEPTNO
DNAME
LOC
--------------------------NUMBER(2)
VARCHAR2(10)
VARCHAR2(10)
Deptno as the primarykey
Solution:
1. Understand create table syntax.
2. Decide the name of the table.
3. Decide the name of each column and its data type.
4. Use the create table syntax to create the said tables.
5. Create primary key constraint for each table as understand from logical table
structure.
Ans:
Problem 1.5: Add constraints to the emp table that empno as the primary key and
deptno as the foreign key.
Solution:
1. Learn alter table syntax.
2. Define the new constraint [type, name, columns effected]
3. Use the alter table syntax for adding constraints.
Ans:
Problem 1.6: Add constraints to the emp table to check the empno value while entering
(i.e) empno > 100.
Solution:
1. Learn alter table syntax.
2. Define the new constraint [type, name, columns effected]
3. Use the alter table syntax for adding constraints.
Ans:
Problem 1.7: Salary value by default is 5000, otherwise as entered values
Solution:
1. Learn alter table syntax.
P.KUMAR, AP-IT, REC
Page 9
CS2258 DATABASE MANAGEMENT SYSTEMS LAB MANUAL
2. Define the new constraint [type, name, columns effected]
3. Use the alter table syntax for adding constraints.
Ans:
Problem 1.8: Add columns Dob to the emp table.
Solution:
1. Learn alter table syntax.
2. Define the new column and its data type.
3. Use the alter table syntax.
Ans:
Problem 1.9: Add and drop a column DOJ to the emp table.
Solution:
4. Learn alter table syntax.
5. Define the new column and its data type.
6. Use the alter table syntax to drop the column.
Ans:
Problem 1.10: Insert few rows and truncate those from the emp1 table and also drop
it..(pseudo table)
Solution:
7. create a pseudo table emp1 from emp
8. truncate values.
9. drop the table.
Ans:
2. Data Manipulation Language (DML) commands in RDBMS.
Rajalakshmi Engineering college
Page 10
Rajalakshmi Engineering College
DML commands are the most frequently used SQL commands and is used to query and
manipulate the existing database objects. Some of the commands are
o Insert
o Select
o Update
o Delete
Insert Command
This is used to add one or more rows to a table. The values are separated by commas and
the data types char and date are enclosed in apostrophes. The values must br entered in
the same order as they are defined.
Inserting a single row into a table:
Syntax: insert into <table name> values (value list)
Example: insert into s values(‘s3’,’sup3’,’blore’,10)
Inserting more than one record using a single insert commands:
Syntax: insert into <table name> values (&col1, &col2, ….)
Example: Insert into stud values(&reg, ‘&name’, &percentage);
Skipping the fields while inserting:
Insert into <tablename(coln names to which datas to b inserted)> values (list of values);
Other way is to give null while passing the values.
Select Commands
It is used to retrieve information from the table.it is generally refered to as querying the
table.We can either display all columns in a table or only specify column from the table.
Syntax: Select * from tablename; // This query selects all rowsfrom the table.
Example; Select * from IT;
The retrieval of specific columns from a table:
It retrieves the specified columns from the table
Syntax: Select column_name1, …..,column_namen from table name;
Example: Select empno, empname from emp;
Elimination of duplicates from the select clause:
It prevents retriving the duplicated values .Distinct keyword is to be used.
Syntax: Select DISTINCT col1, col2 from table name;
Example: Select DISTINCT job from emp;
P.KUMAR, AP-IT, REC
Page 11
CS2258 DATABASE MANAGEMENT SYSTEMS LAB MANUAL
Select command with where clause:
To select specific rows from a table we include ‘where’ clause in the select command. It
can appear only after the ‘from’ clause.
Syntax: Select column_name1, …..,column_namen from table name where condition;
Example: Select empno, empname from emp where sal>4000;
Select command with order by clause:
Syntax: Select column_name1, …..,column_namen from table name where condition order
by colmnname;
Example: Select empno, empname from emp order by empno;
Select command to create a table:
Syntax: create table tablename as select * from existing_tablename;
Example: create table emp1 as select * from emp;
Select command to insert records:
Syntax: insert into tablename ( select columns from existing_tablename);
Example: insert into emp1 ( select * from emp);
Update Command
It is used to alter the column values in a table. A single column may be updated or more
than one column could be updated.
Syntax:update tablename set field=values where condition;
Example:Update emp set sal = 10000 where empno=135;
Delete command
After inserting row in a table we can also delete them if required. The delete command
consists of a from clause followed by an optional where clause.
Syntax: Delete from table where conditions;
Example:delete from emp where empno=135;
Problem 2.1: Insert 5 records into dept table.
Solution:
1. Decide the data to add in dept.
Rajalakshmi Engineering college
Page 12
Rajalakshmi Engineering College
2. Add to dept one row at a time using the insert into syntax.
Ans:
DNAME
DEPTNO
-------- ---------- -------
10
20
30
40
50
DLOC
-- ---------- --------------
MANAGEMENT
DEVELOPMENT
MAINTAINANCE
TRANSPORT
SALES
MAIN BLOCK
MANUFACTURING UNIT
MAIN BLOCK
ADMIN BLOCK
HEAD OFFICE
Problem 2.2: Insert 11 records into emp table.
Solution:
1. Decide the data to add in emp.
2. Add to emp one row at a time using the insert into syntax.
Ans:
EMPNO ENAME JOB
MGR
DOB
SAL COMM DEPTNO
-------- ---------- --------- ---------- --------- ---------- ---------- ---------- ---------- ----------------7369 SMITH
CLERK
7566
17-DEC-80 800
0
20
7399
ASANT SALESMAN 7566
20-FEB-81 1600 300
20
7499
ALLEN SALESMAN 7698
20-FEB-81 1600 300
30
7521
WARD SALESMAN 7698
22-FEB-82 1250 500
30
7566
JONES MANAGER 7839
02-APR-81 5975 500
20
7698
BLAKE MANAGER 7839
01-MAY-79 9850 1400
30
7611 SCOTT HOD
7839
12-JUN-76 3000
10
7839 CLARK CEO
16-MAR-72 9900
10
7368 FORD
SUPERVIS 7366
17-DEC-80 800
0
20
7599
ALLEY SALESMAN 7698
20-FEB-81 1600 300
30
7421
DRANK CLERCK
7698
22-JAN-82 1250 500
30
Problem 2.3: Update the emp table to set the default commission of all employees to Rs
1000/- who are working as managers
Solution:
P.KUMAR, AP-IT, REC
Page 13
CS2258 DATABASE MANAGEMENT SYSTEMS LAB MANUAL
1. Learn update table syntax.
2. Update the default commission as Rs 1000/Ans:
Problem 2.4: Create a pseudo table employee with the same structure as the table emp
and insert rows into the table using select clauses.
Solution:
1. Create a table employee as emp.
2. Use Select clause to perform this.
Ans:
Problem 2.5: Delete only those who are working as supervisors.
Solution:
1. Delete the employee whose job is supervisor.
Ans:
Problem 2.6: Delete the rows whose empno is 7599.
Solution:
1. Delete the employee whose empno is 7599.
Ans:
Problem 2.7: List the records in the emp table orderby salary in ascending order.
Solution:
1. Use the orderby function in select clause.
Ans:
Rajalakshmi Engineering college
Page 14
Rajalakshmi Engineering College
Problem 2.8: List the records in the emp table orderby salary in descending order.
Solution:
1. Use the orderby function in select clause.
Ans:
Problem 2.9: Display only those employees whose deptno is 30.
Solution:
1.
2.
3.
4.
Use SELECT FROM WHERE syntax.
select should include all in the given format.
from should include employee
where should include condition on deptn0 = 30.
Ans:
Problem 2.10: Display deptno from the table employee avoiding the duplicated values.
Solution:
1. Use SELECT FROM syntax.
2. select should include distinct clause for the deptno.
3. from should include employee
Ans:
Problem 2.11: List the records in sorted order of their employees.
Solution:
1.
2.
3.
4.
Use SELECT FROM syntax.
select should include all in the given format.
from should include employee
Use the order by function empname.
Ans:
Problem 2.12: create a manager table from the emp table which should hold details
aonly about the managers.
Solution:
P.KUMAR, AP-IT, REC
Page 15
CS2258 DATABASE MANAGEMENT SYSTEMS LAB MANUAL
1.
2.
3.
4.
Use CREATE as SELECT FROM syntax.
select should include all in the given format.
from should include employee
Use the where clause to filter out only managers.
Ans:
Problem 2.13: List the employee names whose commission is null.
Solution:
1.
2.
3.
4.
Use SELECT FROM syntax.
select should include all in the given format.
from should include employee
Use the where clause to do filtering.
Ans:
Problem 2.14: List the employee names and the department name in which they are
working.
Solution:
5.
6.
7.
8.
Use SELECT FROM syntax.
select should include all in the given format.
from should include employee
Use the where clause to do filtering.
Ans:
3. In Built functions in RDBMS.
Functions
Rajalakshmi Engineering college
Page 16
Rajalakshmi Engineering College
Function accept zero or more arguments and both return one or more results. Both are
used to manipulate individual data items.Operators differ from functional in that they
follow the format of function_name(arg..). An argument is a user defined variables or
constants. Most operators accept at most 2 arguments while the structure of functions
permit to accept 3 or more arguments. Function can be classifies into single row function
and group functions.
Single Row functions
A single row function or scalar function returns only one value for every row queries in
table. Single row function can appear in a select command and can also be included in a
where clause. The single row function can be broadly classified as,
o Date Function
o Numeric Function
o Character Function
o Conversion Function
o Miscellaneous Function
The example that follows mostly uses the symbol table “dual”. It is a table, which is
automatically created by oracle along with the data dictionary.
Date Function
They operate on date values and produce outputs, which also belong to date data type
except for months, between, date function returns a number.
1. Add_month
This function returns a date after adding a specified date with specified number of months.
Syntax: Add_months(d,n);
where d-date n-number of months
Example: Select add_months(sysdate,2) from dual;
2. last_day
It displays the last date of that month.
Syntax: last_day (d);
where d-date
Example: Select last_day (‘1-jun-2009’) from dual;
2. Months_between
It gives the difference in number of months between d1 & d2.
Syntax: month_between (d1,d2);
P.KUMAR, AP-IT, REC
where d1 & d2 -dates
Page 17
CS2258 DATABASE MANAGEMENT SYSTEMS LAB MANUAL
Example: Select month_between (‘1-jun-2009’,’1-aug-2009’) from dual;
4. next_day
It returns a day followed the specified date.
Syntax: next_day (d,day);
Example: Select next_day (sysdate,’wednesday’) from dual
5. round
This function returns the date, which is rounded to the unit specified by the format model.
Syntax : round (d,[fmt]);
where d- date, [fmt] – optional. By default date will be rounded to the nearest day
Example: Select round (to_date(‘1-jun-2009’,’dd-mm-yy’),’year’) from dual;
Select round (‘1-jun-2009’,’year’) from dual;
Numerical Functions
Command
Query
Output
Abs(n)
Select abs(-15) from dual;
15
Ceil(n)
Select ceil(55.67) from dual;
56
Exp(n)
Select exp(4) from dual;
54.59
Floor(n)
Select floor(100.2) from dual;
100
Power(m,n)
Select power(4,2) from dual;
16
Mod(m,n)
Select mod(10,3) from dual;
1
Round(m,n)
Select round(100.256,2) from dual;
100.26
Trunc(m,n)
Select trunc(100.256,2) from dual;
100.23
Sqrt(m,n)
Select sqrt(16) from dual;
4
Character Functions
Command
initcap(char);
Query
select initcap(“hello”) from dual;
Rajalakshmi Engineering college
Output
Hello
Page 18
Rajalakshmi Engineering College
lower (char);
upper (char);
select lower (‘HELLO’) from dual;
select upper (‘hello’) from dual;
hello
HELLO
ltrim (char,[set]);
select ltrim (‘cseit’, ‘cse’) from dual;
it
rtrim (char,[set]);
select rtrim (‘cseit’, ‘it’) from dual;
cse
replace (char,search string,
replace string);
select replace (‘jack and jue’, ‘j’, ‘bl’) from
dual;
black and
blue
substr (char,m,n);
select substr (‘information’, 3, 4) from dual;
form
Conversion Function
1. to_char()
Syntax: to_char(d,[format]);
This function converts date to a value of varchar type in a form specified by date format. If
format is negelected then it converts date to varchar2 in the default date format.
Example: select to_char (sysdate, ’dd-mm-yy’) from dual;
2. to_date()
Syntax: to_date(d,[format]);
This function converts character to date data format specified in the form character.
Example: select to_date(‘aug 15 2009’,’mm-dd-yy’) from dual;
Miscellaneous Functions
1. uid – This function returns the integer value (id) corresponding to the user currently
logged in.
Example: select uid from dual;
2. user – This function returns the logins user name.
P.KUMAR, AP-IT, REC
Page 19
CS2258 DATABASE MANAGEMENT SYSTEMS LAB MANUAL
Example: select user from dual;
2. nvl – The null value function is mainly used in the case where we want to consider null
values as zero.
Syntax; nvl(exp1, exp2)
If exp1 is null, return exp2. If exp1 is not null, return exp1.
Example: select custid, shipdate, nvl(total,0) from order;
4. vsize: It returns the number of bytes in expression.
Example: select vsize(‘tech’) from dual;
Group Functions
A group function returns a result based on group of rows.
1. avg
Example: select avg (total) from student;
2.max
Example: select max (percentagel) from student;
2.min
Example: select min (marksl) from student;
4. sum
Example: select sum(price) from product;
Count Function
In order to count the number of rows, count function is used.
1. count(*) – It counts all, inclusive of duplicates and nulls.
Rajalakshmi Engineering college
Page 20
Rajalakshmi Engineering College
Example: select count(*) from student;
2. count(col_name)– It avoids null value.
Example: select count(total) from order;
2. count(distinct col_name) – It avoids the repeated and null values.
Example: select count(distinct ordid) from order;
Group by clause
This allows us to use simultaneous column name and group functions.
Example: Select max(percentage), deptname from student group by deptname;
Having clause
This is used to specify conditions on rows retrieved by using group by clause.
Example: Select max(percentage), deptname from student group by deptname having
count(*)>=50;
Special Operators:
In / not in – used to select a equi from a specific set of values
Any - used to compare with a specific set of values
Between / not between – used to find between the ranges
Like / not like – used to do the pattern matching
Problem 3.1: Select all employees from department numbers 7369,7499.
Solution:
1. Use select from where clause with the from coming from emp and dept tables and a
condition joining these two table using the key deptno which connects both the
tables with an equality condition.
Ans:
P.KUMAR, AP-IT, REC
Page 21
CS2258 DATABASE MANAGEMENT SYSTEMS LAB MANUAL
Problem 3.2: Display all the details of the records whose employee name starts with
‘S’.
Solution:
1.
2.
3.
4.
Use SELECT FROM WHERE syntax.
select should include all in the given format.
from should include employee
where should include condition on empname like ‘s%’.
Ans:
Problem 3.3: Display all the details of the records whose employee name does not
starts with ‘S’.
Solution:
5.
6.
7.
8.
Use SELECT FROM WHERE syntax.
select should include all in the given format.
from should include employee
where should include condition on empname not like ‘s%’.
Ans:
Problem 3.4: Display the rows whose empno ranges from 7500 to 7600.
Solution:
1.
2.
3.
4.
Use SELECT FROM WHERE syntax.
select should include all in the given format.
from should include employee
where should include condition between 7500 and 7600.
Ans:
Problem 3.5: Display the rows whose empno not in range from 7500 to 7600.
Solution:
5. Use SELECT FROM WHERE syntax.
6. select should include all in the given format.
7. from should include employee
Rajalakshmi Engineering college
Page 22
Rajalakshmi Engineering College
8. where should include condition not between 7500 and 7600.
Ans:
Problem 3.6: Calculate the square root of the salary of all employees.
Solution:
1. Use the sqrt function in select clause for the salary of all employees.
Ans:
Problem 3.7: Count the total records in the emp table.
Solution:
1. Use SELECT FROM syntax.
2. Use count function to find the total number of records.
Ans:
Problem 3.8: Calculate the total and average salary amount of the emptable.
Solution:
1. Use the sum and AVG aggregate function in select clause.
Ans:
Problem 3.9: Determine the max and min salary and rename the column as max_salary
and min_salary.
Solution:
1. Use the MIN & MAX aggregate function in select clause.
2. Rename the column as min_sal & max_sal.
P.KUMAR, AP-IT, REC
Page 23
CS2258 DATABASE MANAGEMENT SYSTEMS LAB MANUAL
Ans:
Problem 3.10: Display total salary spent for employees.
Solution:
1. Use SELECT FROM syntax.
2. select should job and total salary.
3. from should include emp
Ans: select sum (sal) from emp ;
Problem 3.11: Display total salary spent for each job category.
Solution:
4.
5.
6.
7.
Use SELECT FROM syntax.
select should job and total salary.
from should include emp
Group by job.
Ans:
Problem 3.12: Display the month name of date “14-jul-09” in full.
Solution:
1. Use SELECT FROM syntax.
2. select should include the date.
3. Convert the date to character.
Ans:
Problem 3.13: Display the Dob of all employees in the format “dd-mm-yy”.
Solution:
1. Use SELECT FROM syntax.
2. select should include the DOB in the format given.
Rajalakshmi Engineering college
Page 24
Rajalakshmi Engineering College
Ans:
Problem 3.14: Display the date two months after the Dob of employees.
Solution:
1. Use SELECT FROM syntax.
2. select should add 2 months after DOB.
Ans:
Problem 3.15: Display the last date of that month in “05-Oct-09”.
Solution:
1. Use SELECT FROM syntax.
2. select should display the last date of this month.
Ans:
Problem 3.16: Display the rounded date in the year format, month format, day format
in the employees.
Solution:
1. Use SELECT FROM syntax.
2. Select should round the date from emp.
Ans:
Problem 3.17: Display the date 60 days before current date.
Solution:
1. Use SELECT FROM syntax.
2. select should display the 60 days before the current date.
Ans:
P.KUMAR, AP-IT, REC
Page 25
CS2258 DATABASE MANAGEMENT SYSTEMS LAB MANUAL
Problem 3.18: List all employee names , salary and 15% rise in salary.
Solution:
1. Use select from clause and arithmetic to compute 15% rise in salary.
Ans:
Problem 3.19: List all employees which starts with either B or C.
Solution:
1.
2.
3.
4.
Use SELECT FROM WHERE syntax.
select should include all in the given format.
from should include emp
where should include condition on empname like ‘b%’ or ‘c%’.
Ans:
Problem 3.20: Display lowest paid employee details under each manager.
Solution:
1. Use SELECT FROM WHERE GROUPBY syntax.
2. select should include ename and minimum salary.
3. from should include emp
4. where should include condition on minimum salary.
5. Groupby manager.
Ans
Problem 3.21: Display number of employees working in each department and their
department name.
Solution:
1. use SELECT FROM WHERE GROUPBY syntax.
2. select should include dname and no.of employees.
3. from should include emp
4. where should include condition on emp.deptno=dept.deptno
5. Groupby dname
Rajalakshmi Engineering college
Page 26
Rajalakshmi Engineering College
Ans:
Problem 3.22: Display the employee names whose name contains up to 5 characters.
Solution:
1. use SELECT FROM WHERE syntax.
2. select should include empname .
3. from should include emp
4. where should include condition on length of the name should be <=5.
Ans:
Problem 3.23: List all employee names and their manager whose manager is 77499 or
7566 0r 7611.
Solution:
1. Use select from clause.
2. Use in keyword to match from the given values.
Ans:
Problem3.24: Find how many job titles are available in employee table.
Solution:
3. Use select from clause.
4. Use count function to get the result.
Ans:
Problem 3.25 : What is the difference between maximum and minimum salaries of
employees in the organization?
Solution:
5. Use select from clause.
6. Use function max(),min() and find the difference between them to get the result.
Ans:
P.KUMAR, AP-IT, REC
Page 27
CS2258 DATABASE MANAGEMENT SYSTEMS LAB MANUAL
Problem 3.26: Find no.of dept in employee table.
Solution:
7. Use select from clause.
8. Use count and distinctkeys in select clause to get the result.
Ans:
Problem 3.27: Display the names and dob of all employees who were born in Feburary.
INPUT SQL>
Solution:
9. Use select from clause.
10. Use to_char() to get the result.
Ans:
Problem 3.28: List out the employee names who will celebrate their birthdays during
current month.
Solution:
11.Use select from clause.
12. Use to_char functions on name in select clause to get the result.
Ans:
Problem 3.29: List out the employee names whose names starts with s and ends with
h.
Solution:
13.Use select from clause.
14.Use like operator with pattern matching to get the result.
Ans:
Rajalakshmi Engineering college
Page 28
Rajalakshmi Engineering College
Problem 3.30: List out the employee names whose salary is greater than 5000,6000
Solution:
15.Use select from clause.
16.Use any operator to get the result.
Ans:
4. Nested Queries & Joins in RDBMS.
Nested Queries:
Nesting of queries one within another is known as a nested queries.
Subqueries
The query within another is known as a subquery. A statement containing subquery is
called parent statement. The rows returned by subquery are used by the parent statement.
P.KUMAR, AP-IT, REC
Page 29
CS2258 DATABASE MANAGEMENT SYSTEMS LAB MANUAL
Example: select ename, eno, address where salary >(select salary from employee where
ename =’jones’);
Types
1. Subqueries that return several values
Subqueries can also return more than one value.such results should be made use along with
the operators in and any.
Example: select ename, eno, from employee where salary <any (select salary from
employee where deptno =10’);
2. Multiple queries
Here more than one subquery is used. These multiple subqueries are combined by means of
‘and’ & ‘or’ keywords.
3. Correlated subquery
A subquery is evaluated once for the entire parent statement whereas a correlated
subquery is evaluated once per row processed by the parent statement.
Example: select * from emp x where x.salary > (select avg(salary) from emp where
deptno =x.deptno);
Above query selects the employees details from emp table such that the salary of employee
is > the average salary of his own department.
Relating Data through Join Concept
The purpose of a join concept is to combine data spread across tables. A join is actually
performed by the ‘where’ clause which combines specified rows of tables.
Syntax; select columns from table1, table2 where logical expression;
Types of Joins
1. Simple Join
2. Self Join
2. Outer Join
Rajalakshmi Engineering college
Page 30
Rajalakshmi Engineering College
Simple Join
It is the most common type of join. It retrieves the rows from 2 tables having a common
column and is further classified into
a) Equi-join
A join, which is based on equalities, is called equi-join.
Example: select * from item, cust where item.id=cust.id;
In the above statement, item-id = cust-id performs the join statement. It retrieves rows
from both the tables provided they both have the same id as specified by the where clause.
Since the where clause uses the comparison operator (=) to perform a join, it is said to be
equijoin. It combines the matched rows of tables.
It can be used as follows:
o To insert records in the target table.
o To create tables and insert records in this table.
o To update records in the target table.
o To create views.
b) Non Equi-join
It specifies the relationship between columns belonging to different tables by making use of
relational operators other than’=’.
Example: select * from item, cust where item.id<cust.id;
Table Aliases
Table aliases are used to make multiple table queries shorted and more readable. We give
an alias name to the table in the ‘from’ clause and use it instead of the name throughout
the query.
Self join
Joining of a table to itself is known as self-join. It joins one row in a table to another. It
can compare each row of the table to itself and also with other rows of the same table.
Example: select * from emp x ,emp y where x.salary >= (select avg(salary) from x.emp
where x. deptno =y.deptno);
Outer Join
It extends the result of a simple join. An outer join returns all the rows returned by simple
join as well as those rows from one table that do not match any row from the table. The
symbol(+) reprsents outer join.
P.KUMAR, AP-IT, REC
Page 31
CS2258 DATABASE MANAGEMENT SYSTEMS LAB MANUAL
Example: select ename, job, dname from emp, dept where emp.deptno (+) =
dept.deptno;
-------------------------------------------------------------------------------------------------------Problem 4.1: Select all employees from ‘maintainance’ and ‘development’ dept.
Solution:
1. Use select from where clause with the from coming from emp and dept tables and a
condition joining these two table using the key deptno which connects both the
tables with an equality condition.
Ans:
Problem 4.2: Display all employee names and salary whose salary is greater than
minimum salary of the company and job title starts with ‘M’.
Solution:
1. Use select from clause.
2. Use like operator to match job and in select clause to get the result.
Ans:
Problem 4.3: Issue a query to find all the employees who work in the same job as jones.
Ans
Problem 4.4: Issue a query to display information about employees who earn more than
any employee in dept 30.
Ans
Problem 4.5: Display the employees who have the same job as jones and whose salary
>= fords.
Ans:
Rajalakshmi Engineering college
Page 32
Rajalakshmi Engineering College
Problem 4.6: Write a query to display the name and job of all employees in dept 20 who
have a job that someone in the Management dept as well.
Ans:
Problem 4.7: Issue a query to list all the employees who salary is > the average salary of
their own dept.
Ans:
Problem 4.8: Write a query that would display the empname, job where each employee
works and the name of their dept.
Ans:
Problem 4.9: Write a query to list the employees having the same job as employees
located in ‘ mainblock’.(use multiple subquery)
Ans:
Problem 4.10: Write a query to list the employees in dept 10 with the same job as
anyone in the development dept.
Ans:
Problem 4.11: Write a query to list the employees with the same job and salary as
‘ford’.
Ans:
Problem 4.12: Write a query to list all depts. with at least 2 salesman.
Ans:
P.KUMAR, AP-IT, REC
Page 33
CS2258 DATABASE MANAGEMENT SYSTEMS LAB MANUAL
Problem 4.13: Write a query to list the employees in dept 20 with the same job as
anyone in dept 30.
Ans:
Problem 4.14: List out the employee names who get the salary greater than the
maximum salaries of dept with dept no 20,30
Ans:
Problem 4.15: Display the maximum salaries of the departments whose maximum
salary is greater than 9000.
Solution:
1. Use select from clause.
2. Use group by and having functions on name in select clause to get the result.
Ans:
Problem 4.16: Display the maximum salaries of the departments whose minimum
salary is greater than 1000 and lesser than 5000.
Solution:
1. Use select from clause.
2. Use group by and having functions on name in select clause to get the result.
Ans;
JOINS
Create the following table :
AccDept.( Accredited Department by quality council)
DNAME
DEPTNO
-------- ---------- -------
10
20
30
DCity
-- ---------- --------------
MANAGEMENT
DEVELOPMENT
MAINTAINANCE
MAIN BLOCK
MANUFACTURING UNIT
MAIN BLOCK
Rajalakshmi Engineering college
Page 34
Rajalakshmi Engineering College
EQUI-JOIN
~~~~~~~~~
Problem 4.17: Display the departments that are accredited by the quality council.
Solution:
1. Use select from clause.
2. Use equi join in select clause to get the result.
Ans
NON-EQUIJOIN
~~~~~~~~~~~~
Problem 4.18: Display the employees of departments which are not accredited by the
quality council
Solution:
1. Use select from clause.
2. Use non equi join in select clause to get the result.
Ans:
LEFTOUT-JOIN
~~~~~~~~~~~~
Problem 4.19: Display all the employees and the departments implementing a left
outer join.
Solution:
1. Use select from clause.
2. Use left outer join in select clause to get the result.
Ans:
P.KUMAR, AP-IT, REC
Page 35
CS2258 DATABASE MANAGEMENT SYSTEMS LAB MANUAL
RIGHTOUTER-JOIN
~~~~~~~~~~~~~~~
Problem 4.20: Display the employee name and department name in which they are
working implementing a right outer join.
Solution:
1. Use select from clause.
2. Use right outer join in select clause to get the result.
Ans:
FULLOUTER-JOIN
~~~~~~~~~~~~~~
Problem 4.21: Display the employee name and department name in which they are
working implementing a full outer join.
Solution:
1. Use select from clause.
2. Use full outer join in select clause to get the result.
Ans:
SELFJOIN
~~~~~~~~~~~
Problem 4.22: Write a query to display their employee names and their managers
name.
Ans:
Rajalakshmi Engineering college
Page 36
Rajalakshmi Engineering College
Problem 4.23: Write a query to display their employee names and their managers salary
for every employee .
Ans
Problem 4.24: Write a query to output the name , job, empno, deptname and location
for each dept, even if there are no employees.
Ans:
Problem 4.25: Find the name of the manager for each employee. Include the following
in the output: empno, empname, job and his manager’s name.
Ans:
Problem 4.26: Display the details of those who draw the same salary.
Ans:
5. Set operators & Views in RDBMS.
SetOperators:
The Set operator combines the result of 2 queries into a single result.The following are the
operators:
• Union
• Union all
P.KUMAR, AP-IT, REC
Page 37
CS2258 DATABASE MANAGEMENT SYSTEMS LAB MANUAL
•
•
Intersect
Minus
The rules to which the set operators are strictly adhere to :
• The queries which are related by the set operators should have a same number
of column and column definition.
• Such query should not contain a type of long.
• Labels under which the result is displayed are those from the first select
statement.
Union:
Returns all distinct rows selected by both the queries
Syntax:
Query1 Union Query2;
Union all:
Returns all rows selected by either query including the duplicates.
Syntax:
Query1 Union all Query2;
Intersect:
Returns rows selected that are common to both queries.
Syntax:
Query1 Intersect Query2;
Intersect:
Returns all distinct rows selected by the first query and are not by the second
Syntax:
Query1 minus Query2;
Rajalakshmi Engineering college
Page 38
Rajalakshmi Engineering College
Problem 5.1: Display all the dept numbers available with the dept and accdept tables
avoiding duplicates.
Solution:
1. Use select from clause.
2. Use union select clause to get the result.
Ans:
Problem 5.2: Display all the dept numbers available with the dept and accdept tables.
Solution:
1. Use select from clause.
2. Use union all in select clause to get the result.
Ans:
Problem 5.3: Display dept no available in both the dept and acc dept tables.
Solution:
1. Use select from clause.
2. Use intersect in select clause to get the result.
Ans:
Problem 5.4: Display all the dept numbers available in dept and not in accdept tables.
Solution:
1. Use select from clause.
2. Use full outer join in select clause to get the result.
Ans:
P.KUMAR, AP-IT, REC
Page 39
CS2258 DATABASE MANAGEMENT SYSTEMS LAB MANUAL
Views:
A view is the tailored presentation af data contained in one or more table and can also be
said as restricted view to the datas in the tables. A view is a “virtual table” or a “stored
query” which takes the output of a query and treats it as a table.
The table upon which a view is created is called as base table.
A view is a logical table based on a table or another view. A view contains no data of its
own but is like a window through which data from tables can be viewed or changed. The
tables on which a view is based are called base tables. The view is stored as a SELECT
statement in the data dictionary
Advantages of a view:
a.
b.
c.
d.
Additional level of table security.
Hides data complexity.
Simplifies the usage by combinig multiple tables into a single table.
Provides datas in different perspective.
Syntax:
Create [or replace ] view <view name> [column alis names] as <query> [with <options>
conditions];
Example:
Create or replace view empview as select * from emp;
Types of view:
Horizontal  enforced by where cause
Vertical  enforced by selecting the required columns
Problem 5.5: The organization wants to display only the details of the employees
those who are managers.( horizontal portioning)
Solution:
1. Create a view on emp table named managers
2. Use select from clause to do horizontal partioning
Ans:
Problem 5.6:
The organization wants to display only the details
empno,empname,deptno,deptname of the employees .(vertical portioning)
Rajalakshmi Engineering college
Page 40
like
Rajalakshmi Engineering College
Solution:
1. Create a view on emp table named general
2. Use select from clause to do vertical partioning
Ans:
Problem 5.7:
The organization wants to display only the details like
empno,empname,deptno,deptname of the all the employees except the HOD and CEO .
(full portioning)
Solution:
3. Create a view on emp table named all
4. Use select from clause to do vertical partioning
Ans:
Problem 5.8: Display all the views generated.
Ans:
Problem 5.9: Execute the DML commands on the view created.
Ans:
Problem 5.10: Drop a view.
Ans:
P.KUMAR, AP-IT, REC
Page 41
CS2258 DATABASE MANAGEMENT SYSTEMS LAB MANUAL
6. Control Structures
In addition to SQL commands,PL/SQL can also process data usin flow of statements.the flow of
control statements are classified into the following categories.
•
•
•
Conditional control -Branching
Iterative control - looping
Sequential control
BRANCHING in PL/SQL:
Sequence of statements can be executed on satisfying certain condition .
If statements are being used and different forms of if are:
1.Simple IF
2.ELSIF
3.ELSE IF
SIMPLE IF:
Syntax:
Rajalakshmi Engineering college
Page 42
Rajalakshmi Engineering College
IF condition THEN
statement1;
statement2;
END IF;
IF-THEN-ELSE STATEMENT:
Syntax:
IF condition THEN
statement1;
ELSE
statement2;
END IF;
ELSIF STATEMENTS:
Syntax:
IF condition1 THEN
statement1;
ELSIF condition2 THEN
statement2;
ELSIF condition3 THEN
statement3;
ELSE
statementn;
END IF;
NESTED IF :
Syntax:
IF condition THEN
statement1;
ELSE
IF condition THEN
statement2;
ELSE
statement3;
END IF;
END IF;
ELSE
statement3;
END IF;
SELECTION IN PL/SQL(Sequential Controls)
P.KUMAR, AP-IT, REC
Page 43
CS2258 DATABASE MANAGEMENT SYSTEMS LAB MANUAL
SIMPLE CASE
Syntax:
CASE SELECTOR
WHEN Expr1 THEN statement1;
WHEN Expr2 THEN statement2;
:
ELSE
Statement n;
END CASE;
SEARCHED CASE:
CASE
WHEN searchcondition1 THEN statement1;
WHEN searchcondition2 THEN statement2;
:
:
ELSE
statementn;
END CASE;
ITERATIONS IN PL/SQL
Sequence of statements can be executed any number of times using loop construct.
It is broadly classified into:
• Simple Loop
• For Loop
• While Loop
SIMPLE LOOP
Syntax:
LOOP
statement1;
EXIT [ WHEN Condition];
END LOOP;
Example:
Declare
A number:=10;
Begin
Loop
Rajalakshmi Engineering college
Page 44
Rajalakshmi Engineering College
a := a+25;
exit when a=250;
end loop;
dbms_output.put_line(to_char(a));
end;
/
WHILE LOOP
Syntax
WHILE condition LOOP
statement1;
statement2;
END LOOP;
Example:
Declare
i number:=0;
j number:=0;
begin
While i<=100 Loop
j := j+i;
i := i+2;
end loop;
dbms_output.put_line(‘the value of j is’ ||j);
end;
/
FOR LOOP
Syntax:
FOR counter IN [REVERSE]
LowerBound..UpperBound
LOOP
statement1;
statement2;
END LOOP;
Example:
Begin
For I in 1..2
Loop
Update emp set field = value where condition
End loop;
End;
/
Program 6.1:write a pl/sql program to swap two numbers with out taking third variable
P.KUMAR, AP-IT, REC
Page 45
CS2258 DATABASE MANAGEMENT SYSTEMS LAB MANUAL
declare
a number(10);
b number(10);
begin
a:=&a;
b:=&b;
dbms_output.put_line('THE PREV VALUES OF A AND B WERE');
dbms_output.put_line(a);
dbms_output.put_line(b);
a:=a+b;
b:=a-b;
a:=a-b;
dbms_output.put_line('THE VALUES OF A AND B ARE');
dbms_output.put_line(a);
dbms_output.put_line(b);
end;
OUTPUT:
SQL> @ SWAPPING.SQL
17 /
Enter value for a: 5
old 5: a:=&a;
new 5: a:=5;
Enter value for b: 3
old 6: b:=&b;
new 6: b:=3;
THE PREV VALUES OF A AND B WERE
5
3
THE VALUES OF A AND B ARE
3
5
PL/SQL procedure successfully completed.
Program 6.2:write a pl/sql program to swap two numbers by taking third variable
declare
a number(10);
b number(10);
c number(10);
begin
Rajalakshmi Engineering college
Page 46
Rajalakshmi Engineering College
dbms_output.put_line('THE PREV VALUES OF A AND B WERE');
dbms_output.put_line(a);
dbms_output.put_line(b);
a:=&a;
b:=&b;
c:=a;
a:=b;
b:=c;
dbms_output.put_line('THE VALUES OF A AND B ARE');
dbms_output.put_line(a);
dbms_output.put_line(b);
end;
OUTPUT:
SQL> @ SWAPPING2.SQL
19 /
Enter value for a: 5
old 6: a:=&a;
new 6: a:=5;
Enter value for b: 3
old 7: b:=&b;
new 7: b:=3;
THE PREV VALUES OF A AND B WERE
5
3
THE VALUES OF A AND B ARE
3
5
PL/SQL procedure successfully completed.
Program 6.3:
Write a pl/sql program to find the largest of two numbers
declare
a number;
b number;
begin
a:=&a;
b:=&b;
if a=b then
dbms_output.put_line('BOTH ARE EQUAL');
elsif a>b then
dbms_output.put_line('A IS GREATER');
else
P.KUMAR, AP-IT, REC
Page 47
CS2258 DATABASE MANAGEMENT SYSTEMS LAB MANUAL
dbms_output.put_line('B IS GREATER');
end if;
end;
OUTPUT:
SQL> @ GREATESTOF2.sql
13 /
Enter value for a: 5
old 5: a:=&a;
new 5: a:=5;
Enter value for b: 2
old 6: b:=&b;
new 6: b:=2;
A IS GREATER
PL/SQL procedure successfully completed.
Program 6.4:write a pl/sql program to find the total and average of 6 subjects and display the
grade
declare
java number(10);
dbms number(10);
co number(10);
se number(10);
es number(10);
ppl number(10);
total number(10);
avgs number(10);
per number(10);
begin
dbms_output.put_line('ENTER THE MARKS');
java:=&java;
dbms:=&dbms;
co:=&co;
se:=&se;
es:=&es;
ppl:=&ppl;
total:=(java+dbms+co+se+es+ppl);
per:=(total/600)*100;
Rajalakshmi Engineering college
Page 48
Rajalakshmi Engineering College
if java<40 or dbms<40 or co<40 or se<40 or es<40 or ppl<40 then
dbms_output.put_line('FAIL');
if per>75 then
dbms_output.put_line('GRADE A');
elsif per>65 and per<75 then
dbms_output.put_line('GRADE B');
elsif per>55 and per<65 then
dbms_output.put_line('GRADE C');
else
dbms_output.put_line('INVALID INPUT');
end if;
dbms_output.put_line('PERCENTAGE IS '||per);
dbms_output.put_line('TOTAL IS '||total);
end;
OUTPUT:
SQL> @ GRADE.sql
31 /
Enter value for java: 80
old 12: java:=&java;
new 12: java:=80;
Enter value for dbms: 70
old 13: dbms:=&dbms;
new 13: dbms:=70;
Enter value for co: 89
old 14: co:=&co;
new 14: co:=89;
Enter value for se: 72
old 15: se:=&se;
new 15: se:=72;
Enter value for es: 76
old 16: es:=&es;
new 16: es:=76;
Enter value for ppl: 71
old 17: ppl:=&ppl;
new 17: ppl:=71;
GRADE A
PERCENTAGE IS 76
TOTAL IS 458
PL/SQL procedure successfully completed.
Program 6.5:
Write a pl/sql program to find the sum of digits in a given number
P.KUMAR, AP-IT, REC
Page 49
CS2258 DATABASE MANAGEMENT SYSTEMS LAB MANUAL
declare
a number;
d number:=0;
sum1 number:=0;
begin
a:=&a;
while a>0
loop
d:=mod(a,10);
sum1:=sum1+d;
a:=trunc(a/10);
end loop;
dbms_output.put_line('sum is'|| sum1);
end;
OUTPUT:
SQL> @ SUMOFDIGITS.sql
16 /
Program 6.6:write a pl/sql program to display the number in reverse order
declare
a number;
rev number;
d number;
begin
a:=&a;
rev:=0;
while a>0
loop
d:=mod(a,10);
rev:=(rev*10)+d;
a:=trunc(a/10);
end loop;
dbms_output.put_line('no is'|| rev);
end;
OUTPUT:
SQL> @ REVERSE2.sql
16 /
Enter value for a: 536
old 6: a:=&a;
Rajalakshmi Engineering college
Page 50
Rajalakshmi Engineering College
new 6: a:=536;
no is635
PL/SQL procedure successfully completed.
Program 6.7:
Write a pl/sql program to check whether the given number is prime or not
declare
a number;
c number:=0;
i number;
begin
a:=&a;
for i in 1..a
loop
if mod(a,i)=0 then
c:=c+1;
end if;
end loop;
if c=2 then
dbms_output.put_line(a ||'is a prime number');
else
dbms_output.put_line(a ||'is not a prime number');
end if;
end;
OUTPUT:
SQL> @ PRIME.SQL
19 /
Enter value for a: 11
old 6: a:=&a;
new 6: a:=11;
11is a prime number
PL/SQL procedure successfully completed.
Program 6.8:
Write a pl/sql program to find the factorial of a given number
declare
P.KUMAR, AP-IT, REC
Page 51
CS2258 DATABASE MANAGEMENT SYSTEMS LAB MANUAL
n number;
f number:=1;
begin
n:=&n;
for i in 1..n
loop
f:=f*i;
end loop;
dbms_output.put_line('the factorial is'|| f);
end;
OUTPUT:
SQL> @ FACTORIAL.sql
12 /
Enter value for n: 5
old 5: n:=&n;
Program 6.9:write a pl/sql code block to calculate the area of a circle for a value of radius
varying from 3 to 7.
Store the radius and the corresponding values of calculated area in an empty table named
areas ,consisting of two columns radius & area
TABLE NAME:AREAS
RADIUS
AREA
SQL> create table areas(radius number(10),area number(6,2));
Table created.
--PROGRAM
declare
pi constant number(4,2):=3.14;
radius number(5):=3;
area number(6,2);
begin
while radius<7
loop
area:=pi*power(radius,2);
insert into areas values(radius,area);
radius:=radius+1;
end loop;
end;
Rajalakshmi Engineering college
Page 52
Rajalakshmi Engineering College
OUTPUT:
SQL> @ AREAOFCIRCLE.SQL
13 /
PL/SQL procedure successfully completed.
SQL> SELECT * FROM AREAS;
RADIUS
AREA
------------------3
28.26
4
50.24
5
78.5
6
113.04
Program 6.10:write a pl/sql code block that will accept an account number from the user,check if
the users balance is less than minimum balance,only then deduct rs.100/- from the balance.this
process is fired on the acct table.
SQL> create table acct(name varchar2(10),cur_bal number(10),acctno number(6,2));
SQL> insert into stud values('&sname',&rollno,&marks);
SQL> select * from acct;
ACCTNO
---------777
765
855
353
NAME
---------sirius
john
sam
peter
CUR_BAL
---------10000
1000
500
800
--PROGRAM
declare
mano number(5);
mcb number(6,2);
minibal constant number(7,2):=1000.00;
fine number(6,2):=100.00;
begin
mano:=&mano;
select cur_bal into mcb from acct where acctno=mano;
if mcb<minibal then
update acct set cur_bal=cur_bal-fine where acctno=mano;
end if;
end;
P.KUMAR, AP-IT, REC
Page 53
CS2258 DATABASE MANAGEMENT SYSTEMS LAB MANUAL
OUTPUT:
SQL> @ BANKACC.sql
13 /
Enter value for mano: 855
old 7: mano:=&mano;
new 7: mano:=855;
PL/SQL procedure successfully completed.
7. Procedures and Functions
A procedure is a block that can take parameters (sometimes referred to as arguments) and
be invoked.
Procedures promote reusability and maintainability. Once validated, they can be used in
number of applications. If the definition changes, only the procedure are affected, this
greatly simplifies maintenance.
Modularized program development:
• Group logically related statements within blocks.
• Nest sub-blocks inside larger blocks to build powerful programs.
• Break down a complex problem into a set of manageable well defined logical
modules and implement the modules with blocks.
Procedure and function blocks:
Procedure:
Rajalakshmi Engineering college
Page 54
Rajalakshmi Engineering College
-
No return.
PROCEDURE name IS
Function:
- Returns a value
- FUNCTION name RETURN data-type IS
Syntax for procedure: Create [or Replace] PROCEDURE procedur_name
(parameter1 [model1] datatype1,
(parameter2 [model2] datatype2,
…)
IS|AS
PL/SQL Block;
Example:
Create [or Replace] PROCEDURE leave_emp
(v_id IN emp.empno%TYPE)
IS
BEGIN
DELETE FROm emp
WHERE empno=v_id;
END leave_emp;
Syntax for function: Create [or Replace] function function_name
(parameter1 [model1] datatype1,
(parameter2 [model2] datatype2,
…) return type
IS|AS
PL/SQL Block;
Example:
Create [or Replace] PROCEDURE leave_emp
(v_id IN emp.empno%TYPE)
IS
BEGIN
DELETE FROm emp
WHERE empno=v_id;
END leave_emp;
6.1 Write a procedure to add an amount of Rs.1000 for the employees whose salaries is greater
than 5000 and who belongs to the deptno passed as an argument .
CODE:
P.KUMAR, AP-IT, REC
Page 55
CS2258 DATABASE MANAGEMENT SYSTEMS LAB MANUAL
6.2 Write a PL/SQL block to update the salary of the employee with a 10% increase whose
empno is to be passed as an argument for the procedure.
CODE:
6.3 Write a function to find the salary of the employee who is working in the deptno 20(to be
passed as an argument).
CODE:
Rajalakshmi Engineering college
Page 56
Rajalakshmi Engineering College
6.4 Write a function to find the nature of job of the employee whose deptno is 20(to be passed as
an argument)
CODE:
6.5 Write a PL/SQL block to obtain the department name of the employee who works for deptno
30.
P.KUMAR, AP-IT, REC
Page 57
CS2258 DATABASE MANAGEMENT SYSTEMS LAB MANUAL
8. Triggers
A trigger is a PL/SQL block or a PL/SQL procedure that executes implicitly whenever a
particular event takes place. It can either be:
1. Application trigger: Fires whenever an event occurs with a particular application.
2. Database Trigger: Fires whenever a data event (such as DML) occurs on a schema or
database.
Guidelines to Designing Triggers:
o Use the following guidelines when designing triggers.
o Use triggers to guarantee that when a specific operation is performed, related
actions are performed.
o Only use database triggers for centralized, global operations that should be fired for
the triggering statement, regardless of which user or application issues the
statement.
o Do not define triggers to duplicate or replace the functionality already built into the
oracle database. For example do not define trigger to implement integrity rules that
can be done by using declarative constraints.
Rajalakshmi Engineering college
Page 58
Rajalakshmi Engineering College
o The excessive use to triggers can result in complex interdependencies, which may be
difficult to maintain in large applications. Only use triggers when necessary, and
beware of recursive and cascading effects.
Elements in a Trigger:
• Trigger timing
o For table: BEFORE, AFTER
o For view: INSTEAD OF
• Trigger event: INSERT, UPDATE, OR DELETE
• Table name: On table, view
• Trigger Type: Row or statement
• When clause: Restricting condition
• Trigger body: PL/SQL block
“Before triggers” execute the trigger body before the triggering DML event on a table.
These are frequently used to determine whether that triggering statement should be
allowed to complete. This situation enables you to eliminate unnecessary processing of the
triggering statement and it eventual rollback in cases where an exception is raised in the
triggering action.
“After triggers” are used when the triggering statement is to be completed before the
triggering action and to perform a different action on the same triggering statement if a
BEFORE trigger is already present.
“Instead of Triggers” are used to provide a transparent way of modifying views that cannot
be modified directly through SQL DML statements because the view is not inherently
modifiable. You can write INSERT, UPDATE, and DELETE statements against the view. The
INSTEAD OF trigger works invisibly in the background performing the action coded in the
trigger body directly on the underlying tables.
Triggering user events:
o INSERT
o UPDATE
o DELETE
Trigger Components:
o Statement: The trigger body executes once for the triggering event. This is the
default. A statement trigger fires once, even if no rows are affected at all.
o Row: The trigger body executes once for each row affected by the triggering event.
A row trigger is not executed if the triggering event affects no rows.
Trigger Body:
The trigger body is a PL/SQL block or a call to a procedure.
P.KUMAR, AP-IT, REC
Page 59
CS2258 DATABASE MANAGEMENT SYSTEMS LAB MANUAL
Syntax:
CREATE [OR REPLACE] TRIGGER trigger_name
Timing
Event1 [OR event2 OR event3]
ON table_name
Trigger_body
Example: CREATE [OR REPLACE] TRIGGER secure_emp
Before insert on emp
BEGIN
IF(to_char(sysdate,’dy’) IN (‘SAT’,’SUN’)) OR
To_char(sysdate,’HH24’) NOT BETWEEN ‘08’ AND ‘18’)
THEN RAISE_APPLICATION_ERROR(-20500,
‘you may only insert into EMP during normal hours.’);
END IF;
END;
a.
CODE:
write a TRIGGER to ensure that DEPT TABLE does not contain duplicate of null
values in DEPTNO column.
Rajalakshmi Engineering college
Page 60
Rajalakshmi Engineering College
b.
Write a Trigger to carry out the following action: on deleting a deptno from dept table , all the records
with that deptno has to be deleted from the emp table
CODE:
c.
Write a Trigger to carry out the following action: on deleting any records from the emp table ,the same
values must be inserted into the log table.
Problem Statements for practise:
1. Create a trigger which writes a record called “employees table being changed” with time
in a log table whenever anyone attempts to change employees table.
Solution:
We want to write a statement trigger that records the fact that someone is changing the
employees table in a log table using before trigger.
2. Problem Statement:
Create a trigger which writes a record called “employees table has been changed” with
time in a log table whenever someone successfully changes the employee table.
Solution:
We want to write a statement trigger that records the fact that some-one changed the
employees table in a log table using after trigger that acts on insert, update and delete
operations.
3.Problem Statement:
Implement a solution that would record all attempted updates on salary in the employee
table along with the employee id, old salary, new salary and the time when it was
attempted in another table.
P.KUMAR, AP-IT, REC
Page 61
CS2258 DATABASE MANAGEMENT SYSTEMS LAB MANUAL
Solution:
Use row before trigger in update operation.
4.Problem Statement:
Implement a solution that would record all updates on salary in the employee table along
with the employee id, old salary, new salary and the time when it was updated in another
table.
Solution:
Use row after trigger in update operation.
5.Problem Statement:
Implement a solution to insert a log entry in log table whenever salary of employees with
more than 20000 is revised.
Solution:
Write a row after trigger on employee record.
The trigger should work on the condition that the salary of the record is greater than
20000.
8. Front End Tools
(Study about the tool –Visual Basic)
Rajalakshmi Engineering college
Page 62
Rajalakshmi Engineering College
9. Design and implementation of Payroll Processing System.
Aim:
Program to develop an application for Payroll Processing.
Modules:
1. Main Form: It includes the links to employee details, pay slip generation.
2. Employee Details Form: It includes the addition, deletion and modification of the
employee details. It also displays all the employees’ details.
2.1Operations Performed – Add, Edit, Save, Delete, Report, Exit
3. Salary Calculation Form: It includes the calculation of salary for a particular
employee. It also generates the pay slip.
2.1 Operations Performed – Add, Calculate, Save, Report, Exit
TABLE DESCRIPTION
1. Empdet – To maintain the employees’ details
P.KUMAR, AP-IT, REC
Page 63
CS2258 DATABASE MANAGEMENT SYSTEMS LAB MANUAL
Name
Type
Description
Empno*
Number(6)
Employee No
Empname
Varchar2(25)
Employee Name
DOB
Date
Date of Birth
DOJ
Date
Date Of Joining
Designation
Varchar2(20)
Designation
Basic Pay
Number(7,2)
Basic Pay
Address
Varchar(50)
Address
Pin
Number(6)
Pincode
Phone
Number(10)
Phone Number
Name
Type
Description
Empno
Number(6)
Employee No
Empname
Varchar2(25)
Employee Name
Month
Varchar2(10)
Month
Year
Number(4)
Year
Wday
Number(2)
No.of Working Days
EWday
Number(2)
No.of Worked Days
Basic Pay
Number(7,2)
Basic Pay
DA
Number(6,2)
Dearness Allowance
HRA
Number(6,2)
House Rent Allowance
CCA
Number(6,2)
City Compensation
PF
Number(6,2)
Provident Fund
IT
Number(6,2)
Income Tax
LP
Number(6,2)
Loss of pay
DED
Number(6,2)
Rajalakshmi Engineering college
GP
Number(9,2)
Deductions
NP
Number(9,2)
Gross Pay
Net pay
2. Salcal – To
maintain
the details
of pay slip
of an
employee.
Page 64
Rajalakshmi Engineering College
* write a PL/SQL block that calculates the salary and updates the table when a new entry
happens to the salcal table.
P.KUMAR, AP-IT, REC
Page 65