BASES DE DATOS

Anuncio
BASES DE DATOS
Ingeniería Técnica Informática
Asignatura Obligatoria: 4.5 + 4.5 créditos (Segundo cuatrimestre)
Curso académico 2000/2002
Relación de Ejercicios Prácticos
T
EMA 11.. M
ANDATO SSELECT
ELECT B
ÁSICO
TEMA
MANDATO
BÁSICO
1.1.Initiate a SQL*Plus session using the user ID and password provided by the
instructor.
1.2.SQL*Plus commands access the database.
True/False
1.3.Will the SELECT statement execute successfully? True/False
SQL> SELECT
FROM
ename, job, sal
emp;
Salary
1.4.Will the SELECT statement execute successfully? True/False
SQL>SELECT
FROM
*
salgrade;
1.5.There are three coding errors in this statement. Can you identify them?
SQL> SELECT
FROM
empno,ename
salary x 12 ANNUAL SALARY
emp;
1.6.Show the structure of the DEPT table. Select all data from the DEPT table.
Name
----------------DEPTNO
DNAME
LOC
DEPTNO
-----------10
20
30
40
Null?
--------------NOT NULL
DNAME
------------------ACCOUNTING
RESEARCH
SALES
OPERATIONS
Type
-----------NUMBER(2)
VARCHAR2(14)
VARCHAR2(13)
LOC
------------NEWYORK
DALLAS
CHICAGO
BOSTON
1.7.Show the structure of the EMP table. Create a query to display the name,
job, hire date and employee number for each employee, with employee number
appearing first. Save your SQL statement to a file named p1q7.sql.
Página 1
Name
----------------EMPNO
ENAME
JOB
MGR
HIREDATE
SAL
COMM
DEPTNO
Null?
Type
--------------- ------------NOT NULL NUMBER(4)
VARCHAR2(10)
VARCHAR2(9)
NUMBER(4)
DATE
NUMBER(7,2)
NUMBER(7,2)
NOT NULL NUMBER(2)
1.8.Run your query in the file p1q7.sql.
EMPNO
ENAME
--------------------7839
KING
7698
BLAKE
7782
CLARK
7566
JONES
7654
MARTIN
7499
ALLEN
7844
TURNER
7900
JAMES
7521
WARD
7902
FORD
7369
SMITH
7788
SCOTT
7876
ADAMS
7934
MILLER
14 rows selected.
JOB
---------------PRESIDENT
MANAGER
MANAGER
MANAGER
SALESMAN
SALESMAN
SALESMAN
CLERK
SALESMAN
ANALYST
CLERK
ANALYST
CLERK
CLERK
HIREDATE
---------------17-NOV-81
01-MAY-81
09-JUN-81
02-APR-81
28-SEP-81
20-FEB-81
08-SEP-81
03-DEC-81
22-FEB-81
03-DEC-81
17-DEC-80
09-DEC-82
12-JAN-83
23-JAN-82
1.9.Create a query to display unique jobs from the EMP table.
JOB
----------ANALYST
CLERK
MANAGER
PRESIDENT
SALESMAN
1.10.Load p1q7.sql into the SQL buffer. Name the column headings Emp #,
Employee, Job, and Hire Date, respectively. Rerun your query.
Emp
#
--------7839
7698
Employee
------KING
BLAKE
JobHire
---------PRESIDENT
MANAGER
Página 2
Date
-------------17-NOV-81
01-MAY-81
7782
CLARK
7566
JONES
7654
MARTIN
7499
ALLEN
7844
TURNER
7900
JAMES
7521
WARD
7902
FORD
7369
SMITH
7788
SCOTT
7876
ADAMS
7934
MILLER
14 rows selected.
MANAGER
MANAGER
SALESMAN
SALESMAN
SALESMAN
CLERK
SALESMAN
ANALYST
CLERK
ANALYST
CLERK
CLERK
09-JUN-81
02-APR-81
28-SEP-81
20-FEB-81
08-SEP-81
03-DEC-81
22-FEB-81
03-DEC-81
17-DEC-80
09-DEC-82
12-JAN-83
23-JAN-82
1.11.Display the name concatenated with the job, separated by a comma and
space, and name the column Employee and Title.
Employee and Title
------------------KING, PRESIDENT
BLAKE, MANAGER
CLARK, MANAGER
JONES, MANAGER
MARTIN, SALESMAN
ALLEN, SALESMAN
TURNER, SALESMAN
JAMES, CLERK
WARD, SALESMAN
FORD, ANALYST
SMITH, CLERK
SCOTT, ANALYST
ADAMS, CLERK
MILLER, CLERK
14 rows selected.
1.12.Create a query to display all the data from the EMP table. Separate each
column by a comma. Name the column THE_OUTPUT.
THE_OUTPUT
------------------------------------------------7839,KING,PRESIDENT,,17-NOV-81,5000,,10
7698,BLAKE,MANAGER,7839,01-MAY-81,2850,,30
7782,CLARK,MANAGER,7839,09-JUN-81,2450,,10
7566,JONES,MANAGER,7839,02-APR-81,2975,,20
7654,MARTIN,SALESMAN,7698,28-SEP-81,1250,1400,30
Página 3
7499,ALLEN,SALESMAN,7698,20-FEB-81,1600,300,30
7844,TURNER,SALESMAN,7698,08-SEP-81,1500,0,30
7900,JAMES,CLERK,7698,03-DEC-81,950,,30
7521,WARD,SALESMAN,7698,22-FEB-81,1250,500,30
7902,FORD,ANALYST,7566,03-DEC-81,3000,,20
7369,SMITH,CLERK,7902,17-DEC-80,800,,20
7788,SCOTT,ANALYST,7566,09-DEC-82,3000,,20
7876,ADAMS,CLERK,7788,12-JAN-83,1100,,20
7934,MILLER,CLERK,7782,23-JAN-82,1300,,10
14 rows selected.
T
EMA 22.REST
.RESTR
ICC
NY
RDENACIÓN D
EL
OS D
ATOS
TR
IÓ
TEMA
RIC
CIÓ
ÓN
YO
ORDENACIÓN
DE
LOS
DATOS
R
ECUPERADOS.
RECUPERADOS.
2.1.Create a query to display the name and salary of employees earning more
than $2850. Save your SQL statement to a file named p2q1.sql. Run your query.
ENAME
-----------KING
JONES
FORD
SCOTT
SAL
---5000
2975
3000
3000
2.2.Create a query to display the employee name and department number for
employee number 7566.
ENAME
----------JONES
DEPTNO
-----20
2.3.Modify p2q1.sql to display the name and salary for all employees whose
salary is not in the range of $1500 and $2850. Resave your SQL statement to a
file named p2q3.sql. Rerun your query.
ENAME
-----------KING
JONES
MARTIN
JAMES
WARD
FORD
SMITH
SAL
----5000
2975
1250
950
1250
3000
800
Página 4
SCOTT
3000
ADAMS
1100
MILLER
1300
10 rows selected.
2.4.Display the employee name, job and start date of employees hired between
February 20, 1981, and May 1, 1981. Order the query in ascending order of start
date.
ENAME
-----------ALLEN
WARD
JONES
BLAKE
JOB
----------------SALESMAN
SALESMAN
MANAGER
MANAGER
HIREDATE
---------------20-FEB-81
22-FEB-81
02-APR-81
01-MAY-81
2.5.Display the employee name and department number of all employees in
departments 10 and 30 in alphabetical order by name.
ENAME
DEPTNO
-------------- ----------KING
10
BLAKE
30
CLARK
10
MARTIN
30
ALLEN
30
TURNER
30
JAMES
30
WARD
30
MILLER
10
9 rows selected.
2.6.Modify p2q3.sql to list the name and salary of employees who earn more than
$1500 and are in department 10 or 30. Label the columns Employee and Monthly
Salary, respectively. Resave your SQL statement to a file named p2q6.sql. Rerun
your query.
Employee Monthly Salary
--------------- ------------------KING
5000
BLAKE
2850
CLARK
2450
ALLEN
1600
2.7 Display the name and hire date of every employee who was hired in 1982.
ENAME
HIREDATE
Página 5
-----------SCOTT
MILLER
---------------09-DEC-82
23-JAN-82
2.8.Display the name and title of all employees who do not have a manager.
ENAME
-----------KING
JOB
--------PRESIDENT
2.9.Display the name, salary, and commission for all employees who earn
commissions. Sort data in descending order of salary and commissions.
ENAME
----------ALLEN
TURNER
MARTIN
WARD
SAL....
--------1600
1500
1250
1250
COMM
--------300
0
1400
500
2.10.Display the names of all employees where the third letter of their name is an
A.
ENAME
----------BLAKE
CLARK
ADAMS
2.11.Display the name of all employees that have two Ls in their name and are in
department 30 or their manager is 7782.
ENAME
---------ALLEN
MILLER
2.12.Display the name, job, and salary for all employees whose job is Clerk or
Analyst and their salary is not equal to $1000, $3000, or $5000.
ENAME
-----------JAMES
SMITH
ADAMS
MILLER
JOB
------CLERK
CLERK
CLERK
CLERK
SAL
----950
800
1100
1300
Página 6
2.13.Modify p2q6.sql to display the name, salary, and commission for all
employees whose commission amount is greater than their salary increased by
10%. Rerun your query. Resave your query as p2q13.sql.
ENAME
------------MARTIN
SAL COMM
----- ---------1250
1400
T
EMA 33.. FFUNCIONES
UNCIONES D
E SSQL
QL Q
UE A
CTÚAN SSOBRE
OBRE U
NA SSOLA
OLA
TEMA
DE
QUE
ACTÚAN
UNA
FFILA.
ILA.
3.1.Write a query to display the current date. Label the column Date.
Date
-------------28-OCT-97
3.2.Display the employee number, name, salary, and salary increase by 15%
expressed as a whole number. Label the column New Salary. Save your SQL
statement to a file named p3q2.sql.
3.3.Run your query in the file p3q2.sql.
EMPNO
ENAME
---------------------7839
KING
7698
BLAKE
7782
CLARK
7566
JONES
7654
MARTIN
7499
ALLEN
7844
TURNER
7900
JAMES
7521
WARD
7902
FORD
7369
SMITH
7788
SCOTT
7876
ADAMS
7934
MILLER
14 rows selected.
SAL New Salary
----- -------------5000
5750
2850
3278
2450
2818
2975
3421
1250
1438
1600
1840
1500
1725
950
1093
1250
1438
3000
3450
800
920
3000
3450
1100
1265
1300
1495
3.4.Modify your query p3q2.sql to add an additional column that will subtract
the old salary from the new salary. Label the column Increase. Rerun your
Página 7
query.
EMPNO
----------7839
7698
7782
7566
ENAME
-----------KING
BLAKE
CLARK
JONES
SAL
------5000
2850
2450
2975
New Salary
---------5750
3278
2818
3421
Increase
-------750
428
368
446
3.5.Display the employee’s 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 “Sunday, the Seventh of September,
1981.”
ENAME
HIREDATE
--------------------------KING
17-NOV-81
BLAKE
01-MAY-81
CLARK
09-JUN-81
JONES
02-APR-81
MARTIN
28-SEP-81
ALLEN
20-FEB-81
TURNER
08-SEP-81
JAMES
03-DEC-81
WARD
22-FEB-81
FORD
03-DEC-81
SMITH
17-DEC-80
SCOTT
09-DEC-82
ADAMS
12-JAN-83
MILLER
23-JAN-82
14 rows selected.
REVIEW
------------------------------------------------Monday, the Twenty-Fourth of May, 1982
Monday, the Second of November, 1981
Monday, the Fourteenth of December, 1981
Monday, the Fifth of October, 1981
Monday, the Twenty-Ninth of March, 1982
Monday, the Twenty-Fourth of August, 1981
Monday, the Fifteenth of March, 1982
Monday, the Seventh of June, 1982
Monday, the Twenty-Fourth of August, 1981
Monday, the Seventh of June, 1982
Monday, the Twenty-Second of June, 1981
Monday, the Thirteenth of June, 1983
Monday, the Eighteenth of July, 1983
Monday, the Twenty-Sixth of July, 1982
3.6.For each employee display the employee name and calculate the number of
months between today and the date the employee was hired. Label the column
MONTHS_WORKED. Order your results by the number of months employed.
Round the number of months up to the closest whole number.
ENAME
----------ADAMS
SCOTT
MILLER
JAMES
FORD
KING
MARTIN
TURNER
CLARK
BLAKE
MONTHS_WORKED
--------------------------177
178
188
190
190
191
192
193
196
197
Página 8
JONES
WARD
ALLEN
SMITH
14 rows selected
198
199
199
202
3.7.Write a query that produces the following for each employee:
<employee name> earns <salary> monthly but wants <3 times salary>. Label the
column Dream Salaries.
Dream Salaries
---------------------------------------------------KING earns $5,000.00 monthly but wants $15,000.00.
BLAKE earns $2,850.00 monthly but wants $8,550.00.
CLARK earns $2,450.00 monthly but wants $7,350.00.
JONES earns $2,975.00 monthly but wants $8,925.00.
MARTIN earns $1,250.00 monthly but wants $3,750.00.
ALLEN earns $1,600.00 monthly but wants $4,800.00
TURNER earns $1,500.00 monthly but wants $4,500.00.
JAMES earns $950.00 monthly but wants $2,850.00.
WARD earns $1,250.00 monthly but wants $3,750.00.
FORD earns $3,000.00 monthly but wants $9,000.00.
SMITH earns $800.00 monthly but wants $2,400.00.
SCOTT earns $3,000.00 monthly but wants $9,000.00.
ADAMS earns $1,100.00 monthly but wants $3,300.00
MILLER earns $1,300.00 monthly but wants $3,900.00.
14 rows selected.
3.8.Create a query to display name and salary for all employees. Format the
salary to be 15 characters long, left-padded with $. Label the column SALARY.
ENAME SALARY
------------- --------------SMITH
$$$$$$$$$$$$800
ALLEN $$$$$$$$$$$1600
WARD
$$$$$$$$$$$1250
JONES
$$$$$$$$$$$2975
MARTIN $$$$$$$$$$$1250
BLAKE $$$$$$$$$$$2850
CLARK $$$$$$$$$$$2450
SCOTT $$$$$$$$$$$3000
KING
$$$$$$$$$$$5000
TURNER $$$$$$$$$$$1500
ADAMS $$$$$$$$$$$1100
JAMES $$$$$$$$$$$$950
FORD
$$$$$$$$$$$3000
MILLER $$$$$$$$$$$1300
14 rows selected.
Página 9
3.9.Write a query that will display the employee's name with the first letter
capitalized and all other letters lowercase and the length of their name, for all
employees whose name starts with J, A, or M. Give each column an appropriate
label.
Name
Length
--------------Jones
5
Martin
6
Allen
5
James
5
Adams
5
Miller
6
6 rows selected.
3.10.Display the name, hire date, and day of the week on which the employee
started. Label the column DAY. Order the results by the day of the week
starting with Monday.
ENAME
HIREDATE
-------------MARTIN
28-SEP-81
CLARK
09-JUN-81
KING
17-NOV-81
TURNER
08-SEP-81
SMITH
17-DEC-80
ADAMS
12-JAN-83
JONES
02-APR-81
FORD
03-DEC-81
SCOTT
09-DEC-82
JAMES
03-DEC-81
ALLEN
20-FEB-81
BLAKE
01-MAY-81
MILLER
23-JAN-82
WARD
22-FEB-81
14 rows selected
DAY
----------MONDAY
TUESDAY
TUESDAY
TUESDAY
WEDNESDAY
WEDNESDAY
THURSDAY
THURSDAY
THURSDAY
THURSDAY
FRIDAY
FRIDAY
SATURDAY
SUNDAY
3.11.Create a query that will display the employee name and commission
amount. If the employee does not earn commission, put “No Commission.” Label
the column COMM.
ENAME
-----SMITH
ALLEN
WARD
JONES
MARTIN
BLAKE
CLARK
COMM
----------No Commission
300
500
No Commission
1400
No Commission
No Commission
Página 10
SCOTT
KING
TURNER
ADAMS
JAMES
FORD
MILLER
No
No
0
No
No
No
No
Commission
Commission
Commission
Commission
Commission
Commission
14 rows selected.
T
EMA 44.. O
BTENIENDO D
ATOS D
ESDE M
ÚLTIPLES T
ABLAS.
TEMA
OBTENIENDO
DATOS
DESDE
MÚLTIPLES
TABLAS.
4.1.Write a query to display the name, department number, and department
name for all employees.
ENAME
DEPTNO
------------ -----------CLARK
10
KING
10
MILLER
10
SMITH
20
ADAMS
20
FORD
20
SCOTT
20
JONES
20
ALLEN
30
BLAKE
30
MARTIN 30
JAMES
30
TURNER 30
WARD
30
14 rows selected.
DNAME
------------------ACCOUNTING
ACCOUNTING
ACCOUNTING
RESEARCH
RESEARCH
RESEARCH
RESEARCH
RESEARCH
SALES
SALES
SALES
SALES
SALES
SALES
4.2.Create a unique listing of all jobs that are in department 30.
JOB
-------------CLERK
MANAGER
SALESMAN
LOC
------------CHICAGO
CHICAGO
CHICAGO
4.3. Write a query to display the employee name, department name, and location
of all employees who earn a commission.
ENAME
------------ALLEN
DNAME
------------SALES
LOC
------------CHICAGO
Página 11
WARD
MARTIN
TURNER
SALES
SALES
SALES
CHICAGO
CHICAGO
CHICAGO
4.4.Display the employee name and department name for all employees who have
an A in their name. Save your SQL statement in a file called p4q4.sql.
ENAME
DNAME
------------ -----------CLARK
ACCOUNTING
ADAMS
RESEARCH
ALLEN
SALES
WARD
SALES
JAMES
SALES
MARTIN SALES
BLAKE
SALES
7 rows selected.
4.5.Write a query to display the name, job, department number, and department
name for all employees who work in DALLAS.
ENAME
----------SMITH
ADAMS
FORD
SCOTT
JONES
JOB
--------CLERK
CLERK
ANALYST
ANALYST
MANAGER
DEPTNO
------------20
20
20
20
20
DNAME
---------RESEARCH
RESEARCH
RESEARCH
RESEARCH
RESEARCH
4.6
6.Display the employee name and employee number along with their
manager’s name and manager number. Label the columns Employee, Emp#,
Manager, and Mgr#, respectively. Save your SQL statement to a file called
p4q6.sql.
Employee
-------------SCOTT
FORD
ALLEN
WARD
JAMES
TURNER
MARTIN
MILLER
ADAMS
Emp#
--------7788
7902
7499
7521
7900
7844
7654
7934
7876
Página 12
Manager
-----------JONES
JONES
BLAKE
BLAKE
BLAKE
BLAKE
BLAKE
CLARK
SCOTT
Mgr#
--------7566
7566
7698
7698
7698
7698
7698
7782
7788
JONES
CLARK
BLAKE
SMITH
13 rows selected.
7566
7782
7698
7369
KING
KING
KING
FORD
7839
7839
7839
7902
4.7.Modify p4q6.sql to display all employees including King, who has no
manager. Resave as p4q7.sql. Run p4q7.sql.
Employee Emp#
------------- ---------SCOTT
7788
FORD
7902
ALLEN
7499
WARD
7521
JAMES
7900
TURNER 7844
MARTIN 7654
MILLER
7934
ADAMS
7876
JONES
7566
CLARK
7782
BLAKE
7698
SMITH
7369
KING
7839
14 rows selected.
Manager
-----------JONES
JONES
BLAKE
BLAKE
BLAKE
BLAKE
BLAKE
CLARK
SCOTT
KING
KING
KING
FORD
Mgr#
--------7566
7566
7698
7698
7698
7698
7698
7782
7788
7839
7839
7839
7902
4.8.Create a query that will display the employee name, department number,
and all the employees that work in the same department as a given employee.
Give each column an appropriate label.
DEPARTMENT
--------------------10
10
10
10
10
10
20
20
20
20
20
20
20
EMPLOYEE
-----------------CLARK
CLARK
KING
KING
MILLER
MILLER
ADAMS
ADAMS
ADAMS
ADAMS
FORD
COLLEAGUE
--------KING
MILLER
CLARK
MILLER
CLARK
KING
FORD
JONES
SCOTT
SMITH
ADAMS
FORD
FORD
JONES
SCOTT
Página 13
56 rows selected.
4.9.Show the structure of the SALGRADE table. Create a query that will display
the name, job, department name, salary, and grade for all employees.
Name
Null?
------------ ---------GRADE
LOSAL
HISAL
Type
------NUMBER
NUMBER
NUMBER
ENAME
JOB
------------ ----------------MILLER
CLERK
CLARK
MANAGER
KING
PRESIDENT
SMITH
CLERK
SCOTT
ANALYST
FORD
ANALYST
ADAMS
CLERK
JONES
MANAGER
JAMES
CLERK
BLAKE
MANAGER
TURNER SALESMAN
ALLEN
SALESMAN
WARD
SALESMAN
MARTIN SALESMAN
14 rows selected.
DNAME
SAL
-------------------- --------ACCOUNTING 1300
ACCOUNTING 2450
ACCOUNTING 5000
RESEARCH
800
RESEARCH
3000
RESEARCH
3000
RESEARCH
1100
RESEARCH
2975
SALES
950
SALES
2850
SALES
1500
SALES
1600
SALES
1250
SALES
1250
GRADE
----2
4
5
1
4
4
1
4
1
4
3
3
2
2
4.10.Create a query to display the name and hire date of any employee hired
after employee Blake.
ENAME
-----------SMITH
ALLEN
WARD
JONES
HIREDATE
----------------17-DEC-80
20-FEB-81
22-FEB-81
02-APR-81
4.11.Display all employees’ names and hire dates along with their manager’s
name and hire date for all employees who were hired before their managers.
Label the columns Employee, Emp Hiredate, Manager, and Mgr Hiredate,
respectively.
Página 14
Employee Emp Hiredate Manager
------------- --------------- ------------ALLEN
20-FEB-81 BLAKE
WARD
22-FEB-81 BLAKE
JONES
02-APR-81 KING
CLARK
09-JUN-81 KING
BLAKE
01-MAY-81 KING
SMITH
17-DEC-80 FORD
6 rows selected.
Mgr Hiredate
-----------01-MAY-81
01-MAY-81
17-NOV-81
17-NOV-81
17-NOV-81
03-DEC-81
4.12.Create a query that displays the employees name and the amount of the
salaries of the employees are indicated through asterisks. Each asterisk signifies
a hundred dollars. Sort the data in descending order of salary. Label the column
EMPLOYEE_AND_THEIR_SALARIES.
EMPLOYEE_AND_THEIR_SALARIES
-----------------------------------------------------------------------------------KING *************************************************
FORD *****************************
SCOTT *****************************
JONES ****************************
BLAKE ***************************
CLARK ***********************
ALLEN ***************
TURNER **************
MILLER ************
MARTIN ***********
WARD ***********
ADAMS **********
JAMES ********
SMITH *******
14 rows selected.
T
EMA 55.. FFUNCIONES
UNCIONES D
EA
GR
EGACIÓN.
GR
TEMA
DE
AG
REGACIÓN.
Determine the validity of the following statements. Circle either True or False.
5.1.Group functions work across many rows to produce one result.
True/False
5.2.Group functions include nulls in calculations.
True/False
5.3.The WHERE clause restricts rows prior to inclusion in a group calculation.
True/False
5.4.Display the highest, lowest, sum, and average salary of all employees. Label
the columns Maximum, Minimum, Sum, and Average, respectively. Round your
results to the decimal position. Save your SQL statement in a file called p5q4.sql.
Maximum
-------------
Minimum
Sum
------------- - -------Página 15
Average
------------
5000
800
29025
2073
5.5.Modify p5q4.sql to display the minimum, maximum, sum, and average salary
for each job type. Resave to a file called p5q5.sql. Rerun your query.
JOB
-----------------ANALYST
CLERK
MANAGER
PRESIDENT
SALESMAN
Maximum
------------3000
1300
2975
5000
1600
Minimum
------------3000
800
2450
5000
1250
Sum Average
-------- -------6000 3000
4150 1038
8275 2758
5000 5000
5600 1400
5.6.Write a query to display the number of people with the same job.
JOB
---------------ANALYST
CLERK
MANAGER
PRESIDENT
SALESMAN
COUNT(*)
-------------2
4
3
1
4
5.7.Determine the number of managers without listing them. Label the column
Number of Managers.
Number of Managers
-------------------------6
5.8.Write a query that will display the difference between the highest and lowest
salaries. Label the column DIFFERENCE.
DIFFERENCE
---------------- -4200
5.9.Display the manager number and the salary of the lowest paid employee for
that manager. Exclude anyone where the manager id is not known. Exclude
any groups where the minimum salary is less than $1000. Sort the output in
descending order of salary.
MGR
-------7566
7839
7782
7788
MIN(SAL)
-------3000
2450
1300
1100
Página 16
5.10.Write a query to display the department name, location name, number of
employees, and the average salary for all employees in that department. Label
the columns’ dname, loc, Number of People, and Salary, respectively.
DNAME
--------------------ACCOUNTING
RESEARCH
SALES
LOC
-----------------NEW YORK
DALLAS
CHICAGO
Number of People
----------------------3
5
6
Salary
-------2916.67
2175
1566.67
5.11.Create a query that will display the total number of employees and of that
total the number who were hired in 1980, 1981, 1982, and 1983. Give appropriate
column headings.
TOTAL
---------14
1980 1981 1982 1983
-------- ------- -------- -------1
10
2
1
5.12.Create a matrix query to display the job, the salary for that job based upon
department number and the total salary for that job for all departments, giving
each column an appropriate heading.
Job
----------------ANALYST
CLERK
MANAGER
PRESIDENT
SALESMAN
Dept 10
---------1300
2450
5000
Dept 20
-------6000
1900
2975
Dept 30
----------950
2850
5600
Total
------6000
4150
8275
5000
5600
T
EMA 66.. SSUBCONSULTAS.
UBCONSULTAS.
TEMA
6.1.Write a query to display the employee name and hire date for all employees
in the same department as Blake. Exclude Blake.
ENAME
HIREDATE
--------------- --------------MARTIN 28-SEP-81
ALLEN
20-FEB-81
TURNER 08-SEP-81
JAMES
03-DEC-81
WARD
22-FEB-81
6 rows selected.
6.2.Create a query to display the employee number and name for all employees
who earn more than the average salary. Sort the results in descending order of
Página 17
salary.
EMPNO
ENAME
------------ ----------7839
KING
7902
FORD
7788
SCOTT
7566
JONES
7698
BLAKE
7782
CLARK
6 rows selected.
6.3. Write a query that will display the employee number and name for all
employees who work in a department with any employee whose name contains a
T. Save your SQL statement in a file called p6q3.sql.
EMPNO
-----------7566
7788
7876
7369
7902
7698
7654
7499
ENAME
-------JONES
SCOTT
ADAMS
SMITH
FORD
BLAKE
MARTIN
ALLEN
7844
TURNER
7900
JAMES
7521
WARD
11 rows selected.
6.4.Display the employee name, department number, and job title for all
employees whose department location is Dallas.
ENAME
------------JONES
FORD
SMITH
SCOTT
ADAMS
DEPTNO
------------20
20
20
20
20
JOB
--------MANAGER
ANALYST
CLERK
ANALYST
CLERK
6.5.Display the employee name and salary of all employees who report to King.
Página 18
ENAME
-----------BLAKE
CLARK
JONES
SAL
-------2850
2450
2975
6.6.Display the department number, name, and job for all employees in the Sales
department.
DEPTNO ENAME
------------- ------------30
BLAKE
30
MARTIN
30
ALLEN
30
TURNER
30
JAMES
30
WARD
6 rows selected.
JOB
--------MANAGER
SALESMAN
SALESMAN
SALESMAN
CLERK
SALESMAN
6.7.Modify p6q3.sql to display the employee number, name, and salary for all
employees who earn more than the average salary and who work in a
department with any employee with a T in their name. Resave as p6q7.sql. Rerun
your query.
EMPNO
-----------7566
7788
7902
7698
ENAME
-----------JONES
SCOTT
FORD
BLAKE
SAL
------2975
3000
3000
2850
T
EMA 77.. SSUBCONSULTAS
UBCONSULTAS C
ON M
ÚLTIPLES C
OLUMNAS.
TEMA
CON
MÚLTIPLES
COLUMNAS.
7.1.Write a query to display the name, department number, and salary of any
employee whose department number and salary matches both the department
number and salary of any employee who earns a commission.
ENAME
-----------MARTIN
WARD
DEPTNO
------------30
30
SAL
-------1250
1250
Página 19
TURNER
ALLEN
30
30
1500
1600
7.2.Display the name, department name, and salary of any employee whose
salary and commission matches both the salary and commission of any employee
located in Dallas.
ENAME
------------SMITH
ADAMS
JONES
FORD
SCOTT
DNAME
---------------RESEARCH
RESEARCH
RESEARCH
RESEARCH
RESEARCH
SAL
-----800
1100
2975
3000
3000
7.3.Create a query to display the name, hire date, and salary for all employees
who have both the same salary and commission as Scott.
ENAME
------------FORD
HIREDATE
---------------03-DEC-81
SAL
---------3000
7.4.Create a query to display the employees that earn a salary that is higher than
the salary of any of the CLERKS. Sort the results on salary from highest to
lowest.
ENAME
JOB
SAL
-------------- ---------------- --------KING
PRESIDENT 5000
FORD
ANALYST
3000
SCOTT
ANALYST
3000
JONES
MANAGER
2975
BLAKE
MANAGER
2850
CLARK
MANAGER
2450
ALLEN
SALESMAN
1600
TURNER SALESMAN
1500
8 rows selected.
T
EMA 88.. SSALIDA
ALIDA D
ED
ATOS A
EDIDA.
TEMA
DE
DATOS
AM
MEDIDA.
Determine whether the following statements are true or false:
8.1.A single ampersand substitution variable prompts only once.
True/False
8.2.The ACCEPT command is a SQL command.
True/False
8.3.Write a script file to display the employee name, job, and hire date for all
employees who started between a given range. Concatenate the name and job
Página 20
together, separated by a space and comma and label the column Employees.
Prompt the user for the two ranges using the ACCEPT command. Use the
format MM/DD/YY. Save the script file as p8q3.sql.
Please enter the low date range ('MM/DD/YY'): 01/01/81
Please enter the high date range ('MM/DD/YY'): 01/01/82
EMPLOYEES
HIREDATE
------------------------------KING, PRESIDENT
17-NOV-81
BLAKE, MANAGER
01-MAY-81
CLARK, MANAGER
09-JUN-81
JONES, MANAGER
02-APR-81
MARTIN, SALESMAN 28-SEP-81
ALLEN, SALESMAN
20-FEB-81
TURNER, SALESMAN 08-SEP-81
JAMES, CLERK
03-DEC-81
WARD, SALESMAN
22-FEB-81
FORD, ANALYST
03-DEC-81
10 rows selected.
8.4.Write a script to display the employee name, job, and department name. The
search condition should allow for case_insensitive name searches. Save the script
file as p8q4.sql.
Please enter the location name: Dallas
EMPLOYEE
NAME JOB
----------------------------------JONES
MANAGER
FORD
ANALYST
SMITH
CLERK
SCOTT
ANALYST
ADAMS
CLERK
DEPARTMENT NAME
-----------------------------RESEARCH
RESEARCH
RESEARCH
RESEARCH
RESEARCH
8.5.Modify p8q4.sql to create a report containing the department name, employee
name, hire date, salary and each employees annual salary for all employees in a
given location. Prompt the user for the location. Label the columns
DEPARTMENT NAME, EMPLOYEE NAME, START DATE, SALARY and
ANNUAL SALARY, placing the labels on multiple lines. Resave the script as
p8q5.sql.
Please enter the location name: Chicago
DEPARTMENT
EMPLOYEE START
NAME
NAME
DATE
SALARY
-------------------------- ------------------ ------------SALES
BLAKE
01-MAY-81 $2,850.00
MARTIN
28-SEP-81
$1,250.00
ALLEN
20-FEB-81 $1,600.00
TURNER
08-SEP-81
$1,500.00
Página 21
ANNUAL
SALARY
------------$34,200.00
$15,000.00
$19,200.00
$18,000.00
JAMES
WARD
03-DEC-81
22-FEB-81
$950.00
$1,250.00
$11,400.00
$15,000.00
T
EMA 99.. M
ANIPULACIÓN D
ED
ATOS.
TEMA
MANIPULACIÓN
DE
DATOS.
Insert data into the MY_EMPLOYEE table.
9.1.Run the /home/db/InformaciónGeneral/practicasdb2000/practica9/lab9_1.sql
script to build the MY_EMPLOYEE table that will be used for the lab.
9.2.Describe the structure of the MY_EMPLOYEE table to identify the column
names.
Name
Null?
Type
------------------------------- -----------------ID
NOT NULL NUMBER(4)
LAST_NAME
VARCHAR2(25)
FIRST_NAME
VARCHAR2(25)
USERID
VARCHAR2(8)
SALARY
NUMBER(9,2)
9.3.Add the first row of data to the MY_EMPLOYEE table from the sample data
below. Do not list the columns in the INSERT clause.
ID
LAST_NAME
FIRST_NAME
USERID
SALARY
1
Patel
Ralph
rpatel
795
2
Dancs
Betty
bdancs
860
3
Biri
Ben
bbiri
1100
4
Newman
Chad
cnewman
750
5
Ropeburn
Audry
aropebur
1550
9.4.Populate the MY_EMPLOYEE table with the second row of sample data
from the list above. This time, list the columns explicitly in the INSERT clause.
9.5.Confirm your addition to the table.
ID LAST_NAME
----- -----------------1 Patel
2 Dancs
FIRST_NAME
------------------Ralph
Betty
USERID
-----------rpatel
bdancs
SALARY
------------795
860
9.6. Create a script named loademp.sql to load rows into the MY_EMPLOYEE
table interactively. Prompt the user for the employee’s first name, last name, and
salary. Concatenate the first letter of the first name and the first seven
characters of the last name to produce the userid.
9.7.Populate the table with the next two rows of sample data by running the
Página 22
script you created.
9.8.Confirm your additions to the table.
ID
----1
2
3
4
LAST_NAME
-----------------Patel
Dancs
Biri
Newman
FIRST_NAME
------------------Ralph
Betty
Ben
Chad
USERID
-----------rpatel
bdancs
bbiri
cnewman
SALARY
------------795
860
1100
750
9.9.Make the data additions permanent.
Update and delete data in the MY_EMPLOYEE table.
9.10.Change the last name of employee 3 to Drexler.
9.11.Change the salary to 1000 for all employees with a salary less than 900.
9.12.Verify your changes to the table.
LAST_NAME
-----------------Patel
Dancs
Biri
Newman
SALARY
-----------1000
1000
1100
1000
9.13.Delete Betty Dancs from the MY_EMPLOYEE table.
9.14.Confirm your changes to the table.
ID LAST_NAME
FIRST_NAME
USERID
SALARY
------ ----------------------------------------------------------1 Patel
Ralph
rpatel
1000
3 Drexler
Ben
bbiri
1100
4 Newman
Chad
cnewman
1000
9.15. Commit all pending changes.
Control data transaction to the MY_EMPLOYEE tables.
9.16.Populate the table with the last row of sample data by running the script
you created in step 6.
9.17.Confirm your addition to the table.
ID
-----1
3
4
5
LAST_NAME
------------------Patel
Drexler
Newman
Ropeburn
FIRST_NAME
-------------------Ralph
Ben
Chad
Audry
Página 23
USERID SALARY
------------ ------------rpatel
1000
bbiri
1100
cnewman
1000
aropebur
1500
9.18.Mark an intermediate point in the processing of the transaction.
9.19.Empty the entire table.
9.20.Confirm that the table is empty.
9.21.Discard the most recent DELETE operation without discarding the earlier
INSERT operation.
9.22. Confirm that the new row is still intact.
ID
LAST_NAME
FIRST_NAME
-------------------------------------1
Patel
Ralph
3
Biri
Ben
4
Newman
Chad
5
Ropeburn
Audry
9.23.Make the data addition permanent.
USERID
--------rpatel
bbiri
cnewman
aropebur
SALARY
-----795
1100
750
1500
T
EMA 110.
0. C
REANDO Y
ANEJANDO T
ABLAS.
TEMA
CREANDO
YM
MANEJANDO
TABLAS.
10.1.Create the DEPARTMENT table based on the table instance chart given
below. Enter the syntax in a script called p10q1.sql, then execute the script to
create the table. Confirm that the table is created.
Id
Name
Datatype
Number
Varchar2
Length
7
25
Column Name
Key Type
Nulls/Unique
FK Table
FK Column
Name
Null?
---------- -------ID
NAME
Type
----------NUMBER(7)
VARCHAR2(25)
10.2.Populate the DEPARTMENT table with data from the DEPT table. Include
only columns that you need.
Página 24
10.3.Create the EMPLOYEE table based on the table instance chart given below.
Enter the syntax in a script called p10q3.sql, and then execute the script to create
the table. Confirm that the table is created.
ID
LAST_NAME
FIRST_NAME
DEPT_ID
Datatype
Number
Varchar2
Varchar2
Number
Length
7
25
25
7
Column Name
Key Type
Nulls/Unique
FK Table
FK Column
Name
------------ID
LAST_NAME
FIRST_NAME
DEPT_ID
Null?
--------
Type
-----------NUMBER(7)
VARCHAR2(25)
VARCHAR2(25)
NUMBER(7)
10.4.Modify the EMPLOYEE table to allow for longer employee last names.
Confirm your modification.
Name
------------------ID
LAST_NAME
FIRST_NAME
DEPT_ID
Null?
--------
Type
----------NUMBER(7)
VARCHAR2(50)
VARCHAR2(25)
NUMBER(7)
10.5.Confirm that both the DEPARTMENT and EMPLOYEE tables are stored
in the data dictionary. (Hint: USER_TABLES)
TABLE_NAME
------------------------DEPARTMENT
EMPLOYEE
Página 25
10.6.Create the EMPLOYEE2 table based on the structure of the EMP table,
include only the EMPNO, ENAME and DEPTNO columns. Name the columns
in your new table ID, LAST_NAME and DEPT_ID, respectively.
10.7.Drop the EMPLOYEE table.
10.8.Rename the EMPLOYEE2 table to EMPLOYEE.
10.9.Add a comment to the DEPARTMENT and EMPLOYEE table definitions
describing the tables. Confirm your additions in the data dictionary.
T
EMA 111.
1. IINCLUYENDO
NCLUYENDO C
ONSTRAINTS.
TEMA
CONSTRAINTS.
11.1.Add a table level PRIMARY KEY constraint to the EMPLOYEE table
using the ID column. The constraint should be enabled at creation.
11.2.Create a PRIMARY KEY constraint on the DEPARTMENT table using the
ID column. The constraint should be enabled at creation.
11.3.Add a foreign key reference on the EMPLOYEE table that will ensure that
the employee is not assigned to a nonexistent department.
11.4.Confirm that the constraints were added by querying
USER_CONSTRAINTS. Note the types and names of the constraints. Save
your statement text in a file called p11q4.sql.
CONSTRAINT_NAME
----------------------DEPARTMENT_ID_PK
EMPLOYEE_ID_PK
EMPLOYEE_DEPT_ID_FK
C
-P
P
R
11.5.Display the object names and types from the USER_OBJECTS data
dictionary view EMPLOYEE and DEPARTMENT tables. You may want to
format the columns for readability. Notice that the new tables and a new index
were created.
OBJECT_NAME
-----------------------DEPARTMENT
DEPARTMENT_ID_PK
EMPLOYEE
EMPLOYEE_ID_PK
OBJECT_TYPE
--------------------TABLE
INDEX
TABLE
INDEX
11.6.Modify the EMPLOYEE table. Add a SALARY column of NUMBER data
type, precision 7.
Página 26
T
EMA 112.
2. C
REANDO V
ISTAS
ASS..
TEMA
CREANDO
VISTA
12.1.Create a view called EMP_VU based on the employee number, employee
name, and department number from the EMP table. Change the heading for the
employee name to EMPLOYEE.
12.2. Display the content’s of the EMP_VU view.
EMPNO
EMPLOYEE
-------------------------7839
KING
7698
BLAKE
7782
CLARK
7566
JONES
7654
MARTIN
7499
ALLEN
7844
TURNER
7900
JAMES
7521
WARD
7902
FORD
7369
SMITH
7788
SCOTT
7876
ADAMS
7934
MILLER
14 rows selected.
DEPTNO
------------10
30
10
20
30
30
30
30
30
20
20
20
20
10
12.3.Select the view_name and text from the data dictionary USER_VIEWS.
VIEW_NAME
----------EMP_VU
TEXT
---------------------------------------SELECT empno, ename employee, deptno
FROM emp
12.4.Using your view EMP_VU, enter a query to display all employee names and
department numbers.
EMPLOYEE
----------------KING
BLAKE
CLARK
JONES
MARTIN
14 rows selected.
DEPTNO
-------------10
30
10
20
30
12.5.Create a view named DEPT20 that contains the employee number,
employee name, and department number for all employees in department 20.
Label the view column EMPLOYEE_ID, EMPLOYEE, and
DEPARTMENT_ID. Do not allow an employee to be reassigned to another
Página 27
department through the view.
12.6.Display the structure and contents of the DEPT20 view.
Name
Null?
Type
--------------------- ----------------EMPLOYEE_ID NOT NULL NUMBER(4)
EMPLOYEE
VARCHAR2(10)
DEPARTMENT_ID NOT NULL NUMBER(2)
EMPLOYEE_ID
------------------7566
7902
7369
7788
7876
EMPLOYEE DEPARTMENT_ID
----------------- -------------------------JONES
20
FORD
20
SMITH
20
SCOTT
20
ADAMS
20
12.7.Attempt to reassign Smith to department 30.
12.8.Create a view called SALARY_VU based on the employee name,
department name, salary and salary grade for all employees. Label the columns
Employee, Department, Salary and Grade, respectively.
T
EMA 113.
3. O
TROS O
BJETOS D
EB
ASE D
ED
ATOS.
TEMA
OTROS
OBJETOS
DE
BASE
DE
DATOS.
13.1.Create a sequence to be used with the DEPARTMENT table’s primary key
column. The sequence should start at 60 and have a maximum value of 200. Have
your sequence increment by ten numbers. Name the sequence DEPT_ID_SEQ.
13.2.Write a script to display the following information about your sequences:
sequence name, maximum value, increment size, and last number. Name the
script p13q2.sql. Execute your script.
SEQUENCE_NAME MAX_VALUE INCREMENT_BY AST_NUMBER
--------------------------------------------- ----------------------- -------------------CUSTID
1.000E+27
1
109
DEPT_ID_SEQ
200
1
60
ORDID
1.000E+27
1
622
PRODID
1.000E+27
1
200381
13.3.Write an interactive script to insert a row into the DEPARTMENT table.
Name your script p13q3.sql. Be sure to use the sequence that you created for the
ID column. Create a customized prompt to enter the department name. Execute
your script. Add two departments named Education and Administration.
Confirm your additions.
13.4.Create a non-unique index on the FOREIGN KEY column in the
EMPLOYEE table.
13.5.Display the indexes and uniqueness that exist in the data dictionary for the
Página 28
EMPLOYEE table.
Save the statement into a script named p13q5.sql.
INDEX_NAME
------------------------------------EMPLOYEE_DEPT_ID_IDX
EMPLOYEE_ID_PK
TABLE_NAME
-------------------EMPLOYEE
EMPLOYEE
UNIQUENES
-----------------NONUNIQUE
UNIQUE
T
EMA 115.
5. R
EPASO.
TEMA
REPASO.
15.1.Create the tables based on the table instance charts below. Choose the
appropriate datatypes and be sure to add integrity constraints.
a. Table name: MEMBER
Column_
Name
Key
Type
Null/
Unique
Default
Value
Data
Type
Length
MEMBE
R_ID
PK
LAST_
NAME
FIRST_
NAME
ADDRESS
NN,U
NN
NN
Number
Varchar2
Varchar2
Varchar2
Varchar2
Varchar2
System
Date
Date
10
25
25
100
30
15
b. Table name TITLE
Página 29
CITY
PHONE
JOIN_
DATE
Column_
Name
Key
Type
Null/
Unique
Check
TITLE_ID
TITLE
DESCRIPTION
NN
NN
RATING CATEGORY
Data
Type
Length
Number
Varchar2
Varchar2
Varchar2
Varchar2
10
60
400
4
20
RELEASE_
DATE
PK
NN,U
G, PG, R,
NC17, NR
DRAMA,
COMEDY,
ACTION,
CHILD,
SCIFI,
DOCUMENTAR
Y
Date
c. Table:TITLE-COPY
Column Name
COPY_ID
TITLE_ID
Key
Type
Null/
Unique
Check
PK
PK,FK
NN,U
NN,U
NN
Data Type
Length
Number
10
Number
10
AVAILABLE,
DESTROYED,
RENTED,
RESERVED
Varchar2
15
d. Table name: RENTAL
Página 30
STATUS
Column
Name
Key
Type
Default
Value
FK Ref
Table
FK Ref
Col
Data
Type
Length
BOOK_
DATE
PK
MEMBER_
ID
PK,FK
COPY_
ID
PK,FK
ACT_RET_
DATE
System
Date
EXP_RET_
DATE
2 days
member
copy_id
title_copy
member_id
Date
TITLE_
ID
PK,FK
title_id
Number
Number
10
10
Date
Date
Number
10
e. Table name: RESERVATION
Column_
Name
Key
Type
Null/
Unique
FK Ref
Table
FK Ref
Column
Data Type
Length
RES_
DATE
PK
MEMBER_
ID
PK,FK
TITLE_
ID
PK,FK
NN,U
NN,U
NN
MEMBER
TITLE
member_id
title_id
Number
Number
10
10
Date
15.2. Verify that the tables and constraints were created properly by checking
the data dictionary.
TABLE_NAME
----------MEMBER
RENTAL
RESERVATION
TITLE
TITLE_COPY
CONSTRAINT_NAME
----------------------------------------------------MEMBER_LAST_NAME_NN
MEMBER_JOIN_DATE_NN
MEMBER_MEMBER_ID_PK
RENTAL_BOOK_DATE_COPY_TITLE_PK
Página 31
C
--C
C
P
P
TABLE_NAME
-------------MEMBER
MEMBER
MEMBER
RENTAL
RENTAL_MEMBER_ID_FK
RENTAL_COPY_ID_TITLE_ID_FK
RESERVATION_RESDATE_MEM_TIT_PK
RESERVATION_MEMBER_ID
RESERVATION_TITLE_ID
...
18 rows selected.
R
R
P
R
R
RENTAL
RENTAL
RESERVATION
RESERVATION
RESERVATION
15.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.
b. Title number for the TITLE table: start with 92; no caching. Name the
sequence title_id_seq.
c Verify the existence of the sequences in the data dictionary.
SEQUENCE_NAME
------------------------TITLE_ID_SEQ
MEMBER_ID_SEQ
INCREMENT_BY
----------------------1
1
LAST_NUMBER
---------------------92
101
15.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. Save the script as p15q4a.sql. Use the sequences to uniquely identify
each title. Remember that single quotation marks in a character field must be
specially handled. Verify your additions.
TITLE
-----------------------Willie and Christmas Too
Alien Again
The Glob
My Day Off
Miracles on Ice
Soda Gang
6 rows selected.
Página 32
Title
Description
Rating
Category
Release_date
Willie and
Christmas
Too
All of Willie’s friends made
a Christmas list for Santa, but
Willie has yet to add his own
wish list.
Yet another installation of
science fiction history. Can
the heroine save the planet
from the alien life form?
A meteor crashes near a
small American town and
unleashed carnivorous goo in
this classic.
With a little luck and a lot of
ingenuity, a teenager skips
school for a day in New York
A six-year-old has doubts
about Santa Claus but she
discovers that miracles really
do exist.
After discovering a cache of
drugs, a young couple find
themselves pitted against a
vicious gang.
G
CHILD
05-OCT-95
R
SCIFI
19-MAY-95
NR
SCIFI
12-AUG-95
PG
COMEDY
12-JUL-95
PG
DRAMA
12-SEP-95
NR
ACTION
01-JUN-95
Alien Again
The Glob
My Day Off
Miracles on
Ice
Soda Gang
b. Add data to the MEMBER table. Write a script named p15q4b.sql to prompt
users for the information. Execute the script. Be sure to use the sequence to add
the member numbers.
First
Name
Carmen
Last Name
Address
State
Phone
Join Date
Velasquez
283 King Street
Seattle
206-899-6666
08-MAR-90
LaDoris
Ngao
5 Modrany
Bratislava
586-355-8882
08-MAR-90
Midori
Nagayama
68 Via Centrale
Sao Paolo
254-852-5764
17-JUN-91
Mark
Lewis
6921 King Way Lagos
63-559-7777
07-APR-90
Audry
Ropeburn
86 Chu Street
Hong Kong
41-559-87
18-JAN-91
Molly
Urguhart
3035 Laurier
Quebec
418-542-9988
18-JAN-91
Página 33
c. Add the following movie copies in the TITLE_COPY table:
Title
Willie and Christmas Too
Alien
The Glob
My Day Off
Miracles on Ice
Soda Gang
Copy Number
1
1
2
1
1
2
3
1
1
Status
Available
Available
Rented
Available
Available
Available
Rented
Available
Available
d. Add the following rentals to the RENTAL table:
Note: Title number may be different depending on sequence number.
Title
Customer
92
Copy_
number
1
Date_return_expected
101
Date_
Rented
3 days ago
1 day ago
Date_
returned
2 days ago
93
95
97
2
3
1
101
102
106
1 day ago
2 days ago
4 days ago
1 day from now
Today
2 days ago
2 days ago
15.5.Create a view named TITLE_AVAIL to show the movie titles and the
availability of each copy and its expected return date if rented. Query all rows
from the view.
TITLE
-----------------------------Alien Again
Alien Again
Miracles on Ice
My Day Off
My Day Off
My Day Off
Soda Gang
The Glob
Willie and Christmas Too
9 rows selected.
COPY_ID
STATUS
-------------- -------------1
AVAILABLE
2
RENTED
1
AVAILABLE
1
AVAILABLE
2
AVAILABLE
3
RENTED
1
AVAILABLE
1
AVAILABLE
1
AVAILABLE
EXP_RET_D
-----------------05-NOV-97
06-NOV-97
04-NOV-97
05-NOV-97
15.6.Make changes to data in the tables.
a. Add a new title. The movie is “Interstellar Wars,” which is rated PG and
classified as a Sci-fi movie. The release date is 07-JUL-77. The description is
Página 34
“Futuristic interstellar action movie. Can the rebels save the humans from the
evil Empire?” Be sure to add a title copy record for two copies.
b. Enter two reservations. One reservation is for Carmen Velasquez, who wants
to rent “Interstellar Wars.” The other is for Mark Lewis, who wants to rent
“Soda Gang.”
c. Customer Carmen Velasquez rents the movie “Interstellar Wars,” copy 1.
Remove her reservation for the movie. Record the information about the rental.
Allow the default value for the expected return date to be used. Verify that the
rental was recorded by using the view you created.
TITLE
COPY_ID
-------------------------------- -----------Alien Again
1
Alien Again
2
Interstellar Wars
1
Interstellar Wars
2
Miracles on Ice
1
My Day Off
1
My Day Off
2
My Day Off
3
Soda Gang
1
The Glob
1
Willie and Christmas Too 1
9 rows selected.
STATUS
-------------------AVAILABLE
RENTED
RENTED
AVAILABLE
AVAILABLE
AVAILABLE
AVAILABLE
RENTED
AVAILABLE
AVAILABLE
AVAILABLE
EXP_RET_D
---------------05-NOV-97
08-NOV-97
06-NOV-97
04-NOV-97
05-NOV-97
15.7.Make a modification to one of the tables.
a. Add a PRICE column to the TITLE table to record the purchase price of the
video. The column should have a total length of eight digits and two decimal
places. Verify your modifications.
Name
---------------------TITLE_ID
TITLE
DESCRIPTION
RATING
CATEGORY
RELEASE_DATE
PRICE
Null?
-----------------NOT NULL
NOT NULL
NOT NULL
Type
----------------------NUMBER(10)
VARCHAR2(60)
VARCHAR2(400)
VARCHAR2(4)
VARCHAR2(20)
DATE
NUMBER(8,2)
b. Create a script named p15q7b.sql to update each video with a price according
to the following list. Note: Have the title id numbers available for this exercise.
Página 35
Title
Willie and Christmas Too
Alien Again
The Glob
My Day Off
Miracles on Ice
Soda Gang
Interstellar Wars
Price
25
35
35
35
98
35
29
c. Ensure that in the future all titles will contain a price value. Verify the
constraint.
CONSTRAINT_NAME
C
-------------------------------- ---TITLE_PRICE_NN
C
SEARCH_CONDITIONS
------------------------------------PRICE IS NOT NULL
15.8.Create a report titles Customer History Report. This report will contain
each customer’s history of renting videos. Be sure to include the customer name,
movie rented, dates of the rental, and duration of rentals. Total the number of
rentals for all customers for the reporting period. Save the script in a file name
p15q8.sql.
MEMBER
----------------------LaDoris Ngao
Molly Urguhart
Carmen Velasquez
TITLE
-----------------The Glob
Miracles on Ice
Willie and Christmas
Too
Willie and Christmas
Too
Alien Again
BOOK_DATE DURATION
------------------------ -------04-NOV-97
02-NOV-97
2
03-NOV-97
1
03-NOV-97
1
05-NOV-97
T
EMA 116.
6. D
ECLARACIÓN D
EV
ARIABLES.
TEMA
DECLARACIÓN
DE
VARIABLES.
Declare variables.
16.1.Evaluate each of the following declarations. Determine which of them are
not legal and explain why.
a.
DECLARE
Página 36
v_id
b.
c.
d.
e.
NUMBER(4);
DECLARE
v_x, v_y, v_z
VARCHAR2(10);
DECLARE
v_birthdate
DATE NOT NULL;
DECLARE
v_in_stock
BOOLEAN := 1;
DECLARE
TYPE name_table_type IS TABLE OF VARCHAR2(20)
INDEX BY BINARY_INTEGER;
dept_name_table
name_table_type;
16.2.In each of the following assignments, determine the data type of the
resulting expression.
a.
v_days_to_go := v_due_date - SYSDATE;
b.
v_sender := USER || ': ' || TO_CHAR(v_dept_no);
c.
d.
e.
v_sum := $100,000 + $250,000;
v_flag := TRUE;
v_n1 := v_n2 > (2 * v_n3);
f.
v_value := NULL;
16.3.Create an anonymous block to output the phrase “My PL/SQL Block
Works” to the screen.
G_MESSAGE
----------------------My PL/SQL Block Works
16.4.Create a block that declares two variables. Assign the value of these
PL/SQL variables to SQL*Plus host variables and print the results of the
PL/SQL variables to the screen. Execute your PL/SQL block. Save your PL/SQL
block to a file named p16q4.sql.
V_CHAR Character (variable length)
V_NUM
Number
Assign values to these variables as follows:
Variable Value
-------- ------------------------------------V_CHAR The literal '42 is the answer'
V_NUM The first two characters from V_CHAR
Página 37
G_CHAR
--------------------42 is the answer
G_NÚMERO
--------42
T
EMA 117.
7. E
SCRIBIENDO M
ANDATOS E
JECUTABLES.
TEMA
ESCRIBIENDO
MANDATOS
EJECUTABLES.
PL/SQL Block
DECLARE
v_weight
v_message
BEGIN
NUMBER(3) := 600;
VARCHAR2(255) := 'Product 10012';
SUB-BLOCK
DECLARE
v_weight
NUMBER(3) := 1;
v_message
VARCHAR2(255) := 'Product 11001';
v_new_locn VARCHAR2(50) := 'Europe';
BEGIN
v_weight := v_weight + 1;
v_new_locn := 'Western ' || v_new_locn;
END;
v_weight := v_weight + 1;
v_message := v_message || ' is in stock';
v_new_locn := 'Western ' || v_new_locn;
END;
17.1.Evaluate the PL/SQL block on the previous page and determine each of the
following values according to the rules of scoping.
a. The value of V_WEIGHT in the subblock is
____________________________________________________________________
b. The value of V_NEW_LOCN in the subblock is
____________________________________________________________________
c. The value of V_WEIGHT in the main block is
____________________________________________________________________
Página 38
d. The value of V_MESSAGE in the main block is
____________________________________________________________________
e. The value of V_NEW_LOCN in the main block is
____________________________________________________________________
Scope Example
DECLARE
v_customer
v_credit_rating
BEGIN
DECLARE
v_customer
v_name
BEGIN
v_customer
END;
v_customer
VARCHAR2(50) := 'Womansport';
VARCHAR2(50) := 'EXCELLENT';
NUMBER(7) := 201;
VARCHAR2(25) := 'Unisports';
v_name
v_credit_rating
v_name
v_credit_rating
END;
17.2.Suppose you embed a subblock within a block, as shown on the previous
page. You declare two variables, V_CUSTOMER and V_CREDIT_RATING, in
the main block. You also declare two variables, V_CUSTOMER and V_NAME,
in the subblock. Determine the values for each of the following cases.
a. The value of V_CUSTOMER in the subblock is
____________________________________________________________________
b. The value of V_NAME in the subblock is
____________________________________________________________________
c. The value of V_CREDIT_RATING in the subblock is
____________________________________________________________________
Página 39
d. The value of V_CUSTOMER in the main block is
____________________________________________________________________
e. The value of V_NAME in the main block is
____________________________________________________________________
f. The value of V_CREDIT_RATING in the main block is
____________________________________________________________________
17.3.Create and execute a PL/SQL block that accepts two numbers through
SQL*Plus substitution variables. The first number should be divided by the
second number and have the second number added to the result. The result
should be written to a PL/SQL variable and printed to the screen.
Please enter the first number: 2
Please enter the second number: 4
PL/SQL procedure successfully completed.
V_RESULT
--------------4.5
17.4.Build a PL/SQL block that computes the total compensation for one year.
The annual salary and the annual bonus percentage are passed to the PL/SQL
block through SQL*Plus substitution variables and the bonus needs to be
converted from a whole number to a decimal (for example, 15 to .15). If the
salary is null, set it to zero before computing the total compensation. Execute the
PL/SQL block. Reminder: Use the NVL function to handle null values.
Note: To test the NVL function type NULL at the prompt; pressing [Return]
results in a missing expression error.
Please enter the salary amount: 50000
Please enter the bonus percentage: 10
PL/SQL procedure successfully completed.
G_TOTAL
-------------55000
T
EMA 118.INTERACTUANDO
8.INTERACTUANDO C
ON O
RACLE SSERVER.
ERVER.
TEMA
CON
ORACLE
18.1.Create a PL/SQL block that selects the maximum department number in
the DEPT table and store it in a SQL*Plus variable. Print the results to the
screen. Save your PL/SQL block to a file named p18q1.sql.
Página 40
G_MAX_DEPTNO
------------------------40
18.2.Create a PL/SQL block that inserts a new department into the DEPT table.
Save your PL/SQL block to a file named p18q2.sql.
a. Use the department number retrieved from exercise 1 and add 10 to that
number as the input department number for the new department.
b. Use a parameter for the department name.
c. Leave the location null for now.
d. Execute the PL/SQL block.
Please enter the department number: 50
Please enter the department name: EDUCATION
PL/SQL procedure successfully completed.
e. Display the new department that you created.
DEPTNO
----------------50
DNAME
---------------------EDUCATION
LOC
---------
18.3.Create a PL/SQL block that updates the location for an existing
department. Save your PL/SQL block to a file named p18q3.sql.
a. Use a parameter for the department number.
b. Use a parameter for the department location.
c. Test the PL/SQL block.
Please enter the department number: 50
Please enter the department location: HOUSTON
PL/SQL procedure successfully completed.
d. Display the department number, department name, and location for the
updated department.
DEPTNO
-----50
DNAME
--------EDUCATION
LOC
--------------HOUSTON
e. Display the department that you updated.
18.4.Create a PL/SQL block that deletes the department created in exercise 2.
Save your PL/SQL block to a file named p18q4.sql.
a. Use a parameter for the department number.
b. Print to the screen the number of rows affected.
Página 41
c. Test the PL/SQL block.
Please enter the department number: 50
PL/SQL procedure successfully completed.
G_RESULT
----------------------------------------------------------1 row(s) deleted.
d. What happens if you enter a department number that does not exist?
Please enter the department number: 99
PL/SQL procedure successfully completed.
G_RESULT
----------------------------------------------------------0 row(s) deleted.
e.Confirm that the department has been deleted.
no rows selected
T
EMA 119.ESTRUCTURAS
9.ESTRUCTURAS D
EC
ONTROL.
TEMA
DE
CONTROL.
19.1.Run the script
/home/db/InformaciónGeneral/practicasdb2000/tema19/lab19_1.sql to create the
MESSAGES table. Write a PL/SQL block to insert numbers into the
MESSAGES table.
a . Insert the numbers 1 to 10 excluding 6 and 8.
b. Commit before the end of the block.
c. Select from the MESSAGES table to verify that your PL/SQL block worked.
RESULTS
----------------1
2
3
4
5
7
9
10
19.2.Create a PL/SQL block that computes the commission amount for a given
employee based on the employee’s salary.
a. Run the script
Página 42
/home/db/InformaciónGeneral/practicasdb2000/tema19/lab19_2.sql to insert a
new employee into the EMP table.
Note: The employee will have a NULL salary.
b. Accept the employee number as user input with a SQL*Plus substitution
variable.
c. If the employee’s salary is less than $1,000, set the commission amount for the
employee to 10% of the salary.
d. If the employee’s salary is between $1,000 and $1,500, set the commission
amount for the employee to 15% of the salary.
e. If the employee’s salary exceeds $1,500, set the commission amount for the
employee to 20% of the salary.
f. If the employee’s salary is NULL, set the commission amount for the employee
to 0.
g. Commit.
h. Test the PL/SQL block for each case using the following test cases, and check
each updated commission.
Employee Number
Salary
Resulting Commission
7369
800
80
7934
1300
195
7499
1600
320
8000
NULL
NULL
EMPNO
----------8000
7499
7934
7369
ENAME
----------DOE
ALLEN
MILLER
SMITH
SAL
-------1600
1300
800
COMM
--------0
320
195
80
19.3.Modify p16q4.sql to insert the text “Number is odd” or “Number is even,”
depending on whether the value is odd or even, into the MESSAGES table.
Query the MESSAGES table to determine if your PL/SQL block worked.
RESULTS
--------------Number is even
19.4
4.Add a new column to the EMP table for storing asterisk (*).
19.5
5.Create a PL/SQL block that rewards an employee by appending an
asterisk in the STARS column for every $100 of the employee's salary. Round
the employee’s salary to the nearest whole number. Save your PL/SQL block to
a file called p19q5.sql.
Página 43
a. Accept the employee ID as user input with a SQL*Plus substitution variable.
b. Initialize a variable to contain a string of asterisks.
c. Append an asterisk to the string for every $100 of the salary amount. For
example, if the employee has a salary amount of $800, the string of asterisks
should contain eight asterisks.
d. Update the STARS column for the employee with the string of asterisks.
e. Commit.
f. Test the block for employees who have no salary and for an employee who
has a salary.
Please enter the employee number: 7934
PL/SQL procedure successfully completed.
Please enter the employee number: 8000
PL/SQL procedure successfully completed.
EMPNO
SAL
STARS
------------ -----------------------8000
7934
1300
*************
T
EMA 220.TRABAJANDO
0.TRABAJANDO C
ON T
IPOS C
OMPUESTOS.
TEMA
CON
TIPOS
COMPUESTOS.
20.1.Run the script
/home/db/InformaciónGeneral/practicasdb2000/tema20/lab20_1.sql to create a
new table for storing employees and their salaries.
SQL> CREATE TABLE top_dogs
2 (name
VARCHAR2(25),
3 salary
NUMBER(11,2));
20.2.Write a PL/SQL block to retrieve the name and salary of a given employee
from the EMP table based on the employee’s number, incorporate PL/SQL
tables.
a. Declare two PL/SQL tables, ENAME_TABLE and SAL_TABLE, to
temporarily store the names and salaries.
b. As each name and salary is retrieved within the loop, store them in the
PL/SQL tables.
c. Outside the loop, transfer the names and salaries from the PL/SQL tables into
the TOP_DOGS table.
d. Empty the TOP_DOGS table and test the practice.
Please enter the employee number: 7934
PL/SQL procedure successfully completed.
NAME
--------------MILLER
SALARY
--------1300
Página 44
Please enter the employee number: 7876
PL/SQL procedure successfully completed.
NAME
--------------ADAMS
SALARY
--------1100
T
EMA 221.CUR
1.CURS
ORES.
RSSORES.
TEMA
21.1.Create a PL/SQL block that determines the top employees with respect to
salaries.
a. Accept a number n as user input with a SQL*Plus substitution parameter.
b. In a loop, get the last names and salaries of the top n people with respect to
salary in the EMP table.
c. Store the names and salaries in the TOP_DOGS table.
d. Assume that no two employees have the same salary.
e. Test a variety of special cases, such a n = 0, where n is greater than the
number of employees in the EMP table. Empty the TOP_DOGS table after
each test.
Please enter the number of top money makers: 5
NAME
SALARY
----------- -----KING
5000
FORD
3000
SCOTT
3000
JONES
2975
BLAKE
2850
21.2.Consider the case where several employees have the same salary. If one
person is listed, then all people who have the same salary should also be listed.
a. For example, if the user enters a value of 2 for n, then King, Ford and Scott
should be displayed. (These employees are tied for second highest salary.)
b. If the user enters a value of 3, then King, Ford, Scott, and Jones should be
displayed.
c. Delete all rows from TOP_DOGS and test the practice.
Please enter the number of top money makers: 2
NAME
SALARY
------------ ------------KING
5000
FORD
3000
SCOTT
3000
Please enter the number of top money makers: 3
NAME
SALARY
------------ -----Página 45
KING
FORD
SCOTT
JONES
5000
3000
3000
2975
T
EMA 222.CUR
2.CURS
ORES E
XPLÍCITOS A
VANZADOS.
RSSORES
TEMA
EXPLÍCITOS
AVANZADOS.
22.1.Write a query to retrieve all the departments and the employees in each
department. Insert the results in the MESSAGES table. Use a cursor to retrieve
the department number and pass the department number to a cursor to retrieve
the employees in that department.
RESULTS
-----------------------KING - Department 10
CLARK - Department 10
MILLER - Department 10
JONES - Department 20
FORD - Department 20
SMITH - Department 20
SCOTT - Department 20
ADAMS - Department 20
BLAKE - Department 30
MARTIN - Department 30
ALLEN - Department 30
TURNER - Department 30
JAMES - Department 30
WARD - Department 30
14 rows selected.
22.2.Modify p19q5.sql to incorporate the FOR UPDATE and WHERE
CURRENT OF functionality in cursor processing.
EMPNO
--------------8000
7900
7844
SAL STARS
------ --------------------950 **********
1500 ***************
T
EMA 223.MANEJO
3.MANEJO D
EE
XCEPCIONES.
TEMA
DE
EXCEPCIONES.
23.1.Write a PL/SQL block to select the name of the employee with a given
salary value.
a. If the salary entered returns more than one row, handle the exception with an
appropriate exception handler and insert into the MESSAGES table, the
message “More than one employee with a salary of <salary>.”
b. If the salary entered does not return any rows, handle the exception with an
Página 46
appropriate exception handler and insert into the MESSAGES table, the
message “No employee with a salary of <salary>.”
c. If the salary entered returns only one row, insert into the MESSAGES table
the employee’s name and the salary amount.
d. Handle any other exception with an appropriate exception handler and insert
into the MESSAGES table, the message “Some other error occurred.”
e. Test the block for a variety of test cases.
RESULTS
-------------------------------------------SMITH - 800
More than one employee with a salary of 3000
No employee with a salary of 6000
23.2.Modify p18q3.sql to add an exception handler.
a. Write an exception handler for the error to pass a message to the user that the
specified department does not exist.
b. Execute the PL/SQL block by entering a department that does not exist.
Please enter the department number: 50
Please enter the department location: HOUSTON
PL/SQL procedure successfully completed.
G_MESSAGE
-------------------------------------Department 50 is an invalid department
23.3.Write a PL/SQL block that prints the names of the employees who make
plus or minus $100 of the salary value entered.
a. If there is no employee within that salary range, print a message to the user
indicating that is the case. Use an exception for this case.
b. If there are one or more employees within that range, the message should
indicate how many employees are in that salary range.
c. Handle any other exception with an appropriate exception handler, the
message should indicate that some other error occurred.
Please enter the salary: 800
PL/SQL procedure successfully completed.
G_MESSAGE
---------------------------------------------------------There is 1 employee(s) with a salary between 700 and 900
Please enter the salary: 3000
PL/SQL procedure successfully completed.
G_MESSAGE
---------------------------------------------------------There are 3 employee(s) with a salary between 2900 and 3100
Please enter the salary: 6000
PL/SQL procedure successfully completed.
G_MESSAGE
------------------------------------------------Página 47
There are no employee salary between 5900 and 6100
T
EMA 224.OPERADORES
4.OPERADORES D
EC
ONJUNTOS.
TEMA
DE
CONJUNTOS.
24.1.Display the department that has no employees.
DEPTNO
--------40
DNAME
-------------OPERATIONS
24.2.Find the job that was filled in the last half of 1981 and the same job that was
filled during the same period in 1982.
JOB
--------ANALYST
24.3.Write a compound query to produce a list of products showing discount
percentages, product id, and old and new actual price. Products under $10 are
reduced by 10%, products between $10 and $30 are reduced by 15%, products
over $30 are reduced by 20%, and products over $40 are not reduced at all.
DISCOUNT
----------------10% off
10% off
10% off
10% off
10% off
10% off
10% off
15% off
15% off
15% off
20% off
20% off
20% off
no disc
no disc
no disc
no disc
PRODID
--------100870
100870
100871
100871
102130
200376
200380
100860
101860
101863
100860
100860
100861
100861
100861
100890
100890
STDPRICE
---------------2.4
2.8
4.8
5.6
3.4
2.4
4
30
24
12.5
32
35
39
42
45
54
58
ACTPRICE
----------------2.16
2.52
4.32
5.04
3.06
2.16
3.6
25.5
20.4
10.625
25.6
28
31.2
42
45
54
58
24.4.Produce a list of jobs for departments 10, 30, and 20 in that order. Display
job and department number.
JOB
--------CLERK
MANAGER
DEPTNO
-------10
10
Página 48
PRESIDENT
CLERK
MANAGER
SALESMAN
ANALYST
CLERK
MANAGER
10
30
30
30
20
20
20
24.5. List the department number for departments without the job title
ANALYST .
DEPTNO
-----------10
30
40
24.6.List all job titles in department 10 and 20 that do not occur in both
departments.
JOB
-----------------ANALYST
PRESIDENT
T
EMA 225.
5. SSUBCONSULTA
UBCONSULTAS
ORR
LACIONADAS.
AS C
TEMA
COR
RE
ELACIONADAS.
25.1.Write a query to display the top three earners in the EMP table. Display
their names and salaries.
ENAME
---------KING
FORD
SCOTT
SAL
--------5000
3000
3000
25.2.Find all employees who are not a supervisor.
a. Do this using the EXISTS operator first.
ENAME
---------MARTIN
ALLEN
TURNER
JAMES
WARD
SMITH
ADAMS
Página 49
MILLER
b. Can this be done using the IN operator? Why, or why not?
25.3. Write a query to find all employees who make more than the average salary
in their department. Display employee number, salary, department number,
and the average salary for the department. Sort by average salary.
ENAME
------------ALLEN
BLAKE
JONES
FORD
SCOTT
KING
SALARY
------------1600
2850
2975
3000
3000
5000
DEPTNO
-------------30
30
20
20
20
10
DEPT_AVG
----------------1566.6667
1566.6667
2175
2175
2175
2916.6667
25.4.Write a query to display employees who earn less than half the average
salary in their department.
ENAME
---------SMITH
MILLER
25.5. Write a query to display employees who have one or more co-workers in
their department with later hiredates but higher salaries.
ENAME
---------CLARK
JONES
ALLEN
WARD
SMITH
Página 50
Descargar