Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ......

50
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 TEMA 1. MANDATO SELECT BÁSICO T T E E M M A A 1 1 . . M M A A N N D D A A T T O O S S E E L L E E C C T T B B Á Á S S I I C C O O 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 ename, job, sal Salary FROM emp; 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 empno,ename salary x 12 ANNUAL SALARY FROM emp; 1.6.Show the structure of the DEPT table. Select all data from the DEPT table. Name Null? Type ----------------- --------------- ------------ DEPTNO NOT NULL NUMBER(2) DNAME VARCHAR2(14) LOC VARCHAR2(13) DEPTNO DNAME LOC ------------ ------------------- ------------- 10 ACCOUNTING NEWYORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS 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

Transcript of Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ......

Page 1: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

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

TEMA 1. MANDATO SELECT BÁSICO TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO 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 ename, job, sal Salary

FROM emp;

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 empno,ename salary x 12 ANNUAL SALARY

FROM emp; 1.6.Show the structure of the DEPT table. Select all data from the DEPT table.

Name Null? Type ----------------- --------------- ------------ DEPTNO NOT NULL NUMBER(2) DNAME VARCHAR2(14) LOC VARCHAR2(13) DEPTNO DNAME LOC ------------ ------------------- ------------- 10 ACCOUNTING NEWYORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS 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

Page 2: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

Name Null? Type ----------------- --------------- ------------- EMPNO NOT NULL NUMBER(4) ENAME VARCHAR2(10) JOB VARCHAR2(9) MGR NUMBER(4) HIREDATE DATE SAL NUMBER(7,2) COMM NUMBER(7,2) DEPTNO NOT NULL NUMBER(2)

1.8.Run your query in the file p1q7.sql.

EMPNO ENAME JOB HIREDATE ----------- ----------- ---------------- ---------------- 7839 KING PRESIDENT 17-NOV-81 7698 BLAKE MANAGER 01-MAY-81 7782 CLARK MANAGER 09-JUN-81 7566 JONES MANAGER 02-APR-81 7654 MARTIN SALESMAN 28-SEP-81 7499 ALLEN SALESMAN 20-FEB-81 7844 TURNER SALESMAN 08-SEP-81 7900 JAMES CLERK 03-DEC-81 7521 WARD SALESMAN 22-FEB-81 7902 FORD ANALYST 03-DEC-81 7369 SMITH CLERK 17-DEC-80 7788 SCOTT ANALYST 09-DEC-82 7876 ADAMS CLERK 12-JAN-83 7934 MILLER CLERK 23-JAN-82 14 rows selected.

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 # Employee JobHire Date --------- ------- ---------- -------------- 7839 KING PRESIDENT 17-NOV-81 7698 BLAKE MANAGER 01-MAY-81

Página 2

Page 3: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

7782 CLARK MANAGER 09-JUN-81 7566 JONES MANAGER 02-APR-81 7654 MARTIN SALESMAN 28-SEP-81 7499 ALLEN SALESMAN 20-FEB-81 7844 TURNER SALESMAN 08-SEP-81 7900 JAMES CLERK 03-DEC-81 7521 WARD SALESMAN 22-FEB-81 7902 FORD ANALYST 03-DEC-81 7369 SMITH CLERK 17-DEC-80 7788 SCOTT ANALYST 09-DEC-82 7876 ADAMS CLERK 12-JAN-83 7934 MILLER CLERK 23-JAN-82 14 rows selected.

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

Page 4: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

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.

TEMA 2.RESTTRIC IIÓN Y ORDENACIÓN DE LOS DATOS

RECUPERADOS. TTEEMMAA 22..RREESSTRRIICCCCCIÓÓNN YY OORRDDEENNAACCIIÓÓNN DDEE LLOOSS DDAATTOOSS

RREECCUUPPEERRAADDOOSS.. 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 SAL ------------ ---- KING 5000 JONES 2975 FORD 3000 SCOTT 3000

2.2.Create a query to display the employee name and department number for employee number 7566.

ENAME DEPTNO ----------- ------ JONES 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 SAL ------------ ----- KING 5000 JONES 2975 MARTIN 1250 JAMES 950 WARD 1250 FORD 3000 SMITH 800

Página 4

Page 5: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

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 JOB HIREDATE ------------ ----------------- ---------------- ALLEN SALESMAN 20-FEB-81 WARD SALESMAN 22-FEB-81 JONES MANAGER 02-APR-81 BLAKE MANAGER 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

Page 6: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

------------ ---------------- SCOTT 09-DEC-82 MILLER 23-JAN-82

2.8.Display the name and title of all employees who do not have a manager.

ENAME JOB ------------ --------- KING 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 SAL.... COMM ----------- --------- --------- ALLEN 1600 300 TURNER 1500 0 MARTIN 1250 1400 WARD 1250 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 JOB SAL ------------ ------- ----- JAMES CLERK 950 SMITH CLERK 800 ADAMS CLERK 1100 MILLER CLERK 1300

Página 6

Page 7: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

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 SAL COMM ------------- ----- ---------- MARTIN 1250 1400

TEMA 3. FUNCIONES DE SQL QUE ACTÚAN SOBRE UNA SOLA

FILA. TTEEMMAA 33.. FFUUNNCCIIOONNEESS DDEE SSQQLL QQUUEE AACCTTÚÚAANN SSOOBBRREE UUNNAA SSOOLLAA

FFIILLAA.. 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 SAL New Salary ----------- ------------ ----- -------------- 7839 KING 5000 5750 7698 BLAKE 2850 3278 7782 CLARK 2450 2818 7566 JONES 2975 3421 7654 MARTIN 1250 1438 7499 ALLEN 1600 1840 7844 TURNER 1500 1725 7900 JAMES 950 1093 7521 WARD 1250 1438 7902 FORD 3000 3450 7369 SMITH 800 920 7788 SCOTT 3000 3450 7876 ADAMS 1100 1265 7934 MILLER 1300 1495 14 rows selected.

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

Page 8: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

query. EMPNO ENAME SAL New Salary Increase ----------- ------------ ------- ---------- -------- 7839 KING 5000 5750 750 7698 BLAKE 2850 3278 428 7782 CLARK 2450 2818 368 7566 JONES 2975 3421 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 REVIEW ----------- ----------------- ------------------------------------------------- KING 17-NOV-81 Monday, the Twenty-Fourth of May, 1982 BLAKE 01-MAY-81 Monday, the Second of November, 1981 CLARK 09-JUN-81 Monday, the Fourteenth of December, 1981 JONES 02-APR-81 Monday, the Fifth of October, 1981 MARTIN 28-SEP-81 Monday, the Twenty-Ninth of March, 1982 ALLEN 20-FEB-81 Monday, the Twenty-Fourth of August, 1981 TURNER 08-SEP-81 Monday, the Fifteenth of March, 1982 JAMES 03-DEC-81 Monday, the Seventh of June, 1982 WARD 22-FEB-81 Monday, the Twenty-Fourth of August, 1981 FORD 03-DEC-81 Monday, the Seventh of June, 1982 SMITH 17-DEC-80 Monday, the Twenty-Second of June, 1981 SCOTT 09-DEC-82 Monday, the Thirteenth of June, 1983 ADAMS 12-JAN-83 Monday, the Eighteenth of July, 1983 MILLER 23-JAN-82 Monday, the Twenty-Sixth of July, 1982

14 rows selected.

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 MONTHS_WORKED ----------- --------------------------- ADAMS 177 SCOTT 178 MILLER 188 JAMES 190 FORD 190 KING 191 MARTIN 192 TURNER 193 CLARK 196 BLAKE 197

Página 8

Page 9: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

JONES 198 WARD 199 ALLEN 199 SMITH 202 14 rows selected

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

Page 10: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

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 DAY ------ --------- ----------- MARTIN 28-SEP-81 MONDAY CLARK 09-JUN-81 TUESDAY KING 17-NOV-81 TUESDAY TURNER 08-SEP-81 TUESDAY SMITH 17-DEC-80 WEDNESDAY ADAMS 12-JAN-83 WEDNESDAY JONES 02-APR-81 THURSDAY FORD 03-DEC-81 THURSDAY SCOTT 09-DEC-82 THURSDAY JAMES 03-DEC-81 THURSDAY ALLEN 20-FEB-81 FRIDAY BLAKE 01-MAY-81 FRIDAY MILLER 23-JAN-82 SATURDAY WARD 22-FEB-81 SUNDAY 14 rows selected

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 COMM ------ ----------- SMITH No Commission ALLEN 300 WARD 500 JONES No Commission MARTIN 1400 BLAKE No Commission CLARK No Commission

Página 10

Page 11: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

SCOTT No Commission KING No Commission TURNER 0 ADAMS No Commission JAMES No Commission FORD No Commission MILLER No Commission

14 rows selected.

TEMA 4. OBTENIENDO DATOS DESDE MÚLTIPLES TABLAS. TTEEMMAA 44.. OOBBTTEENNIIEENNDDOO DDAATTOOSS DDEESSDDEE MMÚÚLLTTIIPPLLEESS TTAABBLLAASS.. 4.1.Write a query to display the name, department number, and department name for all employees.

ENAME DEPTNO DNAME ------------ ------------ ------------------- CLARK 10 ACCOUNTING KING 10 ACCOUNTING MILLER 10 ACCOUNTING SMITH 20 RESEARCH ADAMS 20 RESEARCH FORD 20 RESEARCH SCOTT 20 RESEARCH JONES 20 RESEARCH ALLEN 30 SALES BLAKE 30 SALES MARTIN 30 SALES JAMES 30 SALES TURNER 30 SALES WARD 30 SALES 14 rows selected.

4.2.Create a unique listing of all jobs that are in department 30.

JOB LOC -------------- ------------- CLERK CHICAGO MANAGER CHICAGO SALESMAN CHICAGO

4.3. Write a query to display the employee name, department name, and location of all employees who earn a commission.

ENAME DNAME LOC ------------- ------------- ------------- ALLEN SALES CHICAGO

Página 11

Page 12: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

WARD SALES CHICAGO MARTIN SALES CHICAGO TURNER SALES 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 JOB DEPTNO DNAME ----------- --------- ------------- ---------- SMITH CLERK 20 RESEARCH ADAMS CLERK 20 RESEARCH FORD ANALYST 20 RESEARCH SCOTT ANALYST 20 RESEARCH JONES MANAGER 20 RESEARCH

4.66..DDiissppllaayy tthhee eemmppllooyyeeee nnaammee aanndd eemmppllooyyeeee nnuummbbeerr aalloonngg wwiitthh tthheeiirr

mmaannaaggeerr’’ss nnaammee aanndd mmaannaaggeerr nnuummbbeerr.. LLaabbeell tthhee ccoolluummnnss EEmmppllooyyeeee,, EEmmpp##,, MMaannaaggeerr,, aanndd MMggrr##,, rreessppeeccttiivveellyy.. SSaavvee yyoouurr SSQQLL ssttaatteemmeenntt ttoo aa ffiillee ccaalllleedd pp44qq66..ssqqll..

Employee Emp# Manager Mgr# -------------- --------- ------------ --------- SCOTT 7788 JONES 7566 FORD 7902 JONES 7566 ALLEN 7499 BLAKE 7698 WARD 7521 BLAKE 7698 JAMES 7900 BLAKE 7698 TURNER 7844 BLAKE 7698 MARTIN 7654 BLAKE 7698 MILLER 7934 CLARK 7782 ADAMS 7876 SCOTT 7788

Página 12

Page 13: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

JONES 7566 KING 7839 CLARK 7782 KING 7839 BLAKE 7698 KING 7839 SMITH 7369 FORD 7902 13 rows selected.

4.7.Modify p4q6.sql to display all employees including King, who has no manager. Resave as p4q7.sql. Run p4q7.sql.

Employee Emp# Manager Mgr# ------------- ---------- ------------ --------- SCOTT 7788 JONES 7566 FORD 7902 JONES 7566 ALLEN 7499 BLAKE 7698 WARD 7521 BLAKE 7698 JAMES 7900 BLAKE 7698 TURNER 7844 BLAKE 7698 MARTIN 7654 BLAKE 7698 MILLER 7934 CLARK 7782 ADAMS 7876 SCOTT 7788 JONES 7566 KING 7839 CLARK 7782 KING 7839 BLAKE 7698 KING 7839 SMITH 7369 FORD 7902 KING 7839 14 rows selected.

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 EMPLOYEE COLLEAGUE --------------------- ------------------ --------- 10 CLARK KING 10 CLARK MILLER 10 KING CLARK 10 KING MILLER 10 MILLER CLARK 10 MILLER KING 20 ADAMS FORD 20 ADAMS JONES 20 ADAMS SCOTT 20 ADAMS SMITH 20 FORD ADAMS 20 FORD JONES 20 FORD SCOTT

Página 13

Page 14: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

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? Type ------------ ---------- ------- GRADE NUMBER LOSAL NUMBER HISAL NUMBER

ENAME JOB DNAME SAL GRADE ------------ ----------------- -------------------- --------- ----- MILLER CLERK ACCOUNTING 1300 2 CLARK MANAGER ACCOUNTING 2450 4 KING PRESIDENT ACCOUNTING 5000 5 SMITH CLERK RESEARCH 800 1 SCOTT ANALYST RESEARCH 3000 4 FORD ANALYST RESEARCH 3000 4 ADAMS CLERK RESEARCH 1100 1 JONES MANAGER RESEARCH 2975 4 JAMES CLERK SALES 950 1 BLAKE MANAGER SALES 2850 4 TURNER SALESMAN SALES 1500 3 ALLEN SALESMAN SALES 1600 3 WARD SALESMAN SALES 1250 2 MARTIN SALESMAN SALES 1250 2 14 rows selected.

4.10.Create a query to display the name and hire date of any employee hired after employee Blake.

ENAME HIREDATE ------------ ----------------- SMITH 17-DEC-80 ALLEN 20-FEB-81 WARD 22-FEB-81 JONES 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

Page 15: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

Employee Emp Hiredate Manager Mgr Hiredate ------------- --------------- ------------- ------------ ALLEN 20-FEB-81 BLAKE 01-MAY-81 WARD 22-FEB-81 BLAKE 01-MAY-81 JONES 02-APR-81 KING 17-NOV-81 CLARK 09-JUN-81 KING 17-NOV-81 BLAKE 01-MAY-81 KING 17-NOV-81 SMITH 17-DEC-80 FORD 03-DEC-81 6 rows selected.

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.

TEMA 5. FUNCIONES DE AGGREGACIÓN. TTEEMMAA 55.. FFUUNNCCIIOONNEESS DDEE AAGRREEGGAACCIIÓÓNN.. 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 Average ------------- ------------- - -------- ------------

Página 15

Page 16: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

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 Maximum Minimum Sum Average ------------------ ------------- ------------- -------- -------- ANALYST 3000 3000 6000 3000 CLERK 1300 800 4150 1038 MANAGER 2975 2450 8275 2758 PRESIDENT 5000 5000 5000 5000 SALESMAN 1600 1250 5600 1400

5.6.Write a query to display the number of people with the same job. JOB COUNT(*) ---------------- -------------- ANALYST 2 CLERK 4 MANAGER 3 PRESIDENT 1 SALESMAN 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 MIN(SAL) -------- -------- 7566 3000 7839 2450 7782 1300 7788 1100

Página 16

Page 17: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

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 LOC Number of People Salary --------------------- ------------------ ----------------------- -------- ACCOUNTING NEW YORK 3 2916.67 RESEARCH DALLAS 5 2175 SALES CHICAGO 6 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 1980 1981 1982 1983 ---------- -------- ------- -------- -------- 14 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 Dept 10 Dept 20 Dept 30 Total ----------------- ---------- -------- ----------- ------- ANALYST 6000 6000 CLERK 1300 1900 950 4150 MANAGER 2450 2975 2850 8275 PRESIDENT 5000 5000 SALESMAN 5600 5600

TEMA 6. SUBCONSULTAS. TTEEMMAA 66.. SSUUBBCCOONNSSUULLTTAASS..

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

Page 18: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

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 ENAME ------------ -------- 7566 JONES 7788 SCOTT 7876 ADAMS 7369 SMITH 7902 FORD 7698 BLAKE 7654 MARTIN 7499 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 DEPTNO JOB ------------- ------------- --------- JONES 20 MANAGER FORD 20 ANALYST SMITH 20 CLERK SCOTT 20 ANALYST ADAMS 20 CLERK

6.5.Display the employee name and salary of all employees who report to King.

Página 18

Page 19: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

ENAME SAL ------------ -------- BLAKE 2850 CLARK 2450 JONES 2975

6.6.Display the department number, name, and job for all employees in the Sales department.

DEPTNO ENAME JOB ------------- ------------- --------- 30 BLAKE MANAGER 30 MARTIN SALESMAN 30 ALLEN SALESMAN 30 TURNER SALESMAN 30 JAMES CLERK 30 WARD SALESMAN 6 rows selected.

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 ENAME SAL ------------ ------------ ------- 7566 JONES 2975 7788 SCOTT 3000 7902 FORD 3000 7698 BLAKE 2850

TEMA 7. SUBCONSULTAS CON MÚLTIPLES COLUMNAS. TTEEMMAA 77.. SSUUBBCCOONNSSUULLTTAASS CCOONN MMÚÚLLTTIIPPLLEESS CCOOLLUUMMNNAASS..

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 DEPTNO SAL ------------ ------------- -------- MARTIN 30 1250 WARD 30 1250

Página 19

Page 20: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

TURNER 30 1500 ALLEN 30 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 DNAME SAL ------------- ---------------- ------ SMITH RESEARCH 800 ADAMS RESEARCH 1100 JONES RESEARCH 2975 FORD RESEARCH 3000 SCOTT RESEARCH 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 HIREDATE SAL ------------- ---------------- ---------- FORD 03-DEC-81 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.

TEMA 8. SALIDA DE DATOS A MEDIDA. TTEEMMAA 88.. SSAALLIIDDAA DDEE DDAATTOOSS AA MMEEDDIIDDAA..

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

Page 21: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

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 DEPARTMENT NAME ----------------- ------------------- ------------------------------ JONES MANAGER RESEARCH FORD ANALYST RESEARCH SMITH CLERK RESEARCH SCOTT ANALYST RESEARCH ADAMS CLERK 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 ANNUAL NAME NAME DATE SALARY SALARY ------------- -------------- ------------------ ------------- ------------- SALES BLAKE 01-MAY-81 $2,850.00 $34,200.00 MARTIN 28-SEP-81 $1,250.00 $15,000.00 ALLEN 20-FEB-81 $1,600.00 $19,200.00 TURNER 08-SEP-81 $1,500.00 $18,000.00

Página 21

Page 22: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

JAMES 03-DEC-81 $950.00 $11,400.00 WARD 22-FEB-81 $1,250.00 $15,000.00

TEMA 9. MANIPULACIÓN DE DATOS. TTEEMMAA 99.. MMAANNIIPPUULLAACCIIÓÓNN DDEE DDAATTOOSS..

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 FIRST_NAME USERID SALARY ----- ------------------ ------------------- ------------ ------------- 1 Patel Ralph rpatel 795 2 Dancs Betty bdancs 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

Page 23: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

script you created. 9.8.Confirm your additions to the table.

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

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 SALARY ------------------ ------------ Patel 1000 Dancs 1000 Biri 1100 Newman 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 LAST_NAME FIRST_NAME USERID SALARY ------ ------------------- -------------------- ------------ -------------

1 Patel Ralph rpatel 1000 3 Drexler Ben bbiri 1100 4 Newman Chad cnewman 1000 5 Ropeburn Audry aropebur 1500

Página 23

Page 24: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

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 USERID SALARY --- ------------------ ------------------- --------- ------ 1 Patel Ralph rpatel 795 3 Biri Ben bbiri 1100 4 Newman Chad cnewman 750 5 Ropeburn Audry aropebur 1500

9.23.Make the data addition permanent.

TEMA 10. CREANDO Y MANEJANDO TABLAS. TTEEMMAA 1100.. CCRREEAANNDDOO YY MMAANNEEJJAANNDDOO TTAABBLLAASS.. 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.

Column Name Id Name

Key Type

Nulls/Unique

FK Table

FK Column

Datatype Number Varchar2

Length 7 25

Name Null? Type ---------- -------- ----------- ID NUMBER(7) NAME VARCHAR2(25)

10.2.Populate the DEPARTMENT table with data from the DEPT table. Include only columns that you need.

Página 24

Page 25: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

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.

Column Name ID LAST_NAME FIRST_NAME DEPT_ID

Key Type

Nulls/Unique

FK Table

FK Column

Datatype Number Varchar2 Varchar2 Number

Length 7 25 25 7

Name Null? Type ------------- -------- ------------ ID NUMBER(7) LAST_NAME VARCHAR2(25) FIRST_NAME VARCHAR2(25) DEPT_ID NUMBER(7)

10.4.Modify the EMPLOYEE table to allow for longer employee last names. Confirm your modification.

Name Null? Type ------------------- -------- ----------- ID NUMBER(7) LAST_NAME VARCHAR2(50) FIRST_NAME VARCHAR2(25) DEPT_ID 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

Page 26: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

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.

TEMA 11. INCLUYENDO CONSTRAINTS. TTEEMMAA 1111.. IINNCCLLUUYYEENNDDOO CCOONNSSTTRRAAIINNTTSS.. 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 C ----------------------- -- DEPARTMENT_ID_PK P EMPLOYEE_ID_PK P EMPLOYEE_DEPT_ID_FK 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 OBJECT_TYPE ------------------------ --------------------- DEPARTMENT TABLE DEPARTMENT_ID_PK INDEX EMPLOYEE TABLE EMPLOYEE_ID_PK INDEX

11.6.Modify the EMPLOYEE table. Add a SALARY column of NUMBER data type, precision 7.

Página 26

Page 27: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

TEMA 12. CREANDO VISTAAS. TTEEMMAA 1122.. CCRREEAANNDDOO VVIISSTTASS.. 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 DEPTNO ---------- ----------------- ------------- 7839 KING 10 7698 BLAKE 30 7782 CLARK 10 7566 JONES 20 7654 MARTIN 30 7499 ALLEN 30 7844 TURNER 30 7900 JAMES 30 7521 WARD 30 7902 FORD 20 7369 SMITH 20 7788 SCOTT 20 7876 ADAMS 20 7934 MILLER 10 14 rows selected.

12.3.Select the view_name and text from the data dictionary USER_VIEWS.

VIEW_NAME TEXT ----------- ---------------------------------------- EMP_VU 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 DEPTNO ----------------- -------------- KING 10 BLAKE 30 CLARK 10 JONES 20 MARTIN 30 14 rows selected.

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

Page 28: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

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 EMPLOYEE DEPARTMENT_ID

------------------- ----------------- -------------------------- 7566 JONES 20 7902 FORD 20 7369 SMITH 20 7788 SCOTT 20 7876 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.

TEMA 13. OTROS OBJETOS DE BASE DE DATOS. TTEEMMAA 1133.. OOTTRROOSS OOBBJJEETTOOSS DDEE BBAASSEE DDEE DDAATTOOSS.. 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

Page 29: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

EMPLOYEE table. Save the statement into a script named p13q5.sql.

INDEX_NAME TABLE_NAME UNIQUENES ------------------------------------- -------------------- ------------------ EMPLOYEE_DEPT_ID_IDX EMPLOYEE NONUNIQUE EMPLOYEE_ID_PK EMPLOYEE UNIQUE

TEMA 15. REPASO. TTEEMMAA 1155.. RREEPPAASSOO..

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

MEMBER_ID

LAST_ NAME

FIRST_NAME

ADDRESS CITY PHONE JOIN_ DATE

Key Type

PK

Null/ Unique

NN,U NN NN

Default Value

System Date

Data Type

Number Varchar2 Varchar2 Varchar2 Varchar2 Varchar2 Date

Length 10 25 25 100 30 15

b. Table name TITLE

Página 29

Page 30: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

Column_Name

TITLE_ID TITLE DESCRIPTION RATING CATEGORY RELEASE_ DATE

Key Type

PK

Null/ Unique

NN,U NN NN

Check G, PG, R, NC17, NR

DRAMA, COMEDY, ACTION, CHILD, SCIFI, DOCUMENTARY

Data Type

Number Varchar2 Varchar2 Varchar2 Varchar2 Date

Length 10 60 400 4 20

c. Table:TITLE-COPY

Column Name COPY_ID TITLE_ID STATUS

KeyType

PK PK,FK

Null/Unique

NN,U NN,U NN

Check AVAILABLE,DESTROYED,RENTED,RESERVED

Data Type Number Number Varchar2Length 10 10 15

d. Table name: RENTAL

Página 30

Page 31: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

ColumnName

BOOK_DATE

MEMBER_ID

COPY_ID

ACT_RET_DATE

EXP_RET_DATE

TITLE_ID

KeyType

PK PK,FK PK,FK PK,FK

DefaultValue

SystemDate

2 days

FK RefTable

member copy_id title_copy

FK RefCol

member_id title_id

DataType

Date Number Number Date Date Number

Length 10 10 10

e. Table name: RESERVATION

Column_Name

RES_DATE

MEMBER_ID

TITLE_ID

KeyType

PK PK,FK PK,FK

Null/Unique

NN,U NN,U NN

FK RefTable

MEMBER TITLE

FK RefColumn

member_id title_id

Data Type Date Number Number

Length 10 10

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 C TABLE_NAME ----------------------------------------------------- --- -------------- MEMBER_LAST_NAME_NN C MEMBER MEMBER_JOIN_DATE_NN C MEMBER MEMBER_MEMBER_ID_PK P MEMBER RENTAL_BOOK_DATE_COPY_TITLE_PK P RENTAL

Página 31

Page 32: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

RENTAL_MEMBER_ID_FK R RENTAL RENTAL_COPY_ID_TITLE_ID_FK R RENTAL RESERVATION_RESDATE_MEM_TIT_PK P RESERVATION RESERVATION_MEMBER_ID R RESERVATION RESERVATION_TITLE_ID R RESERVATION ... 18 rows selected.

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 INCREMENT_BY LAST_NUMBER ------------------------- ----------------------- ---------------------- TITLE_ID_SEQ 1 92 MEMBER_ID_SEQ 1 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

Page 33: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

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.

G CHILD 05-OCT-95

Alien Again Yet another installation of science fiction history. Can the heroine save the planet from the alien life form?

R SCIFI 19-MAY-95

The Glob A meteor crashes near a small American town and unleashed carnivorous goo in this classic.

NR SCIFI 12-AUG-95

My Day Off With a little luck and a lot of ingenuity, a teenager skips school for a day in New York

PG COMEDY 12-JUL-95

Miracles on Ice

A six-year-old has doubts about Santa Claus but she discovers that miracles really do exist.

PG DRAMA 12-SEP-95

Soda Gang After discovering a cache of drugs, a young couple find themselves pitted against a vicious gang.

NR ACTION 01-JUN-95

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.

FirstName

Last Name Address State Phone Join Date

Carmen Velasquez 283 King Street Seattle 206-899-6666 08-MAR-90LaDoris Ngao 5 Modrany Bratislava 586-355-8882 08-MAR-90Midori Nagayama 68 Via Centrale Sao Paolo 254-852-5764 17-JUN-91Mark Lewis 6921 King Way Lagos 63-559-7777 07-APR-90Audry Ropeburn 86 Chu Street Hong Kong 41-559-87 18-JAN-91Molly Urguhart 3035 Laurier Quebec 418-542-9988 18-JAN-91

Página 33

Page 34: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

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

Title Copy Number StatusWillie and Christmas Too 1 AvailableAlien 1 Available

2 RentedThe Glob 1 AvailableMy Day Off 1 Available

2 Available3 Rented

Miracles on Ice 1 AvailableSoda Gang 1 Available

d. Add the following rentals to the RENTAL table: Note: Title number may be different depending on sequence number.

Title Copy_number

Customer Date_Rented

Date_return_expected Date_returned

92 1 101 3 days ago 1 day ago 2 days ago93 2 101 1 day ago 1 day from now95 3 102 2 days ago Today97 1 106 4 days ago 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 COPY_ID STATUS EXP_RET_D ------------------------------ -------------- -------------- ------------------ Alien Again 1 AVAILABLE Alien Again 2 RENTED 05-NOV-97 Miracles on Ice 1 AVAILABLE My Day Off 1 AVAILABLE My Day Off 2 AVAILABLE My Day Off 3 RENTED 06-NOV-97 Soda Gang 1 AVAILABLE 04-NOV-97 The Glob 1 AVAILABLE Willie and Christmas Too 1 AVAILABLE 05-NOV-97 9 rows selected.

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

Page 35: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

“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 STATUS EXP_RET_D -------------------------------- ------------ -------------------- ---------------- Alien Again 1 AVAILABLE Alien Again 2 RENTED 05-NOV-97 Interstellar Wars 1 RENTED 08-NOV-97 Interstellar Wars 2 AVAILABLE Miracles on Ice 1 AVAILABLE My Day Off 1 AVAILABLE My Day Off 2 AVAILABLE My Day Off 3 RENTED 06-NOV-97 Soda Gang 1 AVAILABLE 04-NOV-97 The Glob 1 AVAILABLE Willie and Christmas Too 1 AVAILABLE 05-NOV-97 9 rows selected.

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 Null? Type ---------------------- ------------------ ----------------------- TITLE_ID NOT NULL NUMBER(10) TITLE NOT NULL VARCHAR2(60) DESCRIPTION NOT NULL VARCHAR2(400) RATING VARCHAR2(4) CATEGORY VARCHAR2(20) RELEASE_DATE DATE PRICE 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

Page 36: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

Title Price Willie and Christmas Too 25 Alien Again 35 The Glob 35 My Day Off 35 Miracles on Ice 98 Soda Gang 35 Interstellar Wars 29

c. Ensure that in the future all titles will contain a price value. Verify the constraint.

CONSTRAINT_NAME C SEARCH_CONDITIONS -------------------------------- ---- ------------------------------------- TITLE_PRICE_NN C 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 TITLE BOOK_DATE DURATION ----------------------- ------------------ ------------------------ -------- LaDoris Ngao The Glob 04-NOV-97 Molly Urguhart Miracles on Ice 02-NOV-97 2 Carmen Velasquez Willie and Christmas 03-NOV-97 1 Too Willie and Christmas 03-NOV-97 1 Too Alien Again 05-NOV-97

TEMA 16. DECLARACIÓN DE VARIABLES. TTEEMMAA 1166.. DDEECCLLAARRAACCIIÓÓNN DDEE VVAARRIIAABBLLEESS..

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

Page 37: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

v_id NUMBER(4);

b. DECLARE v_x, v_y, v_z VARCHAR2(10);

c. DECLARE v_birthdate DATE NOT NULL;

d. DECLARE v_in_stock BOOLEAN := 1;

e. 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. v_sum := $100,000 + $250,000; d. v_flag := TRUE; e. 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

Page 38: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

G_CHAR --------------------- 42 is the answer G_NÚMERO --------- 42

TEMA 17. ESCRIBIENDO MANDATOS EJECUTABLES. TTEEMMAA 1177.. EESSCCRRIIBBIIEENNDDOO MMAANNDDAATTOOSS EEJJEECCUUTTAABBLLEESS..

PL/SQL Block

DECLARE v_weight NUMBER(3) := 600; v_message VARCHAR2(255) := 'Product 10012'; BEGIN 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

Page 39: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

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 VARCHAR2(50) := 'Womansport'; v_credit_rating VARCHAR2(50) := 'EXCELLENT'; BEGIN DECLARE v_customer NUMBER(7) := 201; v_name VARCHAR2(25) := 'Unisports'; BEGIN v_customer v_name v_credit_rating END; v_customer 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

Page 40: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

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

TEMA 18.INTERACTUANDO CON ORACLE SERVER. TTEEMMAA 1188..IINNTTEERRAACCTTUUAANNDDOO CCOONN OORRAACCLLEE SSEERRVVEERR..

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

Page 41: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

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 DNAME LOC ----------------- ---------------------- ---------

50 EDUCATION 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 DNAME LOC ------ --------- --------------- 50 EDUCATION 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

Page 42: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

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

TEMA 19.ESTRUCTURAS DE CONTROL. TTEEMMAA 1199..EESSTTRRUUCCTTUURRAASS DDEE CCOONNTTRROOLL.. 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

Page 43: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

/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 ENAME SAL COMM ----------- ----------- -------- --------- 8000 DOE 0 7499 ALLEN 1600 320 7934 MILLER 1300 195 7369 SMITH 800 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.44..AAdddd aa nneeww ccoolluummnn ttoo tthhee EEMMPP ttaabbllee ffoorr ssttoorriinngg aasstteerriisskk ((**)).. 19.55..CCrreeaattee aa PPLL//SSQQLL bblloocckk tthhaatt rreewwaarrddss aann eemmppllooyyeeee bbyy aappppeennddiinngg aann aasstteerriisskk iinn tthhee SSTTAARRSS ccoolluummnn ffoorr eevveerryy $$110000 ooff tthhee eemmppllooyyeeee''ss ssaallaarryy.. RRoouunndd tthhee eemmppllooyyeeee’’ss ssaallaarryy ttoo tthhee nneeaarreesstt wwhhoollee nnuummbbeerr.. SSaavvee yyoouurr PPLL//SSQQLL bblloocckk ttoo aa ffiillee ccaalllleedd pp1199qq55..ssqqll..

Página 43

Page 44: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

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 *************

TEMA 20.TRABAJANDO CON TIPOS COMPUESTOS. TTEEMMAA 2200..TTRRAABBAAJJAANNDDOO CCOONN TTIIPPOOSS CCOOMMPPUUEESSTTOOSS..

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 SALARY --------------- --------- MILLER 1300

Página 44

Page 45: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

Please enter the employee number: 7876 PL/SQL procedure successfully completed.

NAME SALARY --------------- --------- ADAMS 1100

TEMA 21.CURRSORES. TTEEMMAA 2211..CCUURSSOORREESS..

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

Page 46: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

KING 5000 FORD 3000 SCOTT 3000 JONES 2975

TEMA 22.CURRSORES EXPLÍCITOS AVANZADOS. TTEEMMAA 2222..CCUURSSOORREESS EEXXPPLLÍÍCCIITTOOSS AAVVAANNZZAADDOOSS..

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 SAL STARS --------------- ------ --------------------- 8000 7900 950 ********** 7844 1500 ***************

TEMA 23.MANEJO DE EXCEPCIONES. TTEEMMAA 2233..MMAANNEEJJOO DDEE EEXXCCEEPPCCIIOONNEESS..

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

Page 47: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

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

Page 48: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

There are no employee salary between 5900 and 6100

TEMA 24.OPERADORESS DE CONJUNTOS. TTEEMMAA 2244..OOPPEERRAADDOORREES DDEE CCOONNJJUUNNTTOOSS.. 24.1.Display the department that has no employees. DEPTNO DNAME --------- -------------- 40 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 PRODID STDPRICE ACTPRICE ----------------- --------- ---------------- ----------------- 10% off 100870 2.4 2.16 10% off 100870 2.8 2.52 10% off 100871 4.8 4.32 10% off 100871 5.6 5.04 10% off 102130 3.4 3.06 10% off 200376 2.4 2.16 10% off 200380 4 3.6 15% off 100860 30 25.5 15% off 101860 24 20.4 15% off 101863 12.5 10.625 20% off 100860 32 25.6 20% off 100860 35 28 20% off 100861 39 31.2 no disc 100861 42 42 no disc 100861 45 45 no disc 100890 54 54 no disc 100890 58 58

24.4.Produce a list of jobs for departments 10, 30, and 20 in that order. Display job and department number.

JOB DEPTNO --------- -------- CLERK 10 MANAGER 10

Página 48

Page 49: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

PRESIDENT 10 CLERK 30 MANAGER 30 SALESMAN 30 ANALYST 20 CLERK 20 MANAGER 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

TEMA 25. SUBCONSULTAAS COR ELACIONADAS. TTEEMMAA 2255.. SSUUBBCCOONNSSUULLTTASS CCOORRRRREELLAACCIIOONNAADDAASS.. 25.1.Write a query to display the top three earners in the EMP table. Display their names and salaries.

ENAME SAL ---------- --------- KING 5000 FORD 3000 SCOTT 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

Page 50: Relación de Ejercicios Prácticos - uco.es · BASES DE DATOS Ingeniería Técnica Informática ... Relación de Ejercicios Prácticos TTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO

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 SALARY DEPTNO DEPT_AVG ------------- ------------- -------------- ----------------- ALLEN 1600 30 1566.6667 BLAKE 2850 30 1566.6667 JONES 2975 20 2175 FORD 3000 20 2175 SCOTT 3000 20 2175 KING 5000 10 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