Professional Documents
Culture Documents
Year-II Semester-IV
(Code- 18CSC15)
Submitted to :
Mrs.D.Naga Jyothi
Submitted by :
B.E-2/4, CSE-3
1
LIST OF EXPERIMENTS
5 Write the sample queries using DML commands – insert, update, delete and select 26
6 Write the sample queries on aggregate functions(min, max, count, sum, avg) 28
9 Write the sample queries using some, any and all operators 34
EMP(eno,ename,job,… ........................................ )
DEPT(deptno,dname,……)
SALGRADE(… .... )
Use the various integrity constraints like primary key, foreign key, not null,
check constraints while creating and altering the tables.
11 Write the sample queries using other DDL commands- alter, truncate, drop 36
12 Write the sample queries using DCL commands – grant and revoke 37
13 Write the sample queries using TCL commands – commit, rollback and savepoint 39
14 Write the sample queries to exercise all the joins – inner join, left outer join, right 42
outer join and full outer joins
15 Write the sample queries to create the view and show an updation on the view 44
17 Display the last 3 characters of the employee name in uppercase directly followed by 52
the job.
2
18 Display all the employees who earning salary not in the range of 2500 and5000 in 52
department 10 & 20.
20 How many clerks are there in the company? Which department exactly employs one 53
clerk?
22 Display the number of employee for each job goup deptno wise. 55
24 List the emps who are either ‘CLERK’ or ‘ANALYST’ in the Desc order. 56
25 Which department has highest number of salesman, show the department number and 56
the count?
26 Find the lowest paid employee of sales department. 56
30 Find all the employees whose name starts with ‘S’ and has 6 characters in the name. 58
31 Find out all those managers and jr.managers who are drawing salary more than 10,000 58
32 Write the query to display the employee as well as department details department wise. 58
34 List the emps who joined in the company on the same date. 59
35 Get employee details from employee table who joined before January 1st 2013 60
38 For each department show its deptno and average salary. Sort the result in descending 61
order of the average salary.
3
40 Form the employee table by generating the following output: 62
Who , what , and when
………………………………………………………………………………
…………..
Eg: ford is held the position of analyst in dept no 20
41 Find the minimum, maximum and average salary for each job title . 62
42 Show the details of the staff who are not working in the research department. 63
43 Calculate the number of months between today and hired date of the employee. Order 63
the results by the number of months.
44 List the details of the department where maximum number of emps are working. 64
47 Write a pl/sql block to input a number with substitution variable and then print its 65
multiplication table using for and while loop
48 Write a pl/sql block to avail 20% bonus to all employees who are receiving the 67
commission.
49 Write a pl/sql block using implicit cursors to get the number of employees. 67
50 Write a pl/sql block using explicit cursors to get the employee data. Print the 68
employee’s annual salary if the amount is less than 50000.
4
1. AIM: Write the sample queries on single row numeric functions
single row functions: Single-row functions return a single result row for every row of a
queried table or view. These functions can appear in select lists, WHERE clauses, START
Numeric Functions
Numeric functions accept numeric input and return numeric values. Most numeric
functions that return NUMBER values that are accurate to 38 decimal digits. The
transcendental functions COS, COSH, EXP, LN, LOG, SIN, SINH, SQRT, TAN, and
TANH are accurate to 36 decimal digits. The transcendental functions ACOS, ASIN,
ATAN, and ATAN2 are accurate to 30 decimal digits. The numeric functions are:
ABS
CEIL
FLOOR
LOG
MOD
NANVL
POWER
ROUND (number)
SIGN
TRUNC (number)
ABS
Syntax: - abs(n)
ABS (-5)
5
5
CEIL
Syntax: - ceil(n)
CEIL (23.587)
24
FLOOR
Syntax: - floor(n)
FLOOR (23.587)
23
LOG
Syntax: - log(n)
LOG returns the logarithm, base n2, of n1. The base n1 can be any positive value other
LOG (2)
0.3010299957
MOD
6
MOD returns the remainder of n2 divided by n1. Returns n2 if n1 is 0.
MOD (15,4)
POWER
POWER returns n2 raised to the n1 power. The base n2 and the exponent n1 can
POWER (2,4)
16
ROUND (number)
integer, then n is rounded to 0 places. The argument integer can be negative to round off
digits left of the decimal point. For NUMBER values, the value n is rounded away from 0
(for example, to x+1 when x.5 is positive and to x-1 when x.5 is negative).
Example: -
24
ROUND (23.587,1)
7
23.6
20
60
SIGN
SIGN returns the sign of n. This function takes as an argument any numeric
and returns NUMBER. For value of NUMBER type, the sign is:
• -1 if n<0
• 0 if n=0
• 1 if n>0
SIGN (23.587)
TRUNC (number)
then n1 is truncated to 0 places. n2 can be negative to truncate (make zero) n2 digits left
Example: -
8
• select trunc (23.587) from dual;
TRUNC (23.587)
23
20
TRUNC (23.587,1)
23.5
single row character functions: Character functions that return character values return values
returned is NVARCHAR2. The character functions that return character values are:
CHR
CONCAT
INITCAP
9
LOWER
LPAD
LTRIM
REPLACE
RPAD
RTRIM
SUBSTR
TRANSLATE
TRIM
UPPER
CHR
CHR returns the character having the binary equivalent to n as a VARCHAR2 value in
either the database character set or, if you specify USING NCHAR_CS, the national
character set. This function takes as an argument a NUMBER value, or any value that
CONCAT
CONCAT returns char1 concatenated with char2. Both char1 and char2 can be any of the
returned is in the same character set as char1. Its datatype depends on the datatypes of the
10
datatype that results in a lossless conversion.
CONCA
Hello
INITCAP
INITCAP returns char, with the first letter of each word in uppercase, all other letters in
lowercase. Words are delimited by white space or characters that are not alphanumeric.
INITCAP (
H23l4 Hi
LOWER
Syntax: - lower(chr)
LOWER returns char, with all letters lowercase. char can be any of the datatypes CHAR,
VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The return value is the same
LOWER
h2334
LPAD
LPAD returns expr1, left-padded to length n characters with the sequence of characters in
If you do not specify expr2, then the default is a single blank. If expr1 is longer than n,
11
then this function returns the portion of expr1 that fits in n.
LPAD ('H233
00000h2334
LTRIM
LTRIM removes from the left end of char all of the characters contained in set. If you
do not specify set, it defaults to a single blank. If char is a character literal, then you
must enclose it in single quotes. Oracle Database begins scanning char from its first
character and removes all characters that appear in set until reaching a character not in
set and then returns the result. Example: - select ltrim('hi2334','h') from dual;
LTRIM
i2334
REPLACE
REPLACE returns char with every occurrence of search string replaced with replacement
string. If replacement string is omitted or null, then all occurrences of search string are
lets you substitute one string for another as well as to remove character strings.
REPLACE (
12
09ih2334
RPAD
RPAD returns expr1, right-padded to length n characters with expr2, replicated as many
times as necessary.
This function is useful for formatting the output of a query.
expr1 cannot be null. If you do not specify expr2, then it defaults to a single blank. If
expr1 is longer than n, then this function returns the portion of expr1 that fits in n.
The argument n is the total length of the return value as it is displayed on your terminal
screen. In most character sets, this is also the number of characters in the return value.
However, in some multibyte character sets, the display length of a character string can
RPAD ('H233
h233400000
RTRIM
RTRIM removes from the right end of char all of the characters that appear in set. This
If you do not specify set, then it defaults to a single blank. If char is a character literal,
then you must enclose it in single quotes. RTRIM works similarly to LTRIM.
RTRIM
hi233
13
SUBSTR
The SUBSTR functions return a portion of char, beginning at character position, substring
length characters long. SUBSTR calculates lengths using characters as defined by the
• If position is positive, then Oracle Database counts from the beginning of char to
• If position is negative, then Oracle counts backward from the end of char.
• If substring length is omitted, then Oracle returns all characters to the end of char. If
Example: -
--
ll
SUB
---
llo
SU
--
lo
TRANSLATE
14
TRANSLATE returns expr with all occurrences of each character in from string replaced by
its corresponding character in to string. Characters in expr that are not in from string are not
replaced. If expr is a character string, then you must enclose it in single quotation marks. The
argument from string can contain more characters than to string. In this case, the extra
characters at the end of from string have no corresponding characters in to string. If these
extra characters appear in char, then they are removed from the return value.
function. REPLACE lets you substitute a single string for another single string, as well
TRANSLAT
0e920334
TRIM
TRIM enables you to trim leading or trailing characters (or both) from a character
string. If trim character or trim source is a character literal, then you must enclose it in
single quotes. • If you specify LEADING, then Oracle Database removes any leading
• If you specify BOTH or none of the three, then Oracle removes leading and
• If you do not specify trim character, then the default value is a blank space.
• If you specify only trim source, then Oracle removes leading and trailing blank
15
spaces. • The function returns a value with datatype VARCHAR2. The maximum
• If either trim source or trim character is null, then the TRIM function
returns null. Example: - select trim ('h' from 'hi2334') from dual;
TRIM (
i2334
UPPER
UPPER returns char, with all letters uppercase. char can be any of the datatypes CHAR,
VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The return value is the same
UPPER
H2334
UPPER
HELLO
Character Functions Returning Number Values
Character functions that return number values can take as their argument any character
ASCII
INSTR
LENGTH
16
ASCII
ASCII returns the decimal representation in the database character set of the first character
value returned is of datatype NUMBER. If your database character set is 7-bit ASCII, then
Example: -
ASCII('H')
104
ASCII('H')
72
INSTR
The INSTR functions search string for substring. The function returns an integer
indicating the position of the character in string that is the first character of this
occurrence. INSTR calculates strings using characters as defined by the input character
set.
Database begins the search. If position is negative, then Oracle counts backward
from the end of string and then searches backward from the resulting position.
Example: -
INSTR('HELLO','H')
17
1
INSTR('HELLO','Y')
LENGTH
The LENGTH functions return the length of char. LENGTH calculates length using
Output: -
LENGTH('H')
WITH TIME ZONE, and TIMESTAMP WITH LOCAL TIME ZONE), and interval
Some of the datetime functions were designed for the Oracle DATE datatype
you provide a timestamp value as their argument, Oracle Database internally converts the
input type to a DATE value and returns a DATE value. The exceptions are the
MONTHS_BETWEEN function, which returns a number, and the ROUND and TRUNC
functions, which do not accept timestamp or interval values at all. The datetime functions
18
are:
ADD_MONTHS
CURRENT_DATE
CURRENT_TIMESTAMP
LAST_DAY
LOCALTIMESTAMP
MONTHS_BETWEEN
NEW_TIME
NEXT_DAY
ROUND (date)
SYSDATE
SYSTIMESTAMP
TO_CHAR (datetime)
TRUNC (date)
ADD_MONTHS
ADD_MONTHS returns the date date plus integer months. The date argument can be a
datetime value or
any value that can be implicitly converted to DATE. The integer argument can be an integer or
any value that can be implicitly converted to an integer. The return type is always DATE,
regardless of the datatype of date. If date is the last day of the month or if the resulting month
has fewer days than the day component of date, then the result is the last day of the resulting
month. Otherwise, the result has the same day component as date.
Example: -
ADD_MONT
12-02-20
19
• select add_months ('12/8/2019',3) from dual;
ADD_MONT
12-11-19
CURRENT_DATE
Syntax: - current_date
CURRENT_DATE returns the current date in the session time zone, in a value in the
Gregorian calendar of datatype DATE.
CURRENT_
23-12-19
CURRENT_TIMESTAMP
Syntax: - current_timestamp(precision)
CURRENT_TIMESTAMP returns the current date and time in the session time zone, in a value
of datatype TIMESTAMP WITH TIME ZONE. The time zone offset reflects the current local
time of the SQL session. If you omit precision, then the default is 6. The difference between this
Example: -
CURRENT_TIMESTAMP
LAST_DAY
Syntax: - last_day(date)
20
LAST_DAY returns the date of the last day of the month that contains the date. The
Example: -
LAST_DAY
31-01-19
LAST_DAY
31-12-19
MONTHS_BETWEEN
MONTHS_BETWEEN returns number of months between dates date1 and date2. If date1 is
later than date2, then the result is positive. If date1 is earlier than date2, then the result is
negative. If date1 and date2 are either the same days of the month or both last days of months,
then the result is always an integer. Otherwise Oracle Database calculates the fractional
portion of the result based on a 31-day month and considers the difference in time components
Example: -
MONTHS_BETWEEN ('27/02/2001','11/10/1998')
28.516129
21
MONTHS_BETWEEN ('27/02/2001','27/10/2001')
-8
NEW_TIME
NEW_TIME returns the date and time in time zone timezone2 when date and time in time
zone timezone1 are date. Before using this function, you must set the
NEW_TIME
10-10-99
NEXT_DAY
NEXT_DAY returns the date of the first weekday named by char that is later than the date
date. The return type is always DATE, regardless of the datatype of date. The argument char
must be a day of the week in the date language of your session, either the full name or the
abbreviation. The minimum number of letters required is the number of letters in the
abbreviated version. Any characters immediately following the valid abbreviation are
ignored. The return value has the same hours, minutes, and seconds component as the
argument date.
NEXT_DAY
25-12-19
22
ROUND (date)
ROUND returns date rounded to the unit specified by the format model fmt. The value
returned is always of datatype DATE, even if you specify a different datetime datatype for
date. If you omit fmt, then date is rounded to the nearest day. The date expression must
Example: -
ROUND (TO
01-10-19
ROUND (TO
01-11-19
• select round(to_date('23/12/2019'),'mon') from dual;
ROUND (TO
01-01-20
ROUND (TO
01-01-20
ROUND (TO
23
01-10-19
SYSDATE
Syntax: - sysdate
SYSDATE returns the current date and time set for the operating system on which the database
resides. The datatype of the returned value is DATE, and the format returned depends on the
value of the NLS_DATE_FORMAT initialization parameter. The function requires no
arguments. In distributed SQL statements, this function returns the date and time set for the
operating system of your local database.
Example: - select sysdate from dual;
SYSDATE
23-12-19
SYSTIMESTAMP
Syntax: - systimestamp
SYSTIMESTAMP returns the system date, including fractional seconds and time
zone, of the system on which the database resides. The return type is TIMESTAMP
SYSTIMESTAMP
TRUNC (date)
Syntax: - trunc (date, fmt)
The TRUNC (date) function returns date with the time portion of the day truncated to the
unit specified by the format model fmt. The value returned is always of datatype DATE,
even if you specify a different datetime datatype for date. If you omit fmt, then date is
truncated to the nearest day. Please refer to "ROUND and TRUNC Date Functions" for the
24
Example: - select trunc(to_date('25-oct-2001','DD-MON-YY'), 'YEAR')
01-01-01
4. AIM: Write the sample queries on conversion functions- to_date and to_char
Conversion functions convert a value from one datatype to another. Generally, the
form of the function names follows the convention datatype TO datatype. The first
datatype is the input datatype. The second datatype is the output datatype.
TO_CHAR
TO_DATE
TO_CHAR
Syntax: - to_char (n, fmt, ‘nlsparam’)
Example: -
Monday 12-23-2019
25
TO_DATE
to a value of DATE datatype. The fmt is a datetime model format specifying the format of
char. If you omit fmt, then char must be in the default date format. If fmt is J, for Julian,
TO_DATE (
02-10-01
TO_DATE (
12-02-19
5. AIM: Write the sample queries using DML commands – insert, update,
Data Manipulation Language (DML) statements or commands are used for managing
• DELETE – deletes all records from a table, the space for the records remain
Insert:
INSERT INTO <table name> VALUES (<value 1>, ... <value n>);
26
Example:
and the data type of each attribute. Character type values are always enclosed in single
quotes; number values are never in quotes; date values are often (but not always) in the
UPDATE:
The update statement is used to change values that are already in a table.
UPDATE <table name> SET <attribute> = <expression> WHERE <condition>;
Example:
UPDATE STUDENT SET Name = ‘Amar’ WHERE StudID=1001;
The update expression can be a constant, any computed value, or even the result of a
DELETE:
Example:
DELETE FROM STUDENT WHERE StudID=1001;
If the WHERE clause is omitted, then every row of the table is deleted that matches
SELECT:
The SELECT statement is used to form queries for extracting information out of the
Example:
27
6. AIM: Write the sample queries on aggregate functions (min, max, count, sum,
avg) Aggregate functions in DBMS take multiple rows from the table and return a value
Syntax:
AVG Function
This function returns the average value of the numeric column that is supplied as a
AVG(SAL)
28
2073.21429
COUNT Function
The count function returns the number of rows in the result. It does not count the null
values. Types:
1. COUNT (*): Counts all the number of rows of the table including null.
in a column. Example:
COUNT(SAL)
14
MAX Function
The MAX function is used to find maximum value in the column that is supplied as a
MAX(SAL)
5000
MIN Function
The MIN function is used to find minimum value in the column that is supplied as a
MIN(SAL)
29
800
SUM Function
SUM(SAL)
29025
7. AIM: Write the sample queries on set operations (union, intersect and minus) SQL
supports few Set operations which can be performed on the table data. These are used to
get meaningful results from data stored in the table, under different special conditions. In
this tutorial, we will cover 4 different types of SET operations, along with example: 1.
UNION
2. INTERSECT
3. MINUS
UNION
UNION is used to combine the results of two or more SELECT statements. However,
it will eliminate duplicate rows from its result set. In case of union, number of columns
and datatype must be same in both the tables, on which UNION operation is being
applied.
Example: - select * from scott.emp where deptno=10 union select * from scott.emp
where sal>3000;
30
INTERSECT
Intersect operation is used to combine two SELECT statements, but it only returns the
records which are common from both SELECT statements. In case of Intersect the
Example: - select * from scott.emp where deptno=10 intersect select * from scott.emp
where sal>3000; EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
MINUS
The Minus operation combines results of two SELECT statements and return only
those in the final result, which belongs to the first set of the result.
Example: - select * from scott.emp where deptno=10 intersect select * from scott.emp where
8. AIM: Write the sample queries using group by and order by functions
SQL’s ORDER BY, GROUP BY, are a few of the cornerstones in SQL for managing
and organizing the data received from the database. ORDER BY handles the order the
records will be returned. GROUP BY finds similar results and clumps them together.
Two more important keywords are commonly used with ORDER BY, they are
DESC for descending and ASC for ascending. SQL defaults with ascending
order. You would just implement it like so: ORDER BY username DESC.
31
Syntax for order by function:
The GROUP BY Statement in SQL is used to arrange identical data into groups with
the help of some functions. i.e. if a particular column has same values in different rows
Important Points:
• In the query, GROUP BY clause is placed before ORDER BY clause if used any.
Syntax:
FROM table_name
WHERE condition
Example: -
BNAME AVG(A_SAL)
HYDERABAD 25500
32
MADHAPUR 95000
BNAME COUNT(A_NO)
HYDERABAD 2
MADHAPUR 1
HAVING Clause
We know that WHERE clause is used to place conditions on columns but what if we
This is where HAVING clause comes into use. We can use HAVING clause to place
conditions to decide which group will be the part of final result-set. Also, we cannot
use the aggregate functions like SUM (), COUNT () etc. with WHERE clause. So,
we have to use HAVING clause if we want to use any of these functions in the
conditions.
Syntax:
FROM table_name
WHERE condition
Example: -
HYDERABAD 25500
MADHAPUR 95000
33
• select avg(a_bal) from account, customer, depositor
AVG(A_SAL)
5000
9. AIM: Write the sample queries using some, any and all operators
The ‘ALL’, ‘ANY’, ’SOME’ operator compares value to every value returned by the
subquery. All of these operators must follow a comparison operator. The syntax of
Example: -
ENAME SAL
ALLEN 1600
JONES 2975
BLAKE 2850
CLARK 2450
SCOTT 3000
KING 5000
TURNER 1500
FORD 3000
34
Example: -
Example: -
JOB
CLERK
SALESMAN
DEPT(deptno,dname,……)
SALGRADE(… .... )
Using the various integrity constraints like primary key, foreign key, not null, check constraints
while creating and altering the tables.
QUERY:
create table aemp(
eno number(4) CONSTRAINT aemp_eno_u UNIQUE ,
ename varchar(20) CONSTRAINT aemp_name_nn NOT NULL,
ejob varchar(20), esal number(10),
edept number(5) CONSTRAINT aemp_edept_pk PRIMARY KEY);
create table adept(
35
deptno number(5) CONSTRAINT adept_no_fk REFERENCES
aemp(edept), deptname varchar(10)); create table asalgrade( asal
number(10), agrade varchar(5));
OUTPUT :
11. AIM :Write the sample queries using other DDL commands- alter, truncate,
drop.
QUERY :
create table aemp(
eno number(4) CONSTRAINT aemp_eno_u UNIQUE ,
ename varchar(20) CONSTRAINT aemp_name_nn NOT NULL,
ejob varchar(20), esal number(10),
edept number(5) CONSTRAINT aemp_edept_pk PRIMARY KEY);
create table adept(
deptno number(5) CONSTRAINT adept_no_fk REFERENCES
aemp(edept), deptname varchar(10)); create table asalgrade( asal
number(10), agrade varchar(5)); alter table aemp drop column eno; truncate
table asalgrade;
OUTPUT :
36
12. AIM: Write the sample queries using DML commands – insert, update, delete
and select
Data Manipulation Language (DML) statements or commands are used for managing data within
tables. Some commands of DML are:
Some commands of DML are:
• SELECT – retrieve data from the database
• INSERT – insert data into a table
• UPDATE – updates existing data within a table
• DELETE – deletes all records from a table, the space for the records remain
Insert:
The insert statement is used to add new row to a table.
INSERT INTO <table name> VALUES (<value 1>, ... <value n>);
Example:-
INSERT INTO student(Roll_no,NAM,Marks,CGPA,Attendence,phone_no)
VALUES(130,jyoshna,98,8.6,97,9999999999);
1 row inserted.
UPDATE:
The update statement is used to change values that are already in a table. UPDATE
<table name> SET <attribute> = <expression> WHERE <condition>;
Example:
UPDATE STUDENT SET Name = ‘Amar’ WHERE StudID=1001;
1 row updated
DELETE:
The delete statement deletes row(s) from a table.
DELETE FROM <table name> WHERE <condition>;
37
Example:-
DELETE FROM student WHERE Attendence<65;
1 row deleted.
SELECT:
The SELECT statement is used to form queries for extracting information out of the database.
SELECT <attribute>, ....... , <attribute n> FROM <table name>;
Example:
SELECT StudID, Name FROM STUDENT;
AIM:Write the sample queries using DCL commands – grant and revoke.
• System: This includes permissions for creating session, table, etc and all types of other
system privileges.
• Object: This includes permissions for any command or query to perform any operation
• GRANT: Used to provide any user access privileges or other priviliges for the database.
OUTPUT:
38
13. AIM:Write the sample queries using TCL commands – commit, rollback and savepoint.
COMMIT :
DESCRIPTION: command is used to permanently save any transaction into the database.
ROLLBACK command restores the database to last commited state. It is also used with the
SAVEPOINT command to jump to a savepoint in an ongoing transaction.
SAVEPOINT command is used to temporarily save a transaction so that you can rollback to that
point whenever required.
QUERIES:
OUTPUT :
SAVEPOINT A; SELECT
* FROM EMP130;
39
OUTPUT :
SAVEPOINT B; SELECT
* FROM EMP130;
OUTPUT :
3)ROLLBACK TO A;
OUTPUT :
40
41
42
43
44
[Type here]
45
46
47
U cH
using the
li t OrdCr to ••• a s cq'Llcncc, you must first gcnCratC the initial sequence nlJ mbcr by
OUTPUT :
The CURRV AL option returns ihc current sequence number, but ivlll not e.tecute unless the
Sequence has been callCd at lCdSi one time using ilie N EXTVAL option.
QUERY :
job.
QUERY:
select
upper(SUBSTR(ENAME,-3,3)),JOB
FROM myemp;
OUTPUT:
18. Display all the employees who earning salary not in the range of 2500 and5000 in
department 10 &20
QUERY:
SELECT *
FROM myemp
where (sal NOT BETWEEN 2500 AND 5000)AND(deptno=10 OR deptno=20);
OUTPUT:
52
19. List the emps whose jobs are same as SMITH or ALLEN.
QUERY:
select *
from myemp where job in(select job from myemp where ename
in('SMITH','ALLEN'));
OUTPUT:
20.
53
21. How many employees are there in each department?
QUERY:
SELECT deptno,count(*)
no_of_employees from myemp group by
deptno;
54
22. Display the number of employee for each job group deptno wise.
QUERY:
SELECT deptno,job,count(*) no_of_employees from
myemp
group by deptno,job;
OUTPUT:
55
24. List the emps who are either ‘CLERK’ or ‘ANALYST’ in the Desc order.
QUERY:
SELECT ENAME,JOB
FROM myemp
WHERE job IN ('CLERK','ANALYST')
order by ename DESC;
OUTPUT:
25. Which department has highest number of salesman, show the department number and the
Count?
QUERY:
select deptno,count(*) from myemp where
job='SALESMAN' and deptno in
(select deptno from myemp where job='SALESMAN' group by deptno having count(*) in (select
max(count(*)) from myemp where job='SALESMAN' group by deptno)) group by deptno;
OUTPUT:
QUERY:
select * from myemp where sal in (select
min(sal) from myemp
where deptno in(select deptno from scott.dept where dname='SALES'));
OUTPUT:
56
select DISTINCT job from
myemp;
OUTPUT:
29. Find all the employees whose salary can be <2000 or >4000 QUERY:
SELECT ename,sal
FROM myemp
WHERE sal NOT BETWEEN 2000 AND 4000;
OUTPUT:
57
30. Find all the employees whose name starts with ‘S’ and has 6 characters in the name.
QUERY:
select ename from myemp
where ename like 'S ';
OUTPUT:
no rows selected
31. Find out all those managers and jr.managers who are drawing salary more than 10,000
QUERY:
select ename,sal from
myemp
where job='MANAGER' AND sal>=10000;
OUTPUT:
no rows selected
32. Write the query to display the employee as well as department details department wise.
QUERY:
select ename,sal,dname,loc from
myemp,scott.dept
where myemp.deptno=scott.dept.deptno;
58
OUTPUT:
33. List the details of most recently hired emp of dept 30.
QUERY:
SELECT *
FROM myemp where deptno=30 AND HIREDATE IN (SELECT MAX(HIREDATE)
FROM myemp where deptno=30);
34. List the emps who joined in the company on the same date.
QUERY:
select e.*
from myemp e,myemp s
where e.HIREDATE=s.HIREDATE AND e.empno<>s.empno;
OUTPUT:
59
35. Get employee details from employee table who joined before January 1st 2013 QUERY:
select *
from myemp
where HIREDATE<'01-JAN-2013';
OUTPUT:
60
36. AIM : Select all the employees who are earning same as SMITH
QUERY :
select ename from MYEMP where sal=(select sal from MYEMP where ename='SMITH');
OUTPUT :
QUERY:
select empno,ename,sal from MYEMP e1 where &n=(select count(distinct(sal)) from MYEMP
e2 where e2.sal>=e1.sal);
OUTPUT :
38. AIM :For each department show its deptno and average salary. Sort the result in
descending order of the average salary.
QUERY :
select deptno,avg(sal) from MYEMP group by deptno order by avg(sal) desc;
OUTPUT :
61
39. AIM :Display the Empno, Ename, job, Hiredate, Experience of all Managers.
QUERY :
select ename,empno,job,hiredate,round((current_date-hiredate)/365) experience from MYEMP
where job='MANAGER';
OUTPUT :
40. AIM :Form the employee table by generating the following output:
Who , what , and when
…………………………………………………………………………………………..
QUERY :
select ename || ' is held the position of '||job ||' in dept no '|| deptno from MYEMP;
OUTPUT :
41. AIM :Find the minimum, maximum and average salary for each job title.
62
QUERY :
SELECT JOB,MIN(SAL),MAX(SAL),AVG(SAL) FROM MYEMP
GROUP BY JOB;
OUTPUT :
42. AIM :Show the details of the staff who are not working in the research department.
QUERY :
select empno,ename,job,DNAME
from myemp NATURAL JOIN DEPT
where deptno NOT in (select deptno from dept where dname='RESEARCH');
OUTPUT :
43. AIM:Calculate the number of months between today and hired date of the employee.
Order the results by the number of months.
QUERY :
select MONTHS_BETWEEN(current_date,hiredate) months,ename from myemp order by
months;
OUTPUT :
63
44. AIM :List the details of the department where maximum number of emps are working.
QUERY :
select deptno,dname,loc,count(*)
from myemp natural join dept
group by deptno,dname,loc
having count(*) in (select max(count(*)) from myemp group by deptno);
OUTPUT :
64
pl/sql programs :
46. AIM : Write a pl/sql block to find out if a number is odd or even.
PROGRAM:
declare
n integer:= &n;
begin
if mod(n,2)=0 then
dbms_output.put_line('num1 is even');
else
dbms_output.put_line('num1 is odd');
end if;
end;
OUTPUT :
47. AIM :Write a pl/sql block to input a number with substitution variable and then print
its multiplication table using for and while loop
65
PROGRAM:
declare
n integer:=&n;
i integer;
m integer;
limit integer:=&limit;
begin
i:=1;
dbms_output.put_line('multiplication table of:'||n);
for i in 1..limit
loop
m:=n*i;
dbms_output.put_line(n||'*'||i||'='||m);
end loop;
end;
OUTPUT :
66
48. AIM :Write a pl/sql block to avail 20% bonus to all employees who are receiving the
commission.
PROGRAM :
select * from myemp;
begin
update myemp
set sal=sal+(sal*0.2)
where comm is not null;
end;
OUTPUT :
49. AIM :Write a pl/sql block using implicit cursors to get the number of employees.
PROGRAM :
IMPLICIT :
declare
total number(10);
begin
update myemp
set comm=comm+0;
total:=sql%rowcount;
dbms_output.put_line('total number of employees are :' || total);
end;
OUTPUT :
67
EXPLICIT:
declare
e_no myemp.empno%type;
e_name myemp.ename%type;
e_job myemp.job%type;
e_sal myemp.sal%type;
cursor e_emp1 is select empno,ename,job,sal
from myemp;
begin
open e_emp1;
dbms_output.put_line('total number of employees are:');
loop
fetch e_emp1 into e_no,e_name,e_job,e_sal;
exit when e_emp1%notfound;
end loop;
dbms_output.put_line(e_emp1%rowcount);
close e_emp1;
end;
OUTPUT :
50. AIM :Write a pl/sql block using explicit cursors to get the employee data. Print the
employee’s annual salary if the amount is less than 50000.
PROGRAM :
declare
e_no myemp.empno%type;
e_name myemp.ename%type;
e_job myemp.job%type;
e_sal myemp.sal%type;
cursor e_emp is
select empno,ename,job,sal*12 from myemp
where((sal*12)<50000);
begin
open e_emp;
dbms_output.put_line('salaries of emloyees who earn less than 50000 per annum are:');
loop
fetch e_emp into e_no,e_name,e_job,e_sal;
exit when e_emp%notfound;
68
dbms_output.put_line(e_sal);
end loop;
close e_emp;
end;
OUTPUT :
51. AIM :Write a pl/sqlblock to find the maximum of two numbers using functions.
PROGRAM:
DECLARE
a number :=&a;
b number :=&b;
c number;
FUNCTION findMax(x IN number, y IN number)
RETURN number
IS
z number;
BEGIN
IF x > y THEN
z:= x;
ELSE
Z:= y;
END IF;
RETURN z;
END;
BEGIN
c := findMax(a, b);
dbms_output.put_line(' Maximum of (a,b): ' || c);
END;
OUTPUT :
69
70