Top Banner
A PROJECT FILE ON SQL QUERIES SUBMITTED TO: SUBMITTED BY:
124
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Oracle

A PROJECT FILEON

SQL QUERIES

SUBMITTED TO: SUBMITTED BY:

Page 2: Oracle

TABLES USED IN THE QUERIES

Emp545tableEMP_ID FIRST_NAME LAST_NAME EMAIL PH_NO HIRE_DATE JOB_ID SALARY COMM_PCT DEPT_ID MGR_ ID

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

100 Steven King SKING 515.123.4567 17-JUN-87 AD_PRES 24000 0 90

101 Neena Kochhar NKOCHHAR 515.123.4568 21-SEP-89 AD_VP 17000 0 90 100

102 Lex De Haan LDEHAAN 515,123.4569 13-JAN-93 AD_VP 17000 0 90 100

103 Alexander Hunold AHUNOLD 590.423.4567 03-JAN-90 IT_PROG 9000 0 60 102

104 Bruce Ernst BERNST 590.423.4568 21-MAY-91 IT_PROG 6000 0 60 103

107 Diana Lorentz DLORENTZ 590.423.5567 07-FEB-99 IT_PROG 4200 0 60 103124 Kevin Mourgos KMOURGOS 650.123.5234 16-NOV-99 ST_MAN 5800 0 50 100

141 Trenna Rajs TRAJS 650.121.8009 17-OCT-95 ST_CLERK 3500 0 50 124

142 Curtis Davies CDAVIES 650.121.1994 29-JAN-97 ST_CLERK 3100 0 50 124

143 Randall Matos RMATOS 650.123.5234 15-MAR-98ST_CLERK 2600 0 50 124

Page 3: Oracle

Dept545 table

DEPT_ID DEPT_NAME MGR_ID LOC_ID

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

10 Administration 200 1700

20 Marketing 201 1800

50 Shipping 124 1500

60 IT 103 1500

80 Sales 149 2500

90 Executive 100 1700

110 Accounting 205 1700

190 Contracting 0 1700

Page 4: Oracle

Job History EMP_ID STRT_DAT END_DATE JOB_ID DEPT_ID

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

102 13-JAN-93 24-JUL-98 IT_PROG 60

101 21-SEP-89 15-OCT-93 AC_ACCOUNT 110

101 28-OCT-93 15-MAR-97 AC_MGR 110

201 17-FEB-96 19-DEC-99 MK_REP 20

114 24-MAR-98 31-DEC-99 ST_CLERK 50

122 01-JAN-99 31-DEC-99 ST_CLERK 50

200 17-SEP-97 17-JUN-93 AD_ASST 90

176 24-MAR-98 31-DEC-98 SA_REP 80

176 01-JAN-99 31-DEC-99 SA_MAN 80

200 01-JUL-94 31-DEC-98 AC_ACCOUNT 90

Job grades

GRA LOWEST_SAL HIGHEST_SAL

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

A 1000 2999

B 3000 5999

C 6000 9999

D 10000 14999

Page 5: Oracle

E 15000 24999

F 25000 40000

Countries

CO COUNTRY_NAME REGION_ID

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

CA Canada 2

DE Germany 1

UK United Kingdom 1

US United States of America 2

Locations

LOC_ID STR_ADD POST_CODE CITY STATE_PROV CO

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

1400 2014 Jabberwocky Rd 26192 Southlake Texas US

1500 2011 Interiors Blvd 99236 South San Francisco California US

1700 2004 Charde Rd 98199 Seattle Washington US

1800 460 Bloor St.W. ON M5S 1XB Toronto Ontario CA

2500 Magdalen Center OX9 9ZB Oxford Oxford UK

Page 6: Oracle

Chapter-1 Basic SQL Statements

1) Show the structure of the dept545 table. Select all data from the table.

QUERY:

SQL>describe dept545;

Name Null? Type

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

DEPT_ID NUMBER(3)

DEPT_NAME VARCHAR2(18)

MGR_ID NUMBER(3)

LOC_ID NUMBER(5)

SQL>select * from dept545;

DEPT_ID DEPT_NAME MGR_ID LOC_ID

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

10 Administration 200 1700

20 Marketing 201 1800

50 Shipping 124 1500

60 IT 103 1500

80 Sales 149 2500

90 Executive 100 1700

110 Accounting 205 1700

Page 7: Oracle

190 Contracting 0 1700 8 rows selected.2) Show the structure of emp545 table. Create a query to display the last name, job code, hire date and employee number for each employee with employee with employee number appearing first. Provide an alias STARTDATE for the HIRE_DATE column.

QUERY:

SQL>describe emp545;

Name Null? Type

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

EMP_ID NUMBER(3)

FIRST_NAME VARCHAR2(18)

LAST_NAME VARCHAR2(18)

EMAIL VARCHAR2(15)

PH_NO NUMBER(20)

HIRE_DATE DATE

JOB_ID VARCHAR2(12)

SALARY NUMBER(10)

COMM_PCT NUMBER(3)

DEPT_ID NUMBER(4)

SQL>select emp_id, last_name, job_id, hire_date as "StartDate" from emp545;

EMP_ID LAST_NAME JOB_ID StartDate

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

100 King AD_PRES 17-JUN-87

Page 8: Oracle

101 Kochhar AD_VP 21-SEP-89

102 De Haan AD_VP 13-JAN-93

103 Hunold IT_PROG 03-JAN-90

104 Ernst IT_PROG 21-MAY-91

107 Lorentz IT_PROG 07-FEB-99

124 Mourgos ST_MAN 16-NOV-99

141 Rajs ST_CLERK 17-OCT-95

142 Davies ST_CLERK 29-JAN-97

143 Matos ST_CLERK 15-MAR-98

10 rows selected.

3) Create a query to display the employee number, last name, job ID and hire date from emp545 table.

QUERY:

SQL> select emp_id, last_name, job_id,hire_date from emp545;

EMP_ID LAST_NAME JOB_ID HIRE_DATE

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

100 King AD_PRES 17-JUN-87

101 Kochhar AD_VP 21-SEP-89

102 De Haan AD_VP 13-JAN-93

103 Hunold IT_PROG 03-JAN-90

104 Ernst IT_PROG 21-MAY-91

107 Lorentz IT_PROG 07-FEB-99

Page 9: Oracle

124 Mourgos ST_MAN 16-NOV-99

141 Rajs ST_CLERK 17-OCT-95

142 Davies ST_CLERK 29-JAN-97

143 Matos ST_CLERK 15-MAR-9810 rows selected.

4) Create a query to display unique job codes from the EMP545 table.

QUERY:

SQL>select distinct job_id from emp545;

JOB_ID

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

AD_PRES

AD_VP

IT_PROG

ST_CLERK

ST_MAN

5) Copy the statement from 8th question. Name the headings Emp #, Employee, Job and hire date. Run your query.

QUERY:

SQL>select emp_id as "Emp #", last_name as "Employee", job_id as "Job",hire_date as "Hire Date” from emp545;

Emp # Employee Job Hire Date

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

100 King AD_PRES 17-JUN-87

Page 10: Oracle

101 Kochhar AD_VP 21-SEP-89

102 De Haan AD_VP 13-JAN-93

103 Hunold IT_PROG 03-JAN-90

104 Ernst IT_PROG 21-MAY-91

107 Lorentz IT_PROG 07-FEB-99

124 Mourgos ST_MAN 16-NOV-99

141 Rajs ST_CLERK 17-OCT-95

142 Davies ST_CLERK 29-JAN-97

143 Matos ST_CLERK 15-MAR-98

10 rows selected.

6) Display the last name concatenated with job ID, separated by a comma and space and name the column Employee and Title.

QUERY:

SQL>select last_name||' ,'||job_id "Employee and Title" from emp545;

Employee and Title

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

King, AD_PRES

Kochhar, AD_VP

De Haan, AD_VP

Hunold, IT_PROG

Ernst, IT_PROG

Lorentz, IT_PROG

Mourgos, ST_MAN

Page 11: Oracle

Rajs, ST_CLERK

Davies, ST_CLERK

Matos, ST_CLERK

10 rows selected.

7) Create a query to display all the data from the EMP545 table. Separate each column by a comma. Name the column THE_OUTPUT.

QUERY:

SQL>select emp_id ||','|| first_name ||','|| last_name ||','|| email ||','||ph_no||','||','|| job_id ||','||hire_date||','|| salary ||','|| comm_pct ||','||dept_id THE_OUTPUTfrom emp545;

THE_OUTPUT

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

100,Steven, King,SKING,-4175,,AD_PRES,17-JUN-87,24000,0,90

101,Neena,Kochhar,NKOCHHAR,-4176,,AD_VP,21-SEP-89,17000,0,90

102,Lex,De Haan,LDEHAAN,-4177,,AD_VP,13-JAN-93,17000,0,90

103,Alexander,Hunold,AHUNOLD,-4400,,IT_PROG,03-JAN-90,9000,0,60

104,Bruce,Ernst,BERNST,-4401,,IT_PROG,21-MAY-91,6000,0,60

107,Diana,Lorentz,DLORENTZ,-5400,,IT_PROG,07-FEB-99,4200,0,60

124,Kevin,Mourgos,KMOURGOS,-4707,,ST_MAN,16-NOV-99,5800,0,50

141,Trenna,Rajs,TRAJS,-7480,,ST_CLERK,17-OCT-95,3500,0,50

142,Curtis,Davies,CDAVIES,-2465,,ST_CLERK,29-JAN-97,3100,0,50

143,Randall,Matos,RMATOS,-2345,,ST_CLERK,15-MAR-98,2600,0,50

10 rows selected.

Page 12: Oracle

Chapter-2 Restricting and Sorting Data

1)Create a query to display the last name and salary of emp545 earning more than $12,000.Place your SQL statement in a text file named.

QUERY:

SQL>select last_name,salary from emp545 where salary > 12000;

LAST_NAME SALARY

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

King 24000

Kochhar 17000

De Haan 17000

2) Create a query to display the employee last name and department number for employee number 176.

QUERY:

SQL>select last_name, dept_id from emp545 where emp_id=176;

no rows selected

3 Create a query to display the last name and salary for all emp545 whose salary is not in the range of $5,000b and $12,000.Run your SQL statement.

QUERY:

SQL>select last_name, salary from emp545 where salary not between 5000 and 12000;

LAST_NAME SALARY

Page 13: Oracle

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

King 24000

Kochhar 17000

De Haan 17000

Lorentz 4200

Rajs 3500

Davies 3100

Matos 2600

7 rows selected.

4) Display the last name,job ID,and start date of emp545 hired between February 20,1998 and May 1,1998.order the query in ascending order by start date.

QUERY:

SQL>select last_name, job_id, hire_date from emp545 where hire_date between '20-feb-98' and '1-may-98' order by hire_date;

LAST_NAME JOB_ID HIRE_DATE

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

Matos ST_CLERK 15-MAR-98

5) Display the last name and department number of all emp545 in department 20 and 50 in alphabetical order by name.

QUERY:

SQL>select last_name, dept_id from emp545 where dept_id in (20,50) order by last_name;

LAST_NAME DEPT_ID

Page 14: Oracle

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

Davies 50Matos 50

Mourgos 50

Rajs 50

6) Create a query to list the last name and salary of emp545 who earn between $5,000 and $12,000 and are in department 20 or 50.Label the columns employee and monthly salary.

QUERY:

SQL>select last_name as "employee", salary as "monthly salary" from emp545 where salary between5000 and 12000 and dept_id in (20,50);

employee monthly salary

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

Mourgos 5800

7) Display the last name and hire date of every employee who was hired in 1994.

QUERY:

SQL>select last_name, hire_date from emp545 where hire_date like '%94';

no rows selected

8) Display the last name and job title of all emp545 who do not have a manager.

QUERY:

SQL> select last_name, job_id from emp545 where mgr_id is null;

LAST_NAME JOB_ID

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

Page 15: Oracle

King AD_PRES

Kochhar AD_VP

De Haan AD_VP

Hunold IT_PROG

Ernst IT_PROG

Lorentz IT_PROG Mourgos ST_MAN

Rajs ST_CLERK

Davies ST_CLERK

Matos ST_CLERK

10 rows selected.

9) Display the last name, salary and commission for all emp545 who earn commissions. Sort data in descending order of salary and commissions.

QUERY:

SQL>select last_name, salary, comm_pct from emp545 where comm_pct is not nullorder by salary desc,comm_pct desc;

LAST_NAME SALARY COMM_PCT

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

King 24000 0

Kochhar 17000 0

De Haan 17000 0

Hunold 9000 0

Ernst 6000 0

Mourgos 5800 0

Page 16: Oracle

Lorentz 4200 0

Rajs 3500 0

Davies 3100 0

Matos 2600 0

10 rows selected.

10) Display the last names of all emp545 where the third letter of the name is an a.

QUERY:

SQL>select last_name from emp545 where last_name like '__a';

no rows selected

11) Display the last name of all emp545 who have an a and e in their last name.

QUERY:

SQL>select last_name from emp545 where last_name like '%a%' andlast_name like '%e%';

LAST_NAME

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

De Haan

Davies

12) Display the last name, job and salary for all emp545 whose job is sales representative or stock clerk and whose salary is not equal to $2,500,$3,500 or $7,000.

QUERY:

SQL>select last_name, job_id, salary from emp545 where job_id in

Page 17: Oracle

('SA_REP','ST_CLERK') and salary not in (2500,3500,7000);

LAST_NAME JOB_ID SALARY

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

Davies ST_CLERK 3100

Matos ST_CLERK 2600

13) Create a query to display the last name, salary and commission for all emp545 whose commission amount is 20%.

QUERY:

SQL>select last_name as "EMPLOYEE", salary as "MONTHLY SALARY",comm_pct from emp545where commission_pct = .20;

no rows selected

Page 18: Oracle

Chapter-3 Single Row Functions

1)Write a query to display the current date.Label the column Date.

QUERY:

SQL>select sysdate as "Date" from dual;

Date

---------

13-JUL-08

2)For each employee, display the employee number,last_name,salary and salary increased by 15% and expressed as a whole number. Label the column new salary.

QUERY:

SQL>select emp_id, last_name, salary, round (salary*1.15, 0) "New Salary" from emp545;

EMP_ID LAST_NAME SALARY New Salary

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

100 King 24000 27600

101 Kochhar 17000 19550

102 De Haan 17000 19550

103 Hunold 9000 10350

Page 19: Oracle

104 Ernst 6000 6900

107 Lorentz 4200 4830

124 Mourgos 5800 6670

141 Rajs 3500 4025

142 Davies 3100 3565

143 Matos 2600 2990

10 rows selected.

3)Run your query as in the last question.

QUERY:

SQL>select emp_id,last_name,salary,round(salary*1.15,0) "New Salary" from emp545;

EMP_ID LAST_NAME SALARY New Salary

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

100 King 24000 27600

101 Kochhar 17000 19550

102 De Haan 17000 19550

103 Hunold 9000 10350

104 Ernst 6000 6900

107 Lorentz 4200 4830

124 Mourgos 5800 6670

141 Rajs 3500 4025

142 Davies 3100 3565

143 Matos 2600 2990

Page 20: Oracle

10 rows selected.

4) Modify your query.Add a column that subtracts the old salary from the new salary.Label the column Increase.

QUERY:

SQL>select emp_id, last_name, salary, round(salary*1.15 , 0) "New Salary",

round (salary*1.15 , 0)-salary "Increase" from emp545;

EMP_ID LAST_NAME SALARY New Salary Increase

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

100 King 24000 27600 3600

101 Kochhar 17000 19550 2550

102 De Haan 17000 19550 2550 103 Hunold 9000 10350 1350

104 Ernst 6000 6900 900

107 Lorentz 4200 4830 630

124 Mourgos 5800 6670 870

141 Rajs 3500 4025 525

142 Davies 3100 3565 465

143 Matos 2600 2990 390

10 rows selected.

5) Write a query that displays the employee’s last names with the first letter capitalized and all other letters lowercase and the length of all employees whose name starts with J,A or M.Give each column an appropriate label. Sort the results by the employees last names.

QUERY:

Page 21: Oracle

SQL>select initcap(last_name) "Name”, length(last_name) "Length" from emp545

where last_name like 'J%' or last_name like 'M%' or last_name like 'A%'

order by last_name;Name Length

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

Matos 5

Mourgos 7

6)For each employee, display the employee’s last name, and calculate the months between today and the date the employee was hired. Label the column MONTHS_WORKED. Order your results by the number of months employed. Record the number of months up to the closest whole number.

QUERY:

SQL>select last_name, round(months_between (sysdate ,hire_date)) Months_Worked from emp545 order by months_between(sysdate,hire_date);

LAST_NAME MONTHS_WORKED

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

Mourgos -1096

Lorentz -1087

Matos -1076

Davies -1063

Rajs -1047

De Haan -1014

Ernst -994

Hunold -978

Page 22: Oracle

Kochhar -974

King -947

10 rows selected.7) Write a query that produces the following for each employee <employee last name> earns <salary> monthly but wants <3 times salary>.Label the column Dream Salaries.

QUERY:

SQL>select last_name || 'earns'|| to_char(salary,'fm$99,999.00')|| 'monthly but wants'|| to_char(salary*3,'fm$99,999.00')||'.' "Dream Salaries" from emp545;

Dream Salaries

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

Kingearns$24,000.00monthly but wants$72,000.00.

Kochharearns$17,000.00monthly but wants$51,000.00.

De Haanearns$17,000.00monthly but wants$51,000.00.

Hunoldearns$9,000.00monthly but wants$27,000.00.

Ernstearns$6,000.00monthly but wants$18,000.00.

Lorentzearns$4,200.00monthly but wants$12,600.00.

Mourgosearns$5,800.00monthly but wants$17,400.00.

Rajsearns$3,500.00monthly but wants$10,500.00.

Daviesearns$3,100.00monthly but wants$9,300.00.

Matosearns$2,600.00monthly but wants$7,800.00.

10 rows selected.

8)Create a query to display the last name and salary for all emp545.Format the salary to be 15 characters long,left padded with $.Label the column SALARY.

Page 23: Oracle

QUERY:

SQL> select last_name,lpad(salary,15,'$') SALARY from emp545;

LAST_NAME SALARY

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

King $$$$$$$$$$24000

Kochhar $$$$$$$$$$17000

De Haan $$$$$$$$$$17000

Hunold $$$$$$$$$$$9000

Ernst $$$$$$$$$$$6000

Lorentz $$$$$$$$$$$4200

Mourgos $$$$$$$$$$$5800

Rajs $$$$$$$$$$$3500

Davies $$$$$$$$$$$3100

Matos $$$$$$$$$$$2600

10 rows selected.

9) Display each employee’s last name; hire date and salary review date, which is the first Monday after six months of service. Label the column REVIEW. Format the dates to appear in the format similar to “Monday, the Thirty-First of July, 2000”.

QUERY:

SQL> select last_name,hire_date,to_char(hire_date,'day') day from emp545 order by to_char(hire_date-1,'d');

LAST_NAME HIRE_DATE DAY

Page 24: Oracle

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

Ernst 21-MAY-91 monday

Mourgos 16-NOV-99 monday

Rajs 17-OCT-95 monday

King 17-JUN-87 tuesday

De Haan 13-JAN-93 tuesday

Davies 29-JAN-97 tuesday

Hunold 03-JAN-90 tuesday

Kochhar 21-SEP-89 wednesday

Lorentz 07-FEB-99 saturday

Matos 15-MAR-98 saturday

10 rows selected.

10) Create a query that displays the employees’ last names and commission amounts. If any employee does not earn commission, put “no commission”. Label the column COMM.

QUERY:

SQL> select last_name,nvl(to_char(commission_pct),'no commission') comm from emp545;

LAST_NAME COMM

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

King no commission

Kochhar no commission

De Haan no commission

Hunold no commission

Page 25: Oracle

Ernst no commission

Lorentz no commission

Mourgos no commission

Rajs no commission

Davies no commission

Matos no commission

10 rows selected.

11) Create a query that displays the employees’ last names and indicates the amounts of their annual salaries with asterisk.Each asterisk signifies thousand dollars.Sort the data in descending order of salary. Label the column EMPOYEES_AND_THEIR _SALARIES.

QUERY:

SQL> select rpad (last_name, 8) ||''|| rpad (' ', salary/1000+1, '*') employees_and_their_salariesfrom emp545order by salary desc;

EMPLOYEES_AND_THEIR_SALARIES

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

King ************************

Kochhar *****************

De Haan *****************

Hunold *********

Ernst ******

Mourgos *****

Page 26: Oracle

Lorentz ****

Rajs ***

Davies ***

Matos **

10 rows selected.12) Using decode function,write a query that displays the grade of all employee based on the value of the column JOB_ID,as per the foll. Data

Job Grade AD_PRES AST_MAN BIT_PROG CSA_REP DST_CLERK ENone of above 0

QUERY:

SQL> select job_id,decode (job_id,'ST_CLERK','E','sa_rep','D','IT_PROG','C','ST_MAN','B','ad_pres','A','0') grade from emp545;

JOB_ID G

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

AD_PRES A

AD_VP 0 AD_VP 0

IT_PROG C

IT_PROG C

IT_PROG C

Page 27: Oracle

ST_MAN B

ST_CLERK E

ST_CLERK E

ST_CLERK E10 rows selected.

Chapter-4 Displaying Data from Multiple Tables

1)Write a query to display the last name,department number,and department name for all employees.

QUERY:

SQL> select e.last_name, e.dept_id, d.dept_namefrom emp545 e, dept545 dwhere e.dept_id=d.dept_id;

LAST_NAME DEPT_ID DEPT_NAME

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

Mourgos 50 Shipping

Rajs 50 Shipping

Davies 50 Shipping

Matos 50 Shipping

Hunold 60 IT

Ernst 60 IT

Lorentz 60 IT

King 90 Executive

Kochhar 90 Executive

De Haan 90 Executive

Page 28: Oracle

10 rows selected.

2)Create a unique listing of all jobs that are in department 80.Include the location of the department in the output.

QUERY:

SQL> select DISTINCT job_id,loc_id from emp545,dept545 where emp545.dept_id=dept545.dept_id and emp545.dept_id=80;

no rows selected

3)Write a query to display the employees, last_name department_ name,location_id and city of all employees who earn a commission.

QUERY:

SQL> select e.last_name, d.dept_name, d.loc_id, l.city from emp545 e, dept545 d,

Loc545 l where e.dept_id=d.dept_id and d.loc_id=l.loc_id and

e.comm_pct is not null;

LAST_NAME DEPT_NAME LOC_ID CITY

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

Mourgos Shipping 1500 South San Francisco

Rajs Shipping 1500 South San Francisco

Davies Shipping 1500 South San Francisco

Page 29: Oracle

Matos Shipping 1500 South San Francisco

Hunold IT 1500 South San Francisco

Ernst IT 1500 South San Francisco

Lorentz IT 1500 South San Francisco

King Executive 1700 Seattle

Kochhar Executive 1700 Seattle

De Haan Executive 1700 Seattle

10 rows selected.

4) Display the employee last_name and department name for all the employes who have an a(lowercase) in their last names.

QUERY:

SQL> select last_name,dept_name from emp545,dept545where emp545.dept_id=dept545.dept_id and last_name like'%a%';

LAST_NAME DEPT_NAME

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

Rajs Shipping

Davies Shipping

Matos Shipping

Kochhar Executive

De Haan Executive

5.Create a query to display the name and hire_date of any employee hired after Davies.

Page 30: Oracle

QUERY:

SQL>Select e.last_name, e.hire_date from emp545 e, emp545 dwhere d .last_name = “Davies”and d.hire_date < e.hire_date ;

LAST_NAME HIRE_DATE---------------- ----------------Matos 15-mar-98“8 row selected

6. Display the names and hire dates for all employees who hired before their managers, along with their manager’s names and hire dates.

QUERY:

SQL>Select e.last_name, e.hire_date, a.last_name, a.hire_date from emp545 e, emp545 awhere e.mgr_id=a.mgr_idand e.hire_date < a.hire_date;

LAST_NAME HIRE_DATE LAST_NAME HIRE_DATE

Hunold 03-jan-90 De Haan 13-jan-93 Rajs 17-oct-95 Mourgos 16-nov-99 Davies 29-jan-97 Mougos 16-nov-99 Matos 15-mar-98 Mourgos 16-nov-99

Page 31: Oracle

Chapter-5 Aggregating Data Using Group Functions

1) Display the highest, lowest, sum, and salary of all the employees. Label the columns maximum, minimum, sum and average. Round your results to the nearest whole number

QUERY:

SQL> select round(max(salary),0) "Maximum",round(min(salary),0) "Minimum",round(sum(salary),0) “Sum”,round(avg(salary),0) "Average" from emp545;

Maximum Minimum Sum Average

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

24000 2600 92200 9220

2) Display the minimum,maximum,sum and average salary for each job type.

QUERY:

SQL> select job_id,round(max(salary),0) "Maximum",round(min(salary),0) "Minimum",round(sum(salary,0) "Sum",round(avg(salary),0) "Average" from emp545 group by job_id;

JOB_ID Maximum Minimum Sum Average

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

Page 32: Oracle

AD_PRES 24000 24000 24000 24000

AD_VP 17000 17000 34000 17000

IT_PROG 9000 4200 19200 6400

ST_CLERK 3500 2600 9200 3067ST_MAN 5800 5800 5800 5800

3) Write a query to display the number of people with the same job.

QUERY:

SQL> select job_id, count (*) from emp545 group by job_id;

JOB_ID COUNT (*)

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

AD_PRES 1

AD_VP 2

IT_PROG 3

ST_CLERK 3

ST_MAN 1

4) Determine the number of managers without listing them. Label the column Number of Managers.

QUERY:

SQL> select count (distinct mgr_id) "Number of Managers" from emp545;

Number of Managers

Page 33: Oracle

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

8

5) Write a query that display the difference between the highest and lowest salaries.Label the column DIFFERENCE.

QUERY:

SQL> select max(salary)-min(salary) DIFFERENCE from emp545;

DIFFERENCE

----------

21400

6) Display the manager number and salary of the lowest paid employee for the 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.

QUERY:

SQL> select mgr_id, min(salary) from emp545 where mgr_id is not null group by mgr_id having min(salary)>6000 order by min(salary) desc;

no rows selected

7) write a query to display each department’s name, location, number of employees, and average salary for the employees in that department. Label the column Name, Location, Number of people and salary. Round the average salary to two decimal places.

QUERY:

SQL> select d.dept_name "Name",d.loc_id "Location",count(*) "Number of people",round(avg(salary),2) "Salary" from emp545 e,dept545 d where e.dept_id=d.dept_id group by d.dept_name,d.loc_id;

Page 34: Oracle

Name Location Number of people Salary

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

Executive 1700 3 19333.33

IT 1500 3 6400

Shipping 1500 4 3750

8) Create a query that display the total number of employees and,of that total,the number of employees hired in 1995,1996,1997 and 1998.Create appropriate column heading.

QUERY:

SQL> select count(*) total,sum(decode(to_char(hire_date,'yyyy'),1995,1,0))"1995",sum(decode(to_char(hire_date,'yyyy'),1996,1,0)) "1996",sum(decode(to_char(hire_date,'yyyy'),1997,1,0)) "1997",sum(decode(to_char(hire_date,'yyyy'),1998,1,0)) "1998" from emp545;

TOTAL 1995 1996 1997 1998

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

18 0 0 0 0

9) 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.

QUERY:

SQL> select job_id "Job",sum(decode(dept_id,20,salary)) "Dept 20",sum(decode(dept_id,50,salary)) "Dept 50",sum(decode(dept_id,80,salary)) "Dept 80",sum(decode(dept_id,90,salary)) "Dept 90",

Page 35: Oracle

sum(salary) "Total" from emp545group by job_id;

Job Dept 20 Dept 50 Dept 80 Dept 90 Total

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

AD_PRES 24000 24000

AD_VP 34000 34000

IT_PROG 19200

ST_CLERK 9200 9200

ST_MAN 5800 5800

6 rows selected.

Chapter-6 Subqueries

1) Write a query to display the last name and hire date of any employee in the same department as Zlotkey.Excude Zlotkey.

QUERY:

SQL> select last_name,hire_date from emp545 where dept_id=(select dept_id from emp545 where last_name='Zlotkey') and last_name<>'Zlotkey';

no rows selected

2) Create a query to display the employee numbers and last names of all the employees who earn more than the average salary. Sort the results in ascending order of salary.

Page 36: Oracle

QUERY:

SQL> select emp_id,last_name from emp545 where salary>(select avg(salary) from emp545 ) order by salary;

EMP_ID LAST_NAME

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

101 Kochhar 102 De Haan 100 King

3) Write a query that displays the employee numbers and last names of all employees who work in a department with any employee whose last name contains a u.

QUERY:

SQL> select emp_id,last_name from emp545 where dept_id in (select dept_id from emp545 where last_name like '%u%');

EMP_ID LAST_NAME

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

124 Mourgos

141 Rajs

142 Davies

143 Matos

103 Hunold

104 Ernst

107 Lorentz

Page 37: Oracle

7 rows selected.

4) Display the last name,department number and job ID of all employees department location ID is 1700.

QUERY:

SQL> select last_name,dept_id,job_id from emp545 where dept_id in (select dept_id from dept545 where location_id=1700);

LAST_NAME DEPT_ID JOB_ID

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

King 90 AD_PRES

Kochhar 90 AD_VP

De Haan 90 AD_VP

5) Display the last name and salary of every employee who reports to King.

QUERY:

SQL> select last_name,salary from emp545 where mgr_id=(select emp_id from emp545 where last_name='KING');

no rows selected

6) Display the department number,last name and the job ID for the every employee in the Executive department.

QUERY:

SQL> select dept_id, last_name, job_id from emp545 where dept_id in (select dept_id from dept545 where dept_name='Executive');

DEPT_ID LAST_NAME JOB_ID

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

90 King AD_PRES

90 Kochhar AD_VP

Page 38: Oracle

90 De Haan AD_VP

7) Display the employee numbers,last names and salaries of all employees who earn more than average salary and who work in a department with any employee with a u in their name.

QUERY:

SQL> select emp_id,last_name,salary from emp545 where dept_id in (select dept_id from emp545 where last_name like '%u%') and salary > (select avg(salary) from emp545);

no rows selected

Chapter-7 Producing Readable Output with iSQL*Plus

1) Write a script to display the employee last name,job,and hire date for all employees who started between a given range. Concatenate the name and job together, separated by a space and comma, and labels the column Employees. In a separate SQL script file, use the DEFINE command to provide the two ranges. Use the format MM/DD/YYYY.

QUERY:

SQL> set echo off set verify off define low_date = 01/01/1998 define high_date = 01/01/1999

Select last _name ||’,’|| job_id EMPLOYEES,hire_date from emp545 where hire_date between To_date(‘&low_date’,’MM/DD/YYYY’) and to_date(‘&high_date’,’MM/DD/YYYY’) /Undefined low_date undefined high_date set verify on set echo on

EMPLOYEES HIRE_DATE

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

Matos,ST_CLERK 15-MAR-98

Page 39: Oracle

2) Write a script to display the employee last name,job,and department name for a given location. The search condition should allow for case-insensitive searches of the department location.

QUERY:

SQL>set echo off set verify offcolumn last_name HEADING “DEPARTMENT”Select e.last_name,e.job_id,d.dept_name from emp545,dept545,loc545 where e.dept_id=d.dept_id and l.loc_id=d.loc_id and l.city=initcap(‘&p_loc’/Column last_name clear column dept_name clear set verify on set echo on

EMP_NAME JOB_ID DEPT_NAME

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

King AD_PRES Executive

Kochhar AD_VP Executive

De Haan AD_VP Executive

3) Create a query to report containing the dept name, employee last name, hire date, salary, and annual salary for each employee in a given location. Label the columns DNAME, ENAME, STRT DATE, SALARY, and ANN SALARY placing the labels on multiple lines.

QUERY:

SQL>set echo offset feedback off set verify break on dept_name column dept_name heading “DNAME” column last_name heading “ENAME” column hire_date heading “SALARY” FORMAT $99,990.00

Page 40: Oracle

column asal heading “ANN SALARY” format $99,990.00Select d.dept_name,e.last_name,e.hire_date,e.salary,e.salary*12 asal from dept545 d,emp545 e, loc545 l where e.dept_id=d.dept_id and d.loc545_id=l.loc545_id and l.city =’&p_loc’ order by d.dept_name/column dept_name clear column last_name clearcolumn hire_date clear column salary clear break

Set verify on set feedback on set echo on

DNAME ENAME STRT DATE SALARY ANN SALARY

--------------------------------------------------------------------------------------------Administration Whalen 17-SEP-87 $4,400.00 $52,800.00

Executive King 17-JUN-87 $24,000.00 $2880, 000.00

Kochhar 21-SEP-89 $17,000.00 $204,000.00

De Haan 13-JAN-93 $17,000.00 $204,000.00

Chapter-8 Manipulating Data

1) Create a query to build a table MY_EMPLOYEE table that will be used for the lab.

QUERY:

SQL> create table my_employee (id number(4) constraint emp_id_nn not null, last_name varchar2(25),first_name varchar2(25),user_id varchar2(8),salary number(9,2));

Page 41: Oracle

Table created.

2) Describe the structure of the MY_EMPLOYEE table to identify the column names

QUERY:

SQL> desc my_employee;

Name Null? Type

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

ID NOT NULL NUMBER(4)

LAST_NAME VARCHAR2(25)

FIRST_NAME VARCHAR2(25)

USER_ID VARCHAR2(8)

SALARY NUMBER(9,2)

3) Add the row of data to MY_EMPLOYEE table .Do not list the columns in the INSERT clause.

QUERY:

SQL> insert into my_employee values (1,'patel','ralph','rpatel', 895);

1 row created.

4) Populate the MY_EMPLOYEE table with the second row of sample data from the preceding list .List the columns in the insert clause.

QUERY:

SQL> insert into my_employee (id, last_name, first_name, user_id, salary) values (2,'dancs','betty','bdancs',860);

1 row created.

Page 42: Oracle

5) Confirm your addition to the table.

QUERY:

SQL> select * from my_employee;

ID LAST_NAME FIRST_NAME USER_ID SALARY

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

1 patel ralph rpatel 895

2 dancs betty bdancs 860

6 )Write an insert statement in a text file named loademp.sql to load rows into the my_employee table. Concatenate the first letter of the first name and first seven characters of the last name to produce the user_id?

QUERY:

SQL> set echo offSQL> set verify offSQL> insert into my_employee

values (&p_id,'&p_last_name','&p_first_name',lower (substr('&p_first_name',1,1)|| substr('&p_last_name',1,7)),&p_salary);

Enter value for p_id: 1Enter value for p_last_name: patelEnter value for p_first_name: ralphEnter value for p_first_name: patelEnter value for p_last_name: patelEnter value for p_salary: 865

1 row created.

ID LAST_NAME FIRST_NAME USERID SALARY---- ------------------- ---- -------- ------ --------- ------------

1 patel ralph rpatel 865

Page 43: Oracle

7) Populate the table with the last row of sample data by modifying the statements in the script you created?

QUERY:

SQL> insert into my_employee values (&p_id,'&p_last_name','&p_first_name',lower (substr('&p_first_name',1,1)|| substr('&p_last_name',1,7)),&p_salary);

Enter value for p_id: 1Enter value for p_last_name: dancs Enter value for p_first_name: bettyEnter value for p_first_name: bettyEnter value for p_last_name: dancs Enter value for p_salary: 860

1 row created.

ID LAST_NAME FIRST_NAME USERID SALARY--------------------------- -------------------- ----- ---------- -------- ---------------- 2 dancs betty bdancs 860 3 biri ben bbiri 1100 4 newman chad cnewman 750

8) Confirm your additions to the table?

QUERY:

SQL> select * from my_employee;

ID LAST_NAME FIRST_NAME USERID SALARY ------ ------------------------- ---------- ---- ---- --------- ---------- 1 patel ralph rpatel 865 2 dancs betty bdancs 860 3 biri ben bbiri 1100 4 newman chad cnewman 750 9) Make the data additions permanent.

QUERY:

SQL> commit;

Page 44: Oracle

Commit complete.

10) Change the last name of the employee 3 to drexler? And verify it.

QUERY:

SQL> update my_employee 2 set last_name= 'drexler' 3 where id= 3;

1 row updated.

SQL> select * from my_employee;

ID LAST_NAME FIRST_NAME USERID SALARY---------- --------- ------------- ---------- -------- ----------

1 patel ralph rpatel 865 2 dancs betty bdancs 860 3 drexler ben bbiri 1100 4 newman chad cnewman 750

11) Change the salary to 1000 for all the employees whose salary is less than 900 and verify it.

QUERY:

SQL> update my_employee set salary=1000 where salary<900;

3 rows updated.

SQL> select * from my_employee;

ID LAST_NAME FIRST_NAME USERID SALARY ---------- ------------------------- ----- - ---- ----- --- ---------- 1 patel ralph rpatel 1000 2 dancs betty bdancs 1000 3 drexler ben bbiri 1100 4 newman chad cnewman 1000

12)Verify your changes to the table?

Page 45: Oracle

QUERY:

SQL> select * from my_employee;

ID LAST_NAME FIRST_NAME USERID SALARY ---------- ------------------------- ----- - ---- ----- --- ---------- 1 patel ralph rpatel 1000 2 dancs betty bdancs 1000 3 drexler ben bbiri 1100 4 newman chad cnewman 1000

13) Delete betty_dancs from my_employee table?

QUERY:

SQL> delete from my_employee where last_name='dancs';

1 row deleted.

SQL> select * from my_employee;

ID LAST_NAME _FIRST_NAME USERID SALARY ---------- ------------------------- ----- - ---- ----- --- ---------- 1 patel ralph rpatel 1000 3 drexler ben bbiri 1100 4 newman chad cnewman 1000

14) Confirm your changes to your table?

QUERY:

SQL> select * from my_employee;

ID LAST_NAME _FIRST_NAME USERID SALARY ---------- ------------------------- ----- - ---- ----- --- ---------- 1 patel ralph rpatel 1000 3 drexler ben bbiri 1100 4 newman chad cnewman 1000

Page 46: Oracle

15) Commit all pending changes?

QUERY:

SQL> commit;Commit complete

16) Populate the table with the last row of sample data by modifying the statements in the script you created ?

QUERY:

SQL> set echo offSQL> set verify offSQL> insert into my_employee values (&p_id,'&p_last_name','&p_first_name',lower (substr('&p_first_name',1,1)|| substr('&p_last_name',1,7)),&p_salary);

Enter value for p_id: 1Enter value for p_last_name: dancs Enter value for p_first_name: bettyEnter value for p_first_name: betty Enter value for p_last_name: dancs Enter value for p_salary: 865

1 row created.

ID LAST_NAME FIRST_NAME USERID SALARY---- ------------------- ---- -------- ------ --------- ------

2 dancs betty bdancs 1000

17)Confirm your additions to your table?

QUERY:

SQL> select * from my_employee;

ID LAST_NAME FIRST_NAME USERID SALARY ---------- ------------------------- ----- - ---- ----- --- ---------- 1 patel ralph rpatel 1000 2 dancs betty bdancs 1000 3 drexler ben bbiri 1100

Page 47: Oracle

4 newman chad cnewman 1000

18) Mark the intermediate point in the processing of the transaction?

QUERY:

SQL> savepoint step_18; Savepoint created.

19) Empty the entire table?

QUERY:

SQL> delete from my_employee;

4 rows deleted.

20) Confirm that the table is empty?

QUERY:

SQL> select * from my_employee;

no rows selected

21)Discard the most recent delete operation without discarding the earlier insert operation?

QUERY:

SQL>rollback to step_18;

Rollback complete.

22) Confirm that the new row is still intact?

QUERY:

SQL> select * from my_employee;

Page 48: Oracle

ID LAST_NAME FIRST_NAME USERID SALARY ---------- ------------------------- ----- - ---- ----- --- ---------- 1 patel ralph rpatel 1000 2 dancs betty bdancs 1000 3 drexler ben bbiri 1100 4 newman chad cnewman 1000 23 )Make the data additions permanent?

QUERY:

SQL> commit;Commit complete

Chapter-9 Creating and Managing Tables

1) Create the dept table based on the following table instance chart then executes the statement in the script to create the table.

QUERY:

SQL> create table dept( id number(7), name varchar2(25));

Table created.

SQL> desc dept; Name Null? Type -------------------------------------- -------- ------------------------- ID NUMBER(7) NAME VARCHAR2(25)

2) Populate the dept table with data from the departments table. Include only columns that you need.

Page 49: Oracle

QUERY: SQL> insert into dept select dept_id,dept_name from dept545;

7 rows created.

SQL> select * from dept;

ID NAME ------ ------------------------- 10 Administration 20 Marketing 50 Shipping 60 IT 80 Sales 90 Executive 110 Accounting 190 Contracting

7 rows selected.

3) Create emp table based on the following table instance chart and then execute the statement in the script to create table

QUERY:

SQL> create table emp (id number(7),last_name varchar2(25),first_name varchar2(25),dept_id number(7));

Table created.

SQL> desc emp;

Name Null? Type

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

ID NUMBER(5)

LAST_NAME VARCHAR2(25)

FIRST_NAME VARCHAR2(25)

Page 50: Oracle

DEPT_ID NUMBER(7)

4) Modify the emp table to allow for longer employee last names. Confirm your modification.

QUERY:

SQL> alter table emp modify(last_name varchar2(50));

Table altered.

SQL> desc emp;

Name Null? Type

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

ID NUMBER(7) LAST_NAME VARCHAR2(50)

FIRST_NAME VARCHAR2(25)

DEPT_ID NUMBER(7)

5) Confirm that the dept and emp tables are stored in the data dictionary.

QUERY:

SQL> select table_name from user_tables where table_name in ('DEPT','EMP');

TABLE_NAME

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

DEPT

EMP

6) Create the employees2 table based on the structure of employees table. Include only the employee_id , first_name , last_name , salary , and dept_id columns. Name the columns in your new table id , first_name, last_name ,

Page 51: Oracle

salary , and dept_id, respectively.

QUERY:

SQL> create table employee2 AS select emp_id "id",first_name,last_name "last_name", salary,dept_id from emp 545;

Table created.

7) Drop the emp table. QUERY:

SQL> drop table emp;

Table dropped.

8) Rename the employees2 table as emp.

QUERY:

SQL> rename employee2 to emp;

Table renamed.

9) Add a comment to the dept and EMP table definition describing the tables. Confirm your additions in the data dictionary.

QUERY: SQL> comment on table emp is 'Information of employees';

Comment created.

SQL> comment on table dept is 'information of departments';

Comment created. SQL> select * from user_tab_comments 2 where table_name in ('DEPT','EMP');

TABLE_NAME TABLE_TYPE

Page 52: Oracle

------------------------------ -----------COMMENTS--------------------------------------------------------------------------------DEPT TABLEinformation of departments

EMP TABLEInformation of employees

10) Drop the first_name column from emp table.

QUERY:

SQL> alter table empdrop column first_name;

Table altered.11) In the emp table,mark the dept_id column in the emp table as unused.

QUERY:

SQL> alter table empSET UNUSED (dept_id);

Table altered.

12) Drop all the unused columns fro the emp table.

QUERY:

SQL>alter table emp drop unused columns;

Table altered.

Chapter -10 Including Constraints

1) Add a table-level primary key constraint to the emp table on id column. The constraint should be named at creation. Name the constraint my_emp_id_pk.

Page 53: Oracle

QUERY:

SQL> alter table emp add constraint my_emp_id_pk pimary key (id);

Table altered.

2) Create a primary key constraint to the dept table using the id column. The constraint should be named at creation. Name the constraint my_dept_id_pk.

QUERY:

SQL>alter table dept add constraint my_dept_id_pk primary key(id); Table altered.

3)Add a column dept_id to the emp table. Add a foreign key reference on the emp table that ensures that the employee is not assigned to a nonexistent department. Name the constraint my_emp_dept_id_fk.

QUERY:

SQL>alter table emp add (dept_id number(7));

Table altered.

SQL>alter table emp add constraint my_emp_dept_id_fk foreign key (dept_id)

References dept(id);

Table altered.

4)Confirm that the constraints were added by querying the user_constraints view. Note the types and names of the constraints.

QUERY:

SQL>select constraint_name,constraint_type from user_constraints where table_name in

Page 54: Oracle

('EMP', 'DEPT');

CONSTRAINT_NAME C

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

MY_DEPT_ID_PK P

SYS_C002541 C

MY_EMP_ID_PK P

MY_EMP_DEPT_ID_FK R

5)Display the object names and types from the user_objects data dictionary view for the emp and dept tables. Notice that the new tables and a new index were created.

QUERY:

SQL>select object_name,object_type from user_objects where object_name like 'emp%' or object_name like 'dept%';

6)Modify the emp table. Add a commission column of number data type , precision 2, scale 2. Add a constraint to the commission column that ensures that a commission value is greater than zero.

QUERY:

SQL>alter table emp add commission number (2,2) constraint my_emp_comm_ck check commission>=0;

Table altered.

Chapter-11 Creating Views

1) Create a view called EMPLOYEES_VU based on the employee numbers,

Page 55: Oracle

employee names and department numbers from the EMP545table. Change the heading for the employee name to EMPLOYEE.

QUERY:

SQL> create or replace view employee_vu as select emp_id,last_name employee, dept_id from emp545;

2)Display the contents of the EMPLOYEES_VU view.

QUERY:

SQL> select * from employee_vu;

EMP_ID LAST_NAME DEPT_ID---------- --------------- --------------- ---------- 100 King 90 101 Kochhar 90 102 De Haan 90 103 Hunold 60 104 Ernst 60 107 Lorentz 60 124 Mourgos 50 141 Rajs 50 142 Davies 50 143 Matos 70

10 rows selected

3) Select the view name and text from the USER_VIEWS data dictionary view.

QUERY:

select view_name,text from user_views;

VIEW_NAME------------------------------TEXT--------------------------------------------------------------------------------group by d.department_id

CC

Page 56: Oracle

select deptno,sum(sal) salary from emp group by deptno

CLERKselect student.rollno,stream,last_name from student,students

CLERK1

VIEW_NAME------------------------------TEXT--------------------------------------------------------------------------------select clerk.rollno,students.stream,last_name from clerk,students

CLERK11select clerk.rollno,students.stream,students.name from clerk,students

COMPLEXselect deptno,sum(sal) sum_salaryfrom emp group by deptno

VIEW_NAME------------------------------TEXT--------------------------------------------------------------------------------COOLselect ename,empno from emp

DDselect name,class from vishal11

DD1( select last_name,job_id from employee300)

VIEW_NAME------------------------------TEXT--------------------------------------------------------------------------------where deptno=20

EMP342select employee_id, last_name, phone_numberfrom emp102where job_id = 59

Page 57: Oracle

EMP4554SELECT ENAME,JOB,MGR from emp where DEPTNO=20.

4) Using your EMPLOYEES_VU view ,enter a query to display all employee names and department numbers.

QUERY:

SQL> select employee,dept_id from employee_vu;

EMPLOYEE DEPT_ID--------------- ----------King 90Kochhar 90De Haan 90Hunold 60Ernst 60Lorentz 60Mourgos 50Rajs 50Davies 50Matos 70

10 rows selected.

5) Create a view named DEPT50 that contains the employee numbers, employee last names and department numbers for all the employees in department 50.Label the view columns EMPNO, EMPLOYEE and DEPTNO. Do not allow an employee to be reassigned to another department through the view.

QUERY:

SQL> create view dept50 as select emp_id empno,last_name employee, dept_id deptno from emp545where dept_id = 50 with check option constraint emp_dept_50;View created.

6) Display the structure and contents of the DEPT50 view.

QUERY:

Page 58: Oracle

SQL> describe dept50; Name Null? Type ----------------------------------------- -------- ---------------------------- EMPNO NUMBER(3) EMPLOYEE VARCHAR2(15) DEPTNO NUMBER(3)

SQL> select * from dept50;

EMPNO EMPLOYEE DEPTNO---------- --------------- --------------------------- 124 Mourgos 50 141 Rajs 50 142 Davies 50

7)Create a view called SALARY_VU based on the employee last names, department names, salaries and salary grades for all employees. Use the EMPLOYEES,DEPARTMENTS and JOB_GRADES tables. Label the columns Employee, Department, Salary and Grade.

QUERY:

SQL> create or replace view salary_vu ASSelect e.last_name “Employee”, d.dept_name “department”e.salary “Salary”, j.grade_level “grades”from emp545 e,dept545 d,job_grade545 jwhere e.dept_id=d.dept_id AND e.salary between j.lowest_sal and j.highest_sal;

Chapter-12 Other Database Object

1) Create a sequence to be used with primary key column of the dept545 table. The sequence should start at 200 and have a maximum value of 1000.Have your sequence increment by ten numbers. Name the sequence

Page 59: Oracle

DEPT_ID_SEQ.

QUERY:

SQL> create sequence dept_id_seq start with 200 increment by 10 maxvalue 1000;

Sequence created.

2) Write a query to display the following information about your sequence name, maximum value, increment size and last number.

QUERY:

SQL> select sequence_name,max_value,increment_by,last_number from user_sequences;

SEQUENCE_NAME MAX_VALUE INCREMENT_BY LAST_NUMBER

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

DEPT_ID_SEQ 1000 10 200

3)Write a query to insert two rows into the dept545 table.Be sure to use the sequence that you created for the ID column.Add two departments named Education and Administration.

QUERY:

SQL> insert into dept545 values (dept_id_seq.nextval,'Education');

1 row created.

4)Create a nonunique index on the foreign key column(DEPT_ID) in the emp545 table.

QUERY:

SQL> create index emp_dept_id_idx on emp545 (dept_id);

Index created.

5)Display the indexes and uniqueness that data dictionary for the emp545

Page 60: Oracle

table.

QUERY:

SQL> select index_name,table_name,uniqueness from user_indexes where table_name='emp545';

INDEX_NAME TABLE_NAME UNIQUENES

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

EMP_DEPT_ID_IDX EMP545 NONUNIQUE

Chapter-13 Controlling User Access

1) Grant another user access to your DEPT545 table.Have the user grant you query access to his ot her DEPT545 table.

QUERY: SQL>grant select on dept545 to <user1 >;

Page 61: Oracle

Grant succeeded.

SQL>grant select on dept545 to <user2>;

Grant succeeded.

2) Query all the rows in your DEPT545 table.

QUERY:

SQL> select * from dept545;

DEPT_ID DEPT_NAME MGR_ID LOC_ID

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

10 Administration 200 1700

20 Marketing 201 1800

50 Shipping 124 1500 60 IT 103 1500

80 Sales 149 2500

90 Executive 100 1700

110 Accounting 205 1700

190 Contracting 0 1700

8 rows selected.

3) Add a new row to your DEPT545 table. Team 1 should add Education as department number 500.Team 2 should add Human Resources department number 510.Query the other team’s table.

QUERY:

SQL> insert into dept545 (dept_id,dept_name) values (500, ’Education’);

Page 62: Oracle

1 row created.

SQL>Commit; Commit complete.

SQL>insert into dept545 (dept_id,dept_name) values (510, ’Administration’);

1 row created.

SQL>Commit;Commit complete.

4) Create a synonym for the other team’s DEPT545 table.

QUERY:

SQL>Create synonym team2 for<user2>.Dept545;Synonym created.

SQL>create synonym team1 for<user1>.Dept545;Synonym created.

5) Query all the rows in the other team’s DEPARTMENT table by using your synonym.

QUERY:

SQL>select * from team2;

DEPT_ID DEPT_NAME MG_ID LOC_ID

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

10 Administration 200 1700

20 Marketing 201 1800

50 Shipping 124 1500

Page 63: Oracle

60 IT 103 1500

80 Sales 149 2500

90 Executive 100 1700

110 Accounting 205 1700

190 Contracting 0 1700

500 Education 0 0

9 rows selected.

SQL>select * from team1;

DEPT_ID DEPT_NAME MGR_ID LOC_ID

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

10 Administration 200 1700

20 Marketing 201 1800

50 Shipping 124 1500

60 IT 103 1500

80 Sales 149 2500

90 Executive 100 1700

110 Accounting 205 1700

190 Contracting 0 1700

510 Human Resources 0 0

9 rows selected.

6) Query the USER_TABLES data dictionary to see information about the tables that you own.

Page 64: Oracle

QUERY:

SQL> select table_name from user_tables;

TABLE_NAME

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

BONUS

COUNTRIES

DEPT545

DEPT

EMP

EMP545

JOB_GRADES

JOB_HISTORY

LOCATIONS

MY_EMPLOYEE

RITESH

SALGRADE

12 rows selected.

7)Query the ALL_TABLES data dictionary view to see information about all the tables that you can access.

QUERY:

SQL>select table_name,owner from all_tables where owner <>your account>;

Page 65: Oracle

TABLE_NAME OWNER

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

DEPT545 owner

1 row selected.

8) Revoke the select privilege from the other team.

QUERY:

SQL>revoke select on dept545 from user2;

Revoke succeeded.

SQL>revoke select on dept545 from user1;

Revoke succeeded.

9)Remove the row you inserted into the DEPT545 table in step 8 and save the changes.

QUERY:

SQL>delete from dept545 where dept_id = 500;

0 rows deleted.

SQL>commit;Commit complete.

SQL>delete from dept545 where dept_id=510;0 rows deleted.

SQL>commit;Commit complete.

Page 66: Oracle

Chapter -14 SQL Workshop

1)Create the tables based on the following table instance charts.Choose the appropriate data types.

a.Table name : MEMBER

QUERY:

Page 67: Oracle

SQL>create table member (member_id number(10) constraint member _member_id_pk primary key,last_name varchar2(25) constraint member _last_name_nn NOT NULL,first_name varchar2(25),address varchar2(25),city varchar2(30),phone varchar2(15),join_date DATE DEFAULT SYSDATE constraint member_join//-date_nn NOT NULL);

Table created.

b.Table name : TITLE

QUERY:

SQL> create table title(title_id number(10) constraint title_title_pk primary key,title varchar2(60) constraint title_title_nn NOT NULL,description varchar2(400) constraint title_description_nn NOT NULL,rating varchar2(4) constraint title_rating_ck CHECK (rating in (‘G’,’PG’,’R’,’NC17’,’NR’)),category varchar2(20), constraint title_category_ck CHECK (category in (‘DRAMA’ , ‘COMEDY’ , ‘ACTION’ , ‘CHILD’ , ‘SCIFI’ , ‘DOCUMENTARY’)),release_date DATE);

Table created.

c.Table name : TITLE_COPY

QUERY:

SQL>create table title_COPY (copy_id number(10),title_id number(10) constraint title_if_fk REFERENCES title (title_id), status varchar2(15) constraint title_copy_status_nn NOT NULL ,constraint title_copy_status_ck CHECK(status in (‘AVAILABLE’ , ‘DESTROYED’ , ‘RENTED’ , ‘RESERVED’)), constraint title_copy_copy_id_title_id_pk primary key (copy_id,title_id));

Table created.d.Table name : RENTAL

QUERY:

SQL>create table rental (book_date DATE DEFAULT SYSDATE,member_id number(10) constraint rental_member_id_fk REFERENCES member (member_id),copy_id number(10),act_ret_date DATE,exp_ret_date DATE,exp_ret_date DATE DEFAULT SYSDATE +2,title_id number (10), constraint rental_book_date_copy_title_pk primary key (book_date,member_id,copy_id,title_id), constraint rental_copy_id,title_id_fk foreign key (copy_id,title_id) REFERENCES title_copy (copy_id,tittle_id));

Page 68: Oracle

Table created.

e.Table name : RESERVATION

QUERY:

SQL>create table reservation (res_date DATE, member_id number(10) constraint reservation _ member _ id REFERENCES member (member_id),title_id number(10) constraint reservation_title_id REFERENCES title (title_id),constraint reservation_resdate_mem_tit_pk primary key (res_date, member_id , title_id_;

Table created.

3)Create sequences to uniquely identify each row in the MEMBER table and the TITLE table.

a.Member number for the MEMBER table:start with 101;do not allow caching of the values.Name the sequence MEMBER_ID_SEQ.

QUERY:

SQL>create sequence member_id_seq start with 101 nocache;

b.Title number for the TITLE table : start with 92;no caching.Name the sequence TITLE_ID_SEQ.

QUERY:

SQL>create sequence title_id_seq start with 92 nocache;

4)Add data to the tables.Create a script for each set of data to add.

a.Add movie titles to the TITLE table.Write a script to enter the movie information.Use the sequences to uniquely identify each title.Enter the release dates in theDD-MON-YYYY format.Verify your additions.

QUERY:

SQL>set echo off

Page 69: Oracle

Insert into title(title_id,title,description,rating,category,release_date) values (title_id_seq.nextval, ’willlie and Christmas too’,’all of willie’’s friends make a christmas list for santa,but willie has yet

to add his own wish list .’ , ‘G’ , ‘child’ ,to_date(’05-oct-1995’,’DD-MON-YYYY’)

1 row created.

Insert into title(title_id,title,description,rating,category,release_date) values (title_id_seq.nextval,’alien again’ , ‘yet another installation of science fiction history.can the heroine save the planet from the alien life form?’,’R’ ,’SCIFI’ ,to_date (’19-may-1995’,’DD-MON-YYYY’))

1 row created.

Insert into title(title_id,title,description,rating,category,release_date) values (title_id_seq.nextval,’the glob’,’a meteor crashes near a small American town and unleashes carnivorous goo in this classic..’ , ’nr’ , ‘SCIFI’ , to_date (’12-AUG-1995’ , ‘DD-MON-YYYY’))

1 row created.

Set echo on

SQL>select title from title;

b.Add data to the MEMBER table.

QUERY:

SQL> set echo off set verify off insert into member ( member_id , first_name , last_name, address ,city ,phone ,join_date) values (member_id_seq.nextval,’&first_name’,’&last_name’ , ‘&address’ , ‘&city’ , ‘&phone’ , to_date(‘&join_date’,’DD-MON-YYYY’);

1 row created.

SQL>commit;

Commit complete.

SQL>set verify on set echo on

Page 70: Oracle

c.Add the following movie copies in the TITLE_COPY table.

QUERY:

SQL> insert into title_copy (copy_id,title_id,status) values (1,92,’AVAILABLE’);

1 row created.

SQL> insert into title_copy (copy_id,title_id,status) values (1,93’AVAILABLE’);

1 row created.

SQL> insert into title_copy (copy_id,title_id,status) values (2,93,’RENTED’);

1 row created.

SQL> insert into title_copy (copy_id,title_id,status) values (1,94,’AVAILABLE’);

1 row created.

SQL> insert into title_copy (copy_id,title_id,status) values (1,95,’AVAILABLE’);

1 row created.

SQL> insert into title_copy (copy_id,title_id,status) values (2,95,’AVAILABLE’);

1 row created.

SQL> insert into title_copy (copy_id,title_id,status) values (3,95,’RENTED’);

1 row created.

SQL> insert into title_copy (copy_id,title_id,status) values(1,96,’AVAILABLE’);

1 row created.

SQL> insert into title_copy (copy_id,title_id,status) values (1,97,’AVAILABLE’);

1 row created.

d.Add the following rentals to the RENTAL table :

QUERY:

Page 71: Oracle

SQL>insert into rental (title_id,copy_id,member_id,book_date,exp_ret_date,act_ret_date) values (92,1,101,sysdate-3,sysdate-1,sysdate-2);

1 row created.

SQL>insert into rental (title_id,copy_id,member_id,book_date,exp_ret_date,act_ret_date) values(93,2,101,sysdate-1,sysdate-1,NULL);

1 row created.

SQL>insert into rental (title_id,copy_id,member_id,book_date,exp_ret_date,act_ret_date) values(95,3,102,sysdate-2,sysdate,NULL);

1 row created.

SQL>insert into rental (title_id,copy_id,member_id,book_date,exp_ret_date,act_ret_date) values(97,1,102,sysdate-2,sysdate,NULL);

1 row created.

SQL>insert into rental (title_id,copy_id,member_id,book_date,exp_ret_date,act_ret_date) values(97,1,106,sysdate-4,sysdate-2,sysdate-2);

1 row created.

SQL>commit;

Commit complete.

5)Create a view named TITLE_AVAIL to show the movie titles and the availabilities of each copy and its expected return date if rented.Query all rows from the view.Order the results by title.

QUERY:

SQL>create view title_avail as select t.title,c.copy_id,c.status,r.exp_ret_date from title t,title_copy c,rental r where t.title_id = c.title_id and c.copy_id = r.copy_id(+) and c.title_id = r.title_id(+);

View created.

6) Add a new title.The movie is “Interstellar Wars”

Page 72: Oracle

Chapter-15 Using SET Operators

1) List the department IDs for dept545 that do not contain the job ID ST_CLERK,using SET operations.

QUERY:

SQL> select dept_id from dept545 minus select dept_id from emp545 where job_id='ST_CLERK';

DEPT_ID

----------

Page 73: Oracle

10

20

60

80

90

110

190

7 rows selected.

2) Display the country ID and the name of the countries that have no departments located in them using SET operations.

QUERY:

SQL> select country_id,country_name from country545 MINUS select l.country_id,c.country_name from loc545 l,country545 c where l.country_id=c.country_id;

CO COUNTRY_NAME

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

DE Germany

3) Produce a list of jobs for dept545 10,50and 20 in that order.Display job ID and department ID using SET operators.

QUERY:

SQL> select job_id,dept_id,'x' from emp545 where dept_id=10 union select job_id,dept_id,'y' from emp545 where dept_id=50 union select job_id,dept_id,'z' from emp545 where dept_id=20 order by 3;

Page 74: Oracle

JOB_ID DEPT_ID

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

ST_CLERK 50 y

ST_MAN 50 y

4)List the employee IDs and job IDs of those emp545 who currently have the job title that they held before beginning their tenure with the company.

QUERY:

SQL> select emp_id,job_id from emp545 intersect select emp_id,job_id from job_history;

no rows selected

5) Write a compound query to lists the following

a) Last names and department ID of all the employees from the EMP545 table, regardless of whether or not they belong to any department.

b)Department ID and department name of all the departments from the DEPT545 table, regardless of whether or not they have emp545 worKING in them.

QUERY:

SQL> select last_name,dept_id,to_char(null) from emp545 union select to_char(null),dept_id,dept_name from dept545;

LAST_NAME DEPT_ID TO_CHAR(NULL)

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

King 90

Davies 50

De Haan 90

Page 75: Oracle

Ernst 60

Hunold 60

Kochhar 90

Lorentz 60

Matos 50

Mourgos 50

Rajs 50

Chapter 16 Oracle 9i Date Time Functions

1) Alter the session to set the NLS_DATE_FORMAT to DD-MON-YYYY HH24:MI:SS.

QUERY:

SQL> alter session set nls_date_format='dd-mon-yyyy hh24:mi:ss';

Session altered.

2) a.Write queries to display the time zone offsets (TZ_OFFSET) for the

Page 76: Oracle

following time zones-:US/Pacific-New,Singapore,Egypt.

QUERY:

SQL> select tz_offset('us/pacific-new') from dual;

TZ_OFFS--------07:00

SQL> select tz_offset('singapore') from dual;

TZ_OFFS-------+08:00

SQL> select tz_offset('egypt') from dual;

TZ_OFFS-------+03:00

b.Alter the session to set the TIME_ZONE parameter value to the time zone offset of US/Pacific-New

QUERY:

SQL> alter session set time_zone='-7:00';Session altered.c.Display the CURRENT_DATE,CURRENT_TIMESTAMP and LOCALTIMESTAMP for this session.

QUERY:

SQL> select current_date,current_timestamp,localtimestamp from dual;

CURRENT_D---------CURRENT_TIMESTAMP---------------------------------------------------------------------------LOCALTIMESTAMP---------------------------------------------------------------------------16-JUL-08

Page 77: Oracle

16-JUL-08 12.52.20.859000 PM -07:0016-JUL-08 12.52.20.859000 PM

d.Alter the session to set the TIME_ZONE parameter value to the time zone offset of Singapore.

QUERY:

SQL> alter session set time_zone ='+8:00';

Session altered.

e.Display the CURRENT_DATE, CURRENT_TIMESTAMP and LOCALTIMESTAMP for this session.

QUERY:

SQL> select current_date,current_timestamp,localtimestamp from dual;

CURRENT_D---------CURRENT_TIMESTAMP---------------------------------------------------------------------------LOCALTIMESTAMP---------------------------------------------------------------------------17-JUL-0817-JUL-08 03.54.18.937000 AM +08:0017-JUL-08 03.54.18.937000 AM

3)Write a query to display the DBTIMEZONE and SESSIONTIMEZONE.

QUERY:

SQL> select dbtimezone,sessiontimezone from dual;

DBTIME------SESSIONTIMEZONE----------------------------------------------------------------------------07:00+08:00

Page 78: Oracle

4) Write a query to extract the YEAR from the HIRE_DATE column of the EMPLOYEES table for those employees who work in department 80.

QUERY:

SQL> select last_name,extract(year from hire_date) from emp545 where dept_id =80;

LAST_NAME EXTRACT(YEAR FROM HIRE_DATE)---------- --------------------------King 1987Kochhar 1989De Haan 1993

5) Alter the session to set the NLS_DATE_FORMAT to DD-MON-YYYY.

QUERY:

SQL> alter session set nls_date_format='dd-mon-yyyy';

Session altered.

Chapter 17 Enhancements To The Group By clause

1) Write a query to display the following for those employees whose manager id is less than 120:

Manager id Job id and total salary for every job id for employees who report

to the same manager Total salary of those managers Total salary of those managers irrespective of the job ids.

Page 79: Oracle

QUERY:

SQL> select mgr_id,job_id,sum(salary) from emp545 where mgr_id<120 group by rollup(mgr_id,job_id);

MGR_ID JOB_ID SUM(SALARY) --------- -------- ----------- 100 AD_VP 34000 100 ST_MAN 5800 100 39800 102 IT_PROG 9000 102 9000 103 IT_PROG 10200 103 10200 59000

8 rows selected.

2) Write the query using the grouping function to determine whether the NULL values in the columns corresponding to the group by expressions are caused by the rollup operation.

QUERY:

SQL> select mgr_id,job_id,sum(salary),grouping(mgr_id),grouping(job_id) from emp545 where mgr_id <120 group by rollup(mgr_id,job_id);

MGR_ID JOB_ID SUM(SALARY) GROUPING(MGR_ID) GROUPING(JOB_ID)--------- -------- ----------- ---------------- ------------------------------------------------------ 100 AD_VP 34000 0 0 100 ST_MAN 5800 0 0 100 39800 0 1 102 IT_PROG 9000 0 0 102 9000 0 1 103 IT_PROG 10200 0 0 103 10200 0 1 59000 1 1

8 rows selected.

Page 80: Oracle

3) Write a query to display the following for those employees whosemanager ID is less than 120 :

-Manager ID-Job and total salaries for every job for employees who report to the same manager -Total salary of those managers-Cross-tabulation values to display the total salary for every job,irrespective of the manager-Total salary irrespective of all job titles.

QUERY:

SQL> select mgr_id,job_id,sum(salary) from emp545 where mgr_id <120 group by cube(mgr_id,job_id);

MGR_ID JOB_ID SUM(SALARY)--------- -------- -------------------------------- 100 AD_VP 34000 100 ST_MAN 5800 100 39800 102 IT_PROG 9000 102 9000 103 IT_PROG 10200 103 10200 AD_VP 34000 IT_PROG 19200 ST_MAN 5800 59000

11 rows selected.

4) Observe the output from query 3.Write a query using the GROUPING function to determine whether the NULL values in the columns corresponding to the GROUP BY expression are caused by the CUBE operation.

QUERY:

SQL> select mgr_id,job_id,sum(salary),grouping(mgr_id),grouping(job_id) from emp545 where mgr_id <120 group by cube(mgr_id,job_id);

MGR_ID JOB_ID SUM(SALARY) GROUPING(MGR_ID) GROUPING(JOB_ID)

Page 81: Oracle

--------- -------- ----------- ---------------- ---------------- 100 AD_VP 34000 0 0 100 ST_MAN 5800 0 0 100 39800 0 1 102 IT_PROG 9000 0 0 102 9000 0 1 103 IT_PROG 10200 0 0 103 10200 0 1 AD_VP 34000 1 0 IT_PROG 19200 1 0 ST_MAN 5800 1 0 59000 1 1

11 rows selected.

5) Using GROUPING SETS, write a query to display the following grouping:

-department_id, manager_id,job_id

-department_id,job_id

-Manager_id,job_id

The query should calculate the sum of the salaries for each of these groups.

QUERY:

select dept_id , mgr_id , job_id , sum(salary) from emp545 group by grouping sets ((dept_id,mgr_id,job_id),(dept_id,job_id),(mgr_id,job_id));

DEPT_ID MGR_ID JOB_ID SUM(SALARY) --------- -------- ----------- ----------------50 124 ST_CLERK 920050 100 ST_MAN 580060 102 IT_PROG 900060 103 IT_PROG 10200

Page 82: Oracle

Chapter 18 Advanced Subqueries

1) Write a query to display the last name, department number and salary of any employee whose department number and salary both match the department number and salary of any employee who earns a commission.

QUERY:

Page 83: Oracle

SQL> select last_name, dept_id, salary from emp545 where (salary, dept_id) IN (select salary, dept_id from emp545 where comm_pct is not null);

no rows selected

2) Display the last name, department name and salary of any employee whose salary and commission match the salary and commission of any employee located in location ID 1700.

QUERY:

SQL> select e.last_name,d.dept_name,e.salary from emp545 e,dept545 d where e.dept_id=d.dept_id AND (salary,nvl (comm_pct,0)) IN (select salary,nvl(comm_pct,0) from emp545 e,dept545 d where e.dept_id=d.dept_id AND d.loc_id=1700);

LAST_NAME DEPT_NAME SALARY---------- -------------------- ---------------------------------Kochhar Executive 17000De Haan Executive 17000King Executive 24000

3) Create a query to display the last name, hire date and salary for all employees who have the same salary and commission as Kochhar.

QUERY:

SQL> select last_name, hire_date,salary from emp545 where (salary,nvl(comm_pct,0)) IN (select salary,nvl(comm_pct,0) from emp545 where last_name='Kochhar') AND last_name !='Kochhar';

LAST_NAME HIRE_DATE SALARY---------- --------- --------- -----------------------De Haan 13-JAN-93 17000

4) Create a query to display the employees who earn a salary that is higher than the salary of all the sales managers (JOB_ID=’SA_MAN’).Sort the results on salary from highest to lowest.

QUERY:

Page 84: Oracle

SQL> select last_name,job_id,salary from emp545 where salary >all (select salary from emp545 where job_id='SA_MAN') order by salary desc;

LAST_NAME JOB_ID SALARY---------- -------- --------- ---------------------------King AD_PRES 24000Kochhar AD_VP 17000De Haan AD_VP 17000Hunold IT_PROG 9000Ernst IT_PROG 6000Mourgos ST_MAN 5800Lorentz IT_PROG 4200Rajs ST_CLERK 3500Davies ST_CLERK 3100Matos ST_CLERK 2600

10 rows selected.

5) Display the details of the employee ID, last name and department ID of those employees who live in cities whose name begins with T

QUERY:

SQL> select emp_id,last_name,dept_id from emp545 where dept_id IN (select dept_id from dept545 where loc_id IN (select loc_id from loc546 where city like't%'));

no rows selected

6) Write a query to find all employees who earn more than the average salary in their departments. Display last name, salary, department ID and the average salary for the department. Sort by average salary. Use aliases for the columns retrieved by the query.

QUERY:

SQL> select e.last_name ename, e.salary sal,e.dept_id deptno,avg(b.salary) avg from emp545 e,emp545 b where e.dept_id = b.dept_id AND e.salary > (select avg(salary) from emp545 where dept_id = e.dept_id)

Page 85: Oracle

group by e.last_name, e.salary, e.dept_id order by avg(b.salary);

ENAME SAL DEPTNO AVG---------- --------- --------- ------------ ---------------Mourgos 5800 50 3750Hunold 9000 60 6400King 24000 90 19333.333

7) Find all employees who are not supervisors.

a)First do this by using the NOT EXISTS operatorQUERY:

SQL> select e.last_name from emp545 e where not exists (select 'X' from emp545 e1 where e1.mgr_id = e.emp_id);

LAST_NAME----------KochharErnstLorentzRajsDaviesMatos

6 rows selected.

b) Can this be done by using the NOT IN operator? How, or why not?

QUERY:

SQL> select e.last_name from emp545 e where e.emp_id not in (select e1.mgr_id from emp545 e1); no rows selected

8) Write a query to display the last names of the employees who earn less than the average salary in their departments.

QUERY:

SQL> select last_name from emp545 e where e.salary < (select avg(e1.salary) from emp545 e1 where e1.dept_id = e.dept_id);

Page 86: Oracle

LAST_NAME----------KochharDe HaanErnstLorentzRajsDaviesMatos

7 rows selected.

9)Write a query to display the last names of employees who have one or more coworkers in their departments with later hire dates but higher salaries.

QUERY:

SQL> select last_name from emp545 e where exists(select 'X' from emp545 e1 where e1.dept_id = e.dept_id AND e1.hire_date > e.hire_date AND e1.salary > e.salary);

LAST_NAME----------RajsDaviesMatos

10) Write a query to display the employee ID,last names and department names of all employees.

QUERY:

SQL> select emp_id,last_name,(select dept_name from dept545 d where 2 e.dept_id = d.dept_id) dept 3 from emp545 e 4 order by dept;

EMP_ID LAST_NAME DEPT--------- ---------- ---------- ---------- 103 Hunold IT

Page 87: Oracle

104 Ernst IT 107 Lorentz IT 100 King Executive 101 Kochhar Executive 102 De Haan Executive 124 Mourgos Shipping 141 Rajs Shipping 142 Davies Shipping 143 Matos Shipping

10 rows selected.

Chapter-19 Hierarchical Retrieval

1) Produce a report showing an organization chart for Mourgos’s department.Print last names,salaries and department IDs.

QUERY:

SQL> select last_name,salary,dept_id from emp545 start with last_name='Mourgos' connect by prior emp_id = mgr_id;

Page 88: Oracle

LAST_NAME SALARY DEPT_ID

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

Mourgos 5800 50

2)Create a report that shows the hierarchy of the managers for the employee Lorentz.Display his immediate manager first.

QUERY:

SQL> select last_name from emp545 where last_name !='Lorentz' connect by prior mgr_id = emp_id;

LAST_NAME

------------------ King

Kochhar

De Haan

Hunold

Ernst

Mourgos

Rajs

Davies

Matos

Mourgos

Hunold

King

12 rows selected.

Page 89: Oracle

3)Create a indented report showing the management hierarchy starting from the employee whose LAST_NAME is Kochhar.Print the employee’s last name,manager ID and department ID.Give alias to the columns as shown in sample output.

QUERY:

SQL> select LPAD (last_name,length(last_name)+(level*2)-2,'_')name,mgr_id mgr,dept_id deptno from emp545 start with last_name='Kochhar' connect by prior emp_id=mgr_id;

no rows selected

4)Produce a company organization chart that shows the management hierarchy.Start with the person at the top level,exclude all people with a job ID IT_PROG and exclude De Haan and those emp545 who report to De Haan.

QUERY:

SQL> select last_name,emp_id,manager_id from emp545 where job_id !='IT_PROG' start with mgr_id is null connect by prior emp_id=mgr_id and last_name !='De Haan';

LAST_NAME EMP_ID MANAGER_ID

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

King 100

Kochhar 101

De Haan 102

Mourgos 124

Rajs 141

Page 90: Oracle

Davies 142

Matos 143

7 rows selected.

Chapter-20 Oracle 9i Extensions to DML and DDL Statements

1) Create table sal_history.

QUERY:

SQL> create table sal_history(emp_id number(6),hire_date date,salary number(8,2));

Table created.

Page 91: Oracle

2) Display the structure of the table sal_history.

QUERY:

SQL> desc sal_history; Name Null? Type ----------------------------------------------------- -------- ------------------------------ EMP_ID NUMBER(6) HIRE_DATE DATE SALARY NUMBER(8,2)

3) Create the table mgr_history.

QUERY:

SQL> create table mgr_history(emp_id number(6),mgr_id number(6),salary number(8,2));

Table created.

4) Display the structure mgr_history.

QUERY:

SQL> desc mgr_history; Name Null? Type ----------------------------------------------------- -------- ------------------ EMP_ID NUMBER(6) MGR_ID NUMBER(6) SALARY NUMBER(8,2)

5) Create table special_sal.

QUERY:

SQL> create table special_sal(emp_id number(6),salary number(8,2));

Table created.

6) Display the structure of special_sal table

QUERY:

Page 92: Oracle

SQL> desc special_sal; Name Null? Type ----------------------------------------------------- -------- ---------------------- EMP_ID NUMBER(6) SALARY NUMBER(8,2)

7) a.Write a query to do the following:

-Retrieve the details of the employee ID,hire date,salary and manager ID of those employees whose employee ID is less than 125 from the EMP545 table.

-If the salary is more than $20,000 insert the details of employee ID and salary into the SPECIAL_SAL table.

-Insert the details of the employee ID,hire date and salary into the SAL_HISTORY table.

-Insert the details of the employee ID,manager ID and SYSDATE into the MGR_HISTORY table.

QUERY:

Insert ALLWhen SAL>20000 thenInto special_sal values (EMPID,SAL)ElseInto sal_history values(EMPID,HIREDATE,SAL)Into mgr_history values(EMPID,MGR,SAL)Select emp_id EMPID,hire_date HIREDATE,Salary SAL,mgr_id MGR from emp545Where emp_id<125;

b.Display the records from the SPECIAL_SAL table.

QUERY:

Select * from special_sal;

EMP_ID SALARY----------------------- ------------------------

100 24000c.Display the records from the SAL_HISTORY table.

Page 93: Oracle

QUERY:

Select * from sal_history;

EMP_ID HIRE_DATE SALARY----------------- ---------------- ---------------101 21-sep-89 17000102 13-jan-93 17000103 03-jan-90 9000104 21-may-91 6000107 07-feb-99 4200124 16-nov-99 5800

6 rows selected.

d. Display the records from the MGR_HISTORY table.

QUERY:

Select * from mgr_history;

EMP_ID MGR_ID SALARY---------------- ---------------- --------------101 100 17000102 100 17000 103 102 9000104 103 6000107 103 4200124 100 5800

8) Create the SALES_SOURCE_DATA table.

QUERY:

SQL> create table sales_source_data(emp_id number(4),wk_id number(2),sl_mon number(8,2), sl_tue number(8,2),sl_wed number(8,2),sl_thur number(8,2),sl_fri number(8,2));

b) Insert records into the SALES_SOURCE_DATA table.

QUERY:

Page 94: Oracle

SQL> insert into sales_source_datavalues(178,6,1750,2200,1500,1500,3000);

1 row created.

c)Display the structure of the SALES_SOURCE_DATA table.

QUERY:

SQL> desc sales_source_data; Name Null? Type ----------------------------------------------------- -------- ------------------------- EMP_ID NUMBER(4) WK_ID NUMBER(2) SL_MON NUMBER(8,2) SL_TUE NUMBER(8,2) SL_WED NUMBER(8,2) SL_THUR NUMBER(8,2) SL_FRI NUMBER(8,2)

d)Display the records from the SALES_SOURCE_DATA table.

QUERY:

SQL> select * from sales_source_data;

EMP_ID WK_ID SL_MON SL_TUE SL_WED SL _THUR SL_FRI--------- --------- --------- --------- --------- ---------- --------- ------------------ ------------ 178 6 1750 2200 1500 1500 3000

e) Create SALES_INFO table.

QUERY:

SQL> create table sales_info(emp_id number(6),week number(2),sales number(8,2));

Table created.

f) Display the structure of the SALES_INFO table.

QUERY:

SQL> desc sales_info;

Page 95: Oracle

Name Null? Type ----------------------------------------------------- -------- ------------------ EMP_ID NUMBER(6) WEEK NUMBER(2) SALES NUMBER(8,2)

g)Write a query to do the following:- -Retrieve the details of the employee ID,week ID,sales on Monday, sales on Tuesday,SALES_SOURCE_DATA table. -Build a transformation such that record retrieved from the SALES_SOURCE_DATA table is converted into multiple records for the SALES_INFO table.

QUERY:

insert allinto sales_info values(emp_id,week_id,sl_mon)into sales_info values(emp_id,week_id,sl_tue)into sales_info values(emp_id,week_id,sl_wed)into sales_info values(emp_id,week_id,sl_thur)into sales_info values(emp_id,week_id,sl_fri)select emp_id,week_id,sl_mon,sl_tue,sl_wed,sl_thur,Sl_fri from sales_source_data;

h) Display the records from the SALES_INFO table.

QUERY:

select * from sales_info;

EMP_ID WK SALES------------- ------------------- ---------------------------178 6 1750178 6 2200178 6 1500178 6 1500178 6 3000

Page 96: Oracle