Anda di halaman 1dari 29

Bansilal Ramnath Agarwal Charitable Trusts

Vishwakarma Institute of Technology, Pune-37



Department Of Computer Engineering


Lab Manual

DBMS Lab

CS7015



Class: - MCAI Branch: - Computer
Prepared By: - Mrs. Neelam Chandolikar
Contributors: - S.G.Lade
Year: - 2009-10
Examinations: - Practical
Required H/W and S/W: - Any H/W running Windows And
Oracle.


Contents

Sr.
No.
Name
1 SQL queries : DDL Commands
2 SQL queries: DML Commands
3 SQL queries: Select with operators like arithmetic, comparison, logical Query
Expression, operators, Ordering the records with order by
4 SQL queries: Grouping the records ,Group functions: Avg, max, min, sum, count, Set
operations : Union, Union all, intersect, minus
5 SQL queries: J oin concept: Simple, equi, non equi, self, outer join
6 SQL queries : Sub queries
7 SQL queries: Sub queries
8 SQL :Sequence ,Synonym ,index, view
9 PL/SQL code for Control structure, Condition if, Interactive- loop, for, while
,Sequential goto.
10 PL/SQL code for Composite data types ,Record- declaration, refer, record assignment
,Table- Declaration, table attributes.(Count, delete, exists, first, last, next, prior)
11 Programs based on Database Triggers
12 Programs based on cursors and Sub programs: procedure and function
13 MINI PROJ ECT






















Introduction



Database
A computer database is a structured collection of records or data that is stored in a computer
system so that a computer program or person using a query language can consult it to answer
queries

DBMS (Database Management System)
A DBMS is a complex set of software programs that controls the organization, storage,
management, and retrieval of data in a database.

Oracle
Oracle Database (commonly referred to as Oracle RDBMS or simply as Oracle) is a relational
database management system (RDBMS) software product released by Oracle Corporation.
The Oracle database is a broad and powerful product
Database application development features
Database connection features
Distributed database features
Data movement features
Performance features
Database management features

Oracle9i -
Oracle offers a comprehensive high-performance infrastructure for e-business. It is called
Oracle9i. Oracle9i includes everything needed to develop, deploy, and manage Internet
applications.







EXERCISE -1

TITLE:
DDL Commands

OBJECTIVES:
1. Study Basic concepts of Data Definition language.
2. Learn to create, alter, drop table
3. Apply constraints on tables.

THEORY:

DDL
A Data Definition Language is a language for defining and handling database table structure.
For eg. Commands like
1) CREATE
2) ALTER
3) DROP

Basic Data Types

Char Data type can be used to store the character string of fixed length
If the entered strings length is less than the specified size then remaining space is filled
by spaces.

varchar/varchar2 This is variable length datatype which can store the alphanumeric
characters of size 2000.

Long - The data type is used to store the variable length character string containing upto
2 GB.

Number The number data type is used to store the numbers both fixed and floating
point.

Date This data type is used to represent the date and time. Th standard format is DD-
MON-YY.

CLOB (CHARACTER LARGE OBJ ECT ) - The CHARACTER LARGE OBJ ECT
(CLOB) data type stores character string values of varying length up to the maximum
specified as the large object length (n[K|M|G]).

The large object length is n, optionally multiplied by K|M|G.
You can specify the maximum length of the CLOB data type as the length of the column
when you create the table. If you do not specify large object length, the length is
implementation-defined to 1Mb. The maximum length of a CLOB is determined by the
amount of disk space available for its storage.

DLOB BLOB data type is used for binary data. & can extend to 4 GB data.


Table
Definition A table is database object that holds user data.

Syntax of create table command

Create table <tablename> (<columnname1> <datatype>(<size>), <columnname2>
<datatype>(<size>));

Commands for table handling

Alter table - This command is used to change the structure of the table. This command
can be used for three purposes

to add new column :

Syntax alter table <tablename> add(<newcolumnname>
<datatype>(<size>),<newcolumnname> <datatype>(<size>).);

to delete a column from table
Syntax - alter table <tablename> drop column <columnname> ;

to modify column of table
Syntax - alter table <tablename> modify (<columnname> <newdatatype>(<newsize>));

Drop table - command is used to destroy the table
Syntax drop table <tablename>;


Constraints
Constraints enforce rules on the data in a table whenever a row is inserted, updated, or deleted
from that table. The constraint must be satisfied for the operation to succeed.constraints can be
defined at table level or column level.


Types of Constraint
NOT NULL: Specifies that the column cannot contain a null value
UNIQUE :Specifies a column or combination of columns whose values must be
unique for all rows in the table
PRIMARY KEY: Uniquely identifies each row of the table
FOREIGN KEY :Establishes and enforces a foreign key relationship between the
column and a column of the referenced table
CHECK :Specifies a condition that must be true

EXERCISE-2
TITLE:
DML Commands .

OBJECTIVES:
1. Study Basic concepts of Data Manipulation language.
2. Use commands like insert,update,delete,select.

THEORY:
DML (Data Manipulation Language) - It is a family of computer languages used by computer
programs or database users to retrieve, insert, delete and update data in a database.

Insert records command is used to insert the records in the table
insert into <tablename>(<columnname1>,<columnname2>) values
(<expression1>,<expression2>))


Update update command is used to change or modify the data values in a table.
update <tablename>
set <columnname>=<expression>,<columnname>=<expression>

Delete Delete command is used to delete all records of table or to delete some records
of table.
delete from <tablename>;
delete from <tablename>where <condition>;

Select- select command select specified records from table.

select <columnname>to <columnname>from <tablename>;
select * from <tablename>;

select <columnname>,<columnname>from <tablename>;
select * from <tablename>where <condition>;

select <columnname>,<columnname>from <tablename>;








EXERCISE-3
TITLE:
Use of Operators and order by with SQL

OBJECTIVES:
1. Use all operators(arithmetic,comparision,logical)
2. Use of order by clause with select command

THEORY:
Arithmetic operators

+- Addition - - Subtraction
- Multiplication / - Division
** - Exponentiation () - Enclosed operation

Syntax
select <columnname>*<columnname>from <tablename>;
select <columnname>*<columnname>allias_name from <tablename>;

Comparison operators

o =- Equal to <>- Not equal to
o <less than >- Greater than

Logical operators

o And logical and
o Or - logical or
o Not logical not

Ordering the records with order by

Order by clause is used to sort the records according to ascending or descending. If we
want in descending order then we have to specify as desc otherwise by default ordering is
in ascending order,
Syntax
1) select * from <tablename>order by <columnname>;
2) select * from <tablename>order by <columnname>desc;
3) select * from <tablename>order by <columnname1>,<coumnname2>;






EXERCISE-4
TITLE:
Grouping the records , Set operations .

OBJECTIVES:
1. Grouping the records using Group functions: Avg, max, min, sum, count.
2. Use of Set operations : Union, Union all, intersect, minus .
3. Use of SQL functions.
THEORY:

Grouping the records
grouping can be done in SQL using group by clause. Group by clause is one clause of
select statement. The group by clause creates a data set , containing several set of records
grouped together on a condition

Having clause imposes the condition on group by clause which further filters the group
created by group by.
For eg
. 1) Select product_no, ,sum(qty_ordered) Total Qty Ordrered
From sales_order_details
Group by product_no;
2) Select product_no, ,sum(qty_ordered) Total Qty Ordrered
From sales_order_details
Group by product_no;
Having product_no =P0001 or product_no =P0004
SQL functions
Date
add_months(d,m);
Returns date by adding m months in d


last_day(d)
Returns last date of the month d.


months_between(d1,d2);
Returns number of months between first date d1 and second date d2


next_day(date,char);
Returns the date of the first weekday named by char that is after the date named by date.
Char must be the day of week

For eg. Select Next_day(06-july-02,Saturday) NEXT DAY
From dual

NEXT DAY
13-july-02

to_date(char,fmt);
Returns character field to date field;

to_char(date,fmt);
Converts date into specified format

Numeric

abs(n);
Returns absolute value of n;

power(m,n);
Returns m raised to the n
th
power, n must be integer

round(n,m);
Returns n rounded to m places to the right of decimal point. If m is omitted n is rounded
to 0 places of decimal point
sqrt(n);
Returns square root of n.

Character

lower(char) ;
Returns char with all letters in lower case.

initcap(char);
Returns string with the first letter of each word in upper case

upper(char);
Returns char with all lettersforced to uppercase.

substr(char,m,n);
Returns portion of characters, beginning at character m, and going upto character n, if n is
omitted, the result returned is upto the last character in the string. The first position of
char is 1.

length(word);
Returns length of word.

ltrim(char,set);
Removes character from left of char with initial characters removed upto the first
character not in set

rtrim(char,set);
Returns char with final characters removed after the last character not in the set.
set is optional, it defaults to spaces.

lpad(char1,n,char2);
Returns char1, left padded to length n with the sequence of characters specified in
char2.
I f char2 is not specified oracle uses blanks by default.

rpad(char1,n,char2);
Returns char1, right padded to length n with the characters specified in char2, if
char2 is not specified, oracle uses blanks by default.

Conversion to_number(char);
Converts character to number.

Group functions
Avg() finds average of the data values of the specified field,
Max() finds maximum data value among the data values of specified field
Min() - finds minimum data value among the data values of specified field
Sum() calculates the sum of data values of the specifiesd field.
Count() count total data values of the specified field
Set operations

Union Th union clause merges the output of two or more than two queries into a
single set of rows and columns.
Union all same as that of union but allows duplicate values also.
Intersect - the intersect clause outputs only the rows produced by both the queries
intersected.
o Minus the minus clause produced by the first query, after filtering the
rows retrieved by the second query











2
EXERCISE-5

TITLE:
Join concept

OBJECTIVES:
1. understand concept and use of all types of J oin : Simple, equi, non equi, self,
outer join

THEORY:
Join concept :
When data from more than one table in the database is required, a join condition is used.
Rows in one table can be joined to rows in another table according to common values
existing in corresponding columns, that is, usually primary and foreign key columns. To
display data from two or more related tables, write a simple join condition in the WHERE
clause.

Types of join
Equi join
an equijointhat is, values in the one of column on both tables must be equal.

SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column1 =table2.column2;

Non equi join
A non-equijoin is a join condition containing something other than an equality
operator.

Outer join
You use an outer join to also see rows that do not meet the join condition. The
Outer join operator is the plus sign (+).

SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column(+) =table2.column;

Self join
Sometimes you need to join a table to itself it is called self join





3
EXERCISE-6,7
TITLE:
Subquery

OBJECTIVES:
1. understand concept and use of all types of subqueries.

THEORY:
Subquery
A subquery is a SELECT statement that is embedded in a clause of another
SELECT statement. You can build powerful statements out of simple ones by
using subqueries. They can be very useful when you need to select rows from a
table with a condition that depends on the data in the table itself.
You can place the subquery in a number of SQL clauses, including:
The WHERE clause
The HAVING clause
The FROM clause

How to use subquery:

A subquery must be enclosed in parentheses.
Place the subquery on the right side of the comparison condition for readability.
Prior to release Oracle8i, subqueries could not contain an ORDER BY clause.
Only one ORDER BY clause can be used for a SELECT statement, and if
specified it must be the last clause in the main SELECT statement. Starting with
release Oracle8i, an ORDER BY clause can be used and is required in the
subquery to perform Top-N analysis.
Two classes of comparison conditions are used in subqueries: single-row
operators and
multiple-row operators.



Types of Subqueries

Single-row subqueries:
Queries that return only one row from the inner SELECT statement
Multiple-row subqueries:
Queries that return more than one row from the inner SELECT statement






4
EXERCISE-8

TITLE:
View, Synoname, Sequence, Index

OBJECTIVES:
1. understand concept and use of view, synoname, sequence, index.

THEORY:

1. VIEW:
A view is a "virtual table" in the database whose contents are defined by a query,
The CREATE VIEW statement, is used to create a view. The statement assigns a
name to the view and specifies the query that defines the view. To create the view
successfully, you must have permission to access all of the tables referenced in
the query.

Syntax:-

Create view <viewname>

2. SEQUENCE
A sequence automatically generates unique numbers, it Is a sharable object ,Is
typically used to create a primary key value, it Replaces application code ,Speeds
up the efficiency of accessing sequence values when cached in memory.

Syntax:
CREATE SEQUENCE sequence
[INCREMENT BY n]
[START WITH n]
[{MAXVALUE n | NOMAXVALUE}]
[{MINVALUE n | NOMINVALUE}]
[{CYCLE | NOCYCLE}]
[{CACHE n | NOCACHE}];


3. INDEX
Index is a schema object, It Is used by the Oracle server to speed up the retrieval
of rows by using a pointer ,it Can reduce disk I/O by using a rapid path access
method to locate data quickly.
Two types of indexes can be created.
One type is a unique index: the Oracle server automatically creates this
index when you define a column in a table to have a PRIMARY KEY or a
UNIQUE key constraint. The name of the index is the name given to the
constraint.
5
The other type of index is a nonunique index, which a user can create. For
example, you can create a FOREIGN KEY column index for a join in a
query to improve retrieval speed.

Syntax:
CREATE INDEX index
ON table (column[, column]...);

4. SYNONYM:
To refer to a table owned by another user, you need to prefix the table name with the
name of the user who created it followed by a period. Creating a synonym eliminates
the need to qualify the object name with the schema and provides you with an
alternative name for a table, view, sequence, procedure, or other objects.

Syntax:
CREATE [PUBLIC] SYNONYM synonym
FOR object;






















6
EXERCISE-9-12

TITLE:
PL/SQL

OBJECTIVES:
1. understand concept and use of all commands and statements of PL/SQL.

THEORY:

PL/SQL
PL/SQL is the procedural extension to SQL with design features of programming
languages.Blocks of PL/SQL code are passed to and processed by a PL/SQL engine.Data
manipulation and query statements of SQL are included within procedural units of code

PL/SQL Block Structure

DECLARE (Optional)
Variables, cursors, user-defined exceptions
BEGIN (Mandatory)
SQL statements
PL/SQL statements
EXCEPTION (Optional)
Actions to perform when errors occur
END; (Mandatory)

CONDITIONAL STATEMENTS:

1. Conditional IF statements:
IF-THEN-END IF
IF-THEN-ELSE-END IF
IF-THEN-ELSIF-END IF
2. CASE statement
CASE selector
WHEN expression1 THEN result1
WHEN expression2 THEN result2
...
WHEN expressionN THEN resultN
[ELSE resultN+1;]
END;





7

LOOPING STATEMENTS

1. Basic Loops
LOOP
statement1;
. . .
EXIT [WHEN condition];
END LOOP;
2. While loop

WHILE condition LOOP
statement1;
statement2;
. . .
END LOOP;

3.For loop
FOR counter IN [REVERSE]
lower_bound..upper_bound LOOP
statement1;
statement2;
. . .
END LOOP;

Cursors

Every SQL statement executed by the Oracle Server has an individual cursor associated
with it:
Implicit cursors: Declared for all DML and PL/SQL SELECT statements
Explicit cursors: Declared and named by the programmer

Declaring the Cursor
CURSOR cursor_name IS
select_statement;
Opening the Cursor
OPEN cursor_name;
Fetching Data from the Cursor
FETCH cursor_name INTO [variable1, variable2, ...] | record_name];
Closing the Cursor
CLOSE cursor_name;




8

Explicit Cursor Attributes

Attribute Type Description
%ISOPEN Boolean Evaluates to TRUE if the
cursor
%NOTFOUND Boolean Evaluates to TRUE if the
most
%FOUND Boolean Evaluates to TRUE if the
most
%ROWCOUNT Number Evaluates to the total
number of


Handling Exceptions with PL/SQL

An exception is an identifier in PL/SQL that is raised during execution.it is raised when
An Oracle error occurs. or one can raise it explicitly. to handle it one can Trap it with a
handler or Propagate it to the calling environment.


Advantages of PL/SQL Exceptions

1. Using exceptions for error handling has several advantages. Without exception
handling, every time you issue a command, you must check for execution errors.

2. Error processing is not clearly separated from normal processing; nor is it robust. If
you neglect to code a check, the error goes undetected and is likely to cause other,
seemingly unrelated errors.

3. With exceptions, you can handle errors conveniently without the need to code
multiple checks Exceptions improve readability by letting you isolate error-handling
routines. The primary algorithm is not obscured by error recovery algorithms.

4. Exceptions also improve reliability. You need not worry about checking for an error
at every point it might occur. J ust add an exception handler to your PL/SQL block. If
the exception is ever raised in that block (or any sub-block), you can be sure it will be
handled.
Exception Types
Predefined Oracle Server
Nonpredefined Oracle Server
User-defined



9

EXCEPTION
WHEN exception1 [OR exception2 . . .] THEN
statement1;
statement2;
. . .
[WHEN exception3 [OR exception4 . . .] THEN
statement1;
statement2;
. . .]
[WHEN OTHERS THEN
statement1;
statement2;
. . .]
Sample predefined exceptions:
NO_DATA_FOUND
TOO_MANY_ROWS
INVALID_CURSOR
ZERO_DIVIDE
DUP_VAL_ON_INDEX


subprogram:

Is a named PL/SQL block that can accept parameters and be invoked from a calling
environment,Is of two types:
A procedure that performs an action
A function that computes a value
features
Is based on standard PL/SQL block structure
Provides modularity, reusability, extensibility,
and maintainability
Provides easy maintenance, improved data security and integrity, improved
performance, and improved code clarity


Syntax for Creating Procedures
CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter1 [mode1] datatype1,
parameter2 [mode2] datatype2,
. . .)]
IS|AS
PL/SQL Block


10
Assignments

EXERCISE-1

DDL
1. Create table Salespeople with fields snum, sname, city, commission
2. Create table Orders with fields onum, odate, snum, amt
3. Customers table with fields cnum, cname, city, rating, snum
4. Create table
Department(department_id, department_name, manager_name,location ) where
department_id is a primary key.
5. Create table
Employee(employee_id, firsr_name, last_name, email, phone_no,
hire_date,job_id,salary, department_id, commission, grade) with employee_id as a
primary key & department_id as a foreign key.
6 Create table
GRA(Grade,lowest_salary,highest_salary) with UNIQUE constraint.
7. Create table New_EMp from employee with employee_id, firsr_name, last_name,
email, phone_no, ,salary, fields renamed to E_id, F_name, L_name, Email_id
,Ph_no,E_salary respectively.
8. Add new column DOB (Date of birth) to the Customers table .
9. Add new column State to the Customers table .
10. Modify the column cname to Cust_name(30).
11. Delete column state from Customers table.
12. Add primary key constraint on column cnum in Customers table.
13 Add foreign key constraint on column snum in Customers table.
14. Delete all constraints on Customers table.
15 Truncate table New_emp
16 Create table new_Cust from Customers from Customers table with cnum, cname city
16 Drop table new_Cust.

11
EXERCISE-2
DML

1. Insert min 10 records in all tables.
2 Insert null values (implicitly & explicitly) in employee table.
3. Insert system date in employee table as hire date.
4. Update the email of employee J ohn to J ohn@yahoo.co.in
5. Change the commission of the salesperson whose name starts form A.
6. Display all the records with all sales peoples information.
7. Display the odate, snum, onum, amt from orders table.
8. Display snum from orders table without duplications.
9. Display all details of customer where rating is 100.
10. Display all details from customer table where salespersons number is 1001.
11. display Depart_name & manager_name from Deprtment table.
12. Select the employees in department no 7.
13 Display the commission for the employee J ohn
14. Delete the orders given on the date 3
rd
march 2009.
15.Display the name of employee starting with the alphabet m
16 .Display employee hiredate in following format Fifteenth of December 2005



















12
EXERCISE-3
Order By & Operators
1. List all the employees who are from any of the following cities
- Pune, Nashik, Bombay, Nagpur.
2. Display name and salary of all employees in descending order of salary.
3. Display all the employees who are hired on 1
st
J an, 2008 or 1
st
J uly 2008.
4. Display all the employees who are hired on or before 1
st
J an 2007 but not after 1
st

july, 2009.
5. Display the Customers whose name starts from S & all of them from Pune
city.
6. Display data from employee table by adding 1000 commision to salry and display
annual salary
7. Display the counts of all orders for Feb05
8. Display the count of different non-NULL city values in the customers table.
9. Display the maximum outstanding amount as blnc+amt
10. Display the minimum rating within customers table.
11. Display average of amt.
12. Display sales persons number wise maximum amt from order table.
13. Display the largest order taken by each salesperson on each date.
14. Display the details of maximum orders above 3000.
15. Display details of orders order number & date wise
16. Display the employees whose salary is less than or equal to 10,000
17. Write a query to display the name and salary of employees earning more than
$3000.
18. Write a query to display the name and salary of all employees whose salary is not in
the range of $1500 and $2850.
19.Dispaly the employee name and department number of all employees in department
10 and 30 in alphabatical order by name.

20 Display the name and salary of employees who earn more than $1500 and are in dept
10 or 30. Label the columns as Employee and Monthly Salary respectively.
Display the names of all employees where the third letter of their name is an A.
13

21. Display the name of all employees who have two 'L's in their name and are in dept
30 or their manager is 7782.

22. Display the name job and salary of all employees whose job is clerk or Analyst and
their salary is not equal to $1000, $3000 or $5000.

23. Display the employee name concatenated with the job, seperated by a comma and
name the column as Employee and Title.

24. Display the name, salary and commission of all employees whose commission
amount is greater then their salary increased by 10%




























14
EXERCISE-4
Grouping, Set Oprations

1. Display the counts of all orders for Feb05
2. Display the count of different non-NULL city values in the customers table.
3. Display the maximum outstanding amount as blnc+amt
4. Display the minimum rating within customers table.
5. Display average of amt.
6. Display sales persons number wise maximum amt from order table.
7. Display the largest order taken by each salesperson on each date. 8
8. Display the details of maximum orders above 3000.
9. Display details of orders order number & date wise
10. Display the names of the employees who are from Nashik or they are getting
20,000 salary.
11. Display the names of the employees who are from Nashik but they are not
getting 20,000 salary.
12. Display the names of the employees who are from Nashik and they are getting
20,000 salary.
13. Insert the current date as the hire date for the new employee.
14. Display the names of Employees with their hire date by delaying a hire date by 3
months (Adding months to date)
15 .Display the last day of the month in which Customer J ohn has born
16.Display the number of months for Merry that have passed after the J ohn is
17.employed.
( Number of months between hire date of J ohn and hire date of Merry)
18. Display the date of the first Monday that is after the DOB of customer having
cnum 15. ( next_day(date, char); Returns the date of the first weekday named by char
that is after the date named by date. Char must be the day of week )
19 . Display the hire date of all the employees in the format DD-MON-YY HH:MM
A.M..
20 .Select the amt for all the orders in the form of $099,999.

15
21. Display the absolute value of any negative number.
22. Find the value of (10
5
).
23 .Find the average amount for all the orders & round it to 2 decimal places.
24 .Display the square root of 4009.
25. Select the distinct city names from customers table with all city names in lowercase.
26. Select the distinct names of employees from Employee table with all names starting
with a capital letter.
27 .Select the distinct names of employees from Employee table with all names in capital
letters.
28 Display the 3 characters from the distinct names of employees starting from the
second letter in the name.
29 .Display the distinct names of employees with the length of their names.
30. Display the salaries of all employees from Employee table with salary amount with
prefix characters Rs. .
31. Display the salaries of all employees from Employee table with salary amount
ending with the characters $.
32. Remove character * from left of string ( *******abc**) to get the result starting
with letter a
33. Remove character * from right of string ( *******abc**) to get the result ending
with letter c
33. Display the current date into DD-MM-YY format.















16
EXERCISE-5

Join

1. Delete record of employee who s manager is jon.
2. Write a query to display the last name, department number, and department name for
All employees.
3. Display count of all employee working in EDP
4. Display employee name, department and salary having salary between 4,000 and
8,000.
5.Display employee names with department. Name of employee must end with sh.
6.Create a unique listing of all jobs that are in department 80. Include the location of the
Department in the output.
7. Write a query to display the employee last name, department name, location id, and
city of All employees who earn a commission.
8. Write a query to display the last name, job, department number, and department name
for all employees who work in toronto.
9. Display names of all customers matched with the salespeople serving them.
10. Find all orders by customers not located in same cities as their salespersons.
11. Display each order number followed by the name of customer who made it.
12. Calculate the amount of salespersons commissions on each order by a customer with
a rating above 100.
13. Display the pairs of salespeople who are living in the same city. Exclude
combinations of sales people with themselves as well as duplicate rows with the order
reversed.
14. Display the names & cities of all customers with same rating as Hoffman.
15 .Display employee name working in department Computer
Display the name and hire date of every employees who was hired in 1982.
16. Display the name and job title of all employees who do not have manager.
17. Display the name and job title of all employees who earn commission. Sort data in
descending order of salary and commission.

17
EXERCISE-6,7

SubQueries

1. Write a query that uses a subquery to obtain all orders for the customer named Gopal.
Assume you do not know the customer number.
2. write a query that produces the names & ratings of all customers who have above-
average orders.
3. Write a query that selects the total amt in orders for each salesperson for whom this
total is greater than the amount of the largest order in table
4. Write a query to display all the data from the EMP table where each column is
seperated by a comma. Give a heading to the output as THE_OUTPUT.
5.Write a query to display the number of people with the same job.
6. Display the manager number and the salary of the lowest paid employee for that
manager. Exclude any one whose manager is not known. Exclude any groups where the
minimum salary is less than $1000. Sort the output in desc order of salary.
7. Write a query to display the department name, location, number of employees, and the
average salary for all employees in that dept.
8. Write a query to display the employee name and hiredate for all employees in the same
department as BLAKE. Exclude Blake.
9. Write a query to display the employee number and name for all employees who earn
more than the average salary.
10. Write a query to display the employee number and name for all employees who work
in a department with any employee whose name contains a T.
11. Dispaly the name, department number and job for all employees in the SALES
department.
12. Write a query to display the name, department number, and salary of any employee
whose department number and salary match the department number and salary of any
employees who earns a commision.
13. Write a query to display the name, hiredate and salary of all employees who have the
same salary and commision as 'SCOTT'.

18
14. Write a query to display the employees that earn a salary that is higher than the salary
of all the clerks. ( try out different ways ) Hint - Try using ALL operator.
15. Display the highest, lowest, sum, and average salary of all employees. Label the
columns
Maximum, Minimum, Sum, and Average, respectively. Round your results to the nearest
whole number.
16. Display the minimum, maximum, sum, and average salary For each job type.
17. Write a query to display the number of people with the same job.
18. Determine the number of managers without listing them. Label the column Number
of Managers. Hint: Use the MANAGER_ID column to determine the number of
managers.
19. Write a query that displays the difference between the highest and lowest salaries.
Label the Column DIFFERENCE.
20.displays the department numbers and average salaries for those departments
Whose maximum salary is greater than $10,000:
21. Display sum of salary grouped by at first dept_id then by job_id.
22. Display the manager number and the salary of the lowest paid employee for that
manager. Exclude anyone whose manager is not known. Exclude any groups where the
minimum Salary is $6,000 or less. Sort the output in descending order of salary.
23. Write a query to display each departments name, location, number of employees, and
the Average salary for all employees in that department. Label the columns Name,
Location, Number of People, and Salary, respectively. Round the average salary to two
decimal Places.
24. Create a query that will display the total number of employees and, of that total, the
number of employees hired in 1995, 1996, 1997, and 1998. Create appropriate column
headings.23. display average commission it should include null values also.
25. Create a matrix query to display the job, the salary for that job based on department
number,
And the total salary for that job, for departments 20, 50, 80, and 90, giving each column
an Appropriate heading.

19
EXERCISE-8


Sequence, Synonym, View, Index

1. Create an index that would permit each salesperson to retrieve his or her orders
grouped by date quickly.
2. Create a composite index on the Employee table for the fields Employee_id &
job_id.
3. Create unique index on customers table with cnum field
4. Drop index on customers table.
5. Create a view that shows all of the customers who have highest ratings.
6. Create a view named dept20 that contains the employee number, name and dept
number for all employees in department 20. Label the view column names as
EMP_ID, EMPLOYEE, and DEPT_ID.
7. Create view named Salary_5000 which have the fields Employee_id,
Employy_name, Dept_name where all employees have a salary greater than 5000.
8. Drop the view created from the customers table.
9. Create an index on dept_id column of emp table.
10. Create a sequence named seq_1 to start at 60, increment by 10 and have a max
value of 200.
11. Create a sequence named seq_2 to start at 1000,decrement by 10 and have a min
value of 10 . After reaching to a min value it should continue to generate the
values repetitively.
12. Change sequence seq_2 to have min value of 5& the interval between the
numbers should be 5.
13. Drop sequence seq_1.
14. Create synonyms for all the tables, views & sequences that you have created.




20
EXERCISE-9-12

PL/SQL

1. Write a PL/SQL block for finding the square root of a particular number.

2. Write a PL/SQL block for finding the area of a circle.

3. Write a PL/SQL block for checking whether a number is even or odd.

4. Write a trigger weather a specified course code is of two digit.

5. Write a trigger to check that emp record should be entered on normal duty hours i.e
between 9 to 5.

6. Write a PL/SQL block to display all names in descending order from EMP table
whose salary is greater than 5000.Maximum records should not be more than 5.

7. The HRD Manager has decoded to raise the salary for all employees in dept number
20 by 0.05.Whenever any raise is given to all the employees, a record for the same
is maintained in the EMPRAISE table. IT includes the employee number, the date
when the raise was given and the actual raise. Write a PL/SQL block to update the
salary of each employee and insert a record in the EMP_RAISE table.

8. Write a PL/SQL block of code that first inserts a record in an emp table. Update
the salary by Rs. 2000. then check to see that the total salary does not exceed
20000. if so, undo the updates made to the salaries.

9. HRD manager has decided to raise the salary of employees by 0.15. Write a
PL/SQL block to accept the employee number & update the salary of that emp.
Display message based on the existence of record in employee table.

10. when any such raise in salary, a record for the same is maintained in emp_raise
table. It includes the employee no, the date of raise & the actual raise.

11. Create a stored function to perform itemid check operation. Which accepts a itemid
& returns a flag as per the id exist or not.

Anda mungkin juga menyukai