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 em ployee number for each employee, w ith employee number appearing first. Save your SQL statement to a file named p1q7.sql. Página 1
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
TEMA 1. MANDATO SELECT BÁSICOTTEEMMAA 11.. MMAANNDDAATTOO SSEELLEECCTT BBÁÁSSIICCOO 1.1.Initiate a SQL*Plus session using the user ID and password provided by theinstructor.
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 SalaryFROM 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,enamesalary x 12 ANNUAL SALARYFROM 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)
Name Null? Type----------------- --------------- -------------EMPNO NOT NULL NUMBER(4)ENAME VARCHAR2(10)
JOB VARCHAR2(9)MGR NUMBER(4)HIREDATE DATESAL 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-817698 BLAKE MANAGER 01-MAY-817782 CLARK MANAGER 09-JUN-817566 JONES MANAGER 02-APR-817654 MARTIN SALESMAN 28-SEP-817499 ALLEN SALESMAN 20-FEB-817844 TURNER SALESMAN 08-SEP-817900 JAMES CLERK 03-DEC-817521 WARD SALESMAN 22-FEB-817902 FORD ANALYST 03-DEC-81
7369 SMITH CLERK 17-DEC-807788 SCOTT ANALYST 09-DEC-827876 ADAMS CLERK 12-JAN-837934 MILLER CLERK 23-JAN-82
14 rows selected.
1.9.Create a query to display unique jobs from the EMP table. JOB-----------
ANALYSTCLERK MANAGER PRESIDENTSALESMAN
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
TEMA 2.RESTTRIC IIÓN Y ORDENACIÓN DE LOS DATOSRECUPERADOS.
TTEEMMAA 22..R R EESSTR R IICCCCCIÓÓNN YY OOR R DDEENNAACCIIÓÓNN DDEE LLOOSS DDAATTOOSS R R EECCUUPPEER R AADDOOSS..
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 5000JONES 2975FORD 3000SCOTT 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 whosesalary is not in the range of $1500 and $2850. Resave your SQL statement to afile named p2q3.sql . Rerun your query.
2.4.Display the employee name, job and start date of employees hired betweenFebruary 20, 1981, and May 1, 1981. Order the query in ascending order of startdate.
MARTIN 30ALLEN 30TURNER 30JAMES 30WARD 30MILLER 109 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 . Rerunyour query.
2.13.Modify p2q6.sql to display the name, salary, and commission for allemployees whose commission amount is greater than their salary increased by10%. 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 SOLAFILA.
TTEEMMAA 33.. FFUUNNCCIIOONNEESS DDEE SSQQLL QQUUEE AACCTTÚÚAANN SSOOBBR R EE 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 SQLstatement to a file named p3q2.sql .
3.3.Run your query in the file p3q2.sql .
EMPNO ENAME SAL New Salary----------- ------------ ----- --------------7839 KING 5000 57507698 BLAKE 2850 32787782 CLARK 2450 28187566 JONES 2975 34217654 MARTIN 1250 14387499 ALLEN 1600 18407844 TURNER 1500 17257900 JAMES 950 10937521 WARD 1250 14387902 FORD 3000 34507369 SMITH 800 9207788 SCOTT 3000 34507876 ADAMS 1100 12657934 MILLER 1300 1495
14 rows selected.
3.4.Modify your query p3q2.sql to add an additional column that will subtractthe old salary from the new salary. Label the column Increase. Rerun your
query. EMPNO ENAME SAL New Salary Increase----------- ------------ ------- ---------- --------
7839 KING 5000 5750 7507698 BLAKE 2850 3278 4287782 CLARK 2450 2818 3687566 JONES 2975 3421 446
3.5.Display the employee’s name, hire date, and salary review date, which is thefirst Monday after six months of service. Label the column REVIEW. Formatthe 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, 1982BLAKE 01-MAY-81 Monday, the Second of November, 1981CLARK 09-JUN-81 Monday, the Fourteenth of December, 1981JONES 02-APR-81 Monday, the Fifth of October, 1981MARTIN 28-SEP-81 Monday, the Twenty-Ninth of March, 1982ALLEN 20-FEB-81 Monday, the Twenty-Fourth of August, 1981TURNER 08-SEP-81 Monday, the Fifteenth of March, 1982JAMES 03-DEC-81 Monday, the Seventh of June, 1982WARD 22-FEB-81 Monday, the Twenty-Fourth of August, 1981
FORD 03-DEC-81 Monday, the Seventh of June, 1982SMITH 17-DEC-80 Monday, the Twenty-Second of June, 1981SCOTT 09-DEC-82 Monday, the Thirteenth of June, 1983ADAMS 12-JAN-83 Monday, the Eighteenth of July, 1983MILLER 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 columnMONTHS_WORKED. Order your results by the number of months employed.Round the number of months up to the closest whole number.
3.7.Write a query that produces the following for each employee:
<employee name> earns <salary> monthly but wants <3 times salary>. Label thecolumn 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.00TURNER 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 thesalary to be 15 characters long, left-padded with $. Label the column SALARY.
3.9.Write a query that will display the employee's name with the first lettercapitalized and all other letters lowercase and the length of their name, for allemployees whose name starts with J , A, or M . Give each column an appropriatelabel.
3.10.Display the name, hire date, and day of the week on which the employeestarted. 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 commissionamount. If the employee does not earn commission, put “No Commission.” Labelthe column COMM.
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
MMaannaaggeerr,, aanndd MMggrr##,, rreessppeeccttiivveellyy.. SSaavvee yyoouurr SSQQLL ssttaatteemmeenntt ttoo aa f f iillee ccaalllleedd p p44qq6 6 . .ssqql l ..
Employee Emp# Manager Mgr#-------------- --------- ------------ ---------SCOTT 7788 JONES 7566FORD 7902 JONES 7566ALLEN 7499 BLAKE 7698WARD 7521 BLAKE 7698JAMES 7900 BLAKE 7698TURNER 7844 BLAKE 7698MARTIN 7654 BLAKE 7698MILLER 7934 CLARK 7782ADAMS 7876 SCOTT 7788
JONES 7566 KING 7839CLARK 7782 KING 7839BLAKE 7698 KING 7839SMITH 7369 FORD 7902
13 rows selected.
4.7.Modify p4q6.sql to display all employees including King, who has nomanager. Resave as p4q7.sql . Run p4q7.sql .
Employee Emp# Manager Mgr#------------- ---------- ------------ ---------SCOTT 7788 JONES 7566FORD 7902 JONES 7566ALLEN 7499 BLAKE 7698
WARD 7521 BLAKE 7698JAMES 7900 BLAKE 7698TURNER 7844 BLAKE 7698MARTIN 7654 BLAKE 7698MILLER 7934 CLARK 7782ADAMS 7876 SCOTT 7788JONES 7566 KING 7839CLARK 7782 KING 7839BLAKE 7698 KING 7839SMITH 7369 FORD 7902KING 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 KING10 CLARK MILLER 10 KING CLARK 10 KING MILLER 10 MILLER CLARK 10 MILLER KING20 ADAMS FORD20 ADAMS JONES20 ADAMS SCOTT20 ADAMS SMITH20 FORD ADAMS
JONES 02-APR-81 KING 17-NOV-81CLARK 09-JUN-81 KING 17-NOV-81BLAKE 01-MAY-81 KING 17-NOV-81SMITH 17-DEC-80 FORD 03-DEC-816 rows selected.
4.12.Create a query that displays the employees name and the amount of thesalaries of the employees are indicated through asterisks. Each asterisk signifiesa hundred dollars. Sort the data in descending order of salary. Label the columnEMPLOYEE_AND_THEIR_SALARIES.
MILLER ************MARTIN ***********WARD ***********ADAMS **********JAMES ********SMITH *******14 rows selected.
TEMA 5. FUNCIONES DE AGGREGACIÓN.TTEEMMAA 55.. FFUUNNCCIIOONNEESS DDEE AAGR R EEGGAACCIIÓÓ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. Labelthe columns Maximum, Minimum, Sum, and Average, respectively. Round yourresults to the decimal position. Save your SQL statement in a file called p5q4.sql .
Maximum Minimum Sum Average------------- ------------- - -------- ------------
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 lowestsalaries. Label the column DIFFERENCE.
DIFFERENCE---------------- --
4200
5.9.Display the manager number and the salary of the lowest paid employee forthat manager. Exclude anyone where the manager id is not known. Excludeany groups where the minimum salary is less than $1000. Sort the output indescending order of salary.
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. Labelthe columns’ dname, loc, Number of People, and Salary, respectively.
DNAME LOC Number of People Salary--------------------- ------------------ ----------------------- --------ACCOUNTING NEW YORK 3 2916.67RESEARCH DALLAS 5 2175SALES CHICAGO 6 1566.67
5.11.Create a query that will display the total number of employees and of thattotal the number who were hired in 1980, 1981, 1982, and 1983. Give appropriatecolumn 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 upondepartment number and the total salary for that job for all departments, givingeach column an appropriate heading.
6.2.Create a query to display the employee number and name for all employeeswho earn more than the average salary. Sort the results in descending order of
30 BLAKE MANAGER 30 MARTIN SALESMAN30 ALLEN SALESMAN
30 TURNER SALESMAN30 JAMES CLERK 30 WARD SALESMAN
6 rows selected.
6.7.Modify p6q3.sql to display the employee number, name, and salary for allemployees who earn more than the average salary and who work in adepartment with any employee with a T in their name. Resave as p6q7.sql . Rerunyour query.
EMPNO ENAME SAL------------ ------------ -------7566 JONES 29757788 SCOTT 30007902 FORD 30007698 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 anyemployee whose department number and salary matches both the departmentnumber and salary of any employee who earns a commission.
7.2.Display the name, department name, and salary of any employee whosesalary and commission matches both the salary and commission of any employeelocated in Dallas.
ENAME DNAME SAL------------- ---------------- ------SMITH RESEARCH 800ADAMS RESEARCH 1100JONES RESEARCH 2975FORD RESEARCH 3000SCOTT RESEARCH 3000
7.3.Create a query to display the name, hire date, and salary for all employeeswho have both the same salary and commission as Scott.
ALLEN SALESMAN 1600TURNER SALESMAN 15008 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/False8.3.Write a script file to display the employee name, job, and hire date for allemployees who started between a given range. Concatenate the name and job
together, separated by a space and comma and label the column Employees.Prompt the user for the two ranges using the ACCEPT command. Use theformat MM/DD/YY. Save the script file as p8q3.sql .
Please enter the low date range ('MM/DD/YY'): 01/01/81Please enter the high date range ('MM/DD/YY'): 01/01/82EMPLOYEES HIREDATE----------------- ---------------KING, PRESIDENT 17-NOV-81BLAKE, MANAGER 01-MAY-81CLARK, MANAGER 09-JUN-81JONES, MANAGER 02-APR-81MARTIN, SALESMAN 28-SEP-81ALLEN, SALESMAN 20-FEB-81TURNER, SALESMAN 08-SEP-81JAMES, CLERK 03-DEC-81WARD, SALESMAN 22-FEB-81FORD, ANALYST 03-DEC-8110 rows selected.
8.4.Write a script to display the employee name, job, and department name. Thesearch condition should allow for case_insensitive name searches. Save the scriptfile as p8q4.sql .
Please enter the location name: DallasEMPLOYEE NAME JOB DEPARTMENT NAME----------------- ------------------- ------------------------------JONES MANAGER RESEARCHFORD ANALYST RESEARCHSMITH CLERK RESEARCHSCOTT ANALYST RESEARCHADAMS CLERK RESEARCH
8.5.Modify p8q4.sql to create a report containing the department name, employeename, hire date, salary and each employees annual salary for all employees in agiven location. Prompt the user for the location. Label the columnsDEPARTMENT NAME, EMPLOYEE NAME, START DATE, SALARY andANNUAL SALARY, placing the labels on multiple lines. Resave the script as
p8q5.sql . Please enter the location name: ChicagoDEPARTMENT EMPLOYEE START ANNUAL
NAME NAME DATE SALARY SALARY------------- -------------- ------------------ ------------- -------------
JAMES 03-DEC-81 $950.00 $11,400.00WARD 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 columnnames.
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 databelow. 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 datafrom 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
9.6. Create a script named loademp.sql to load rows into the MY_EMPLOYEEtable interactively. Prompt the user for the employee’s first name, last name, andsalary. Concatenate the first letter of the first name and the first sevencharacters of the last name to produce the userid. 9.7.Populate the table with the next two rows of sample data by running the
ID LAST_NAME FIRST_NAME USERID SALARY----- ------------------ ------------------- ------------ -------------1 Patel Ralph rpatel 7952 Dancs Betty bdancs 8603 Biri Ben bbiri 11004 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.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 earlierINSERT operation.
9.22. Confirm that the new row is still intact.
ID LAST_NAME FIRST_NAME USERID SALARY--- ------------------ ------------------- --------- ------1 Patel Ralph rpatel 7953 Biri Ben bbiri 1100
4 Newman Chad cnewman 7505 Ropeburn Audry aropebur 1500
9.23.Make the data addition permanent.
TEMA 10. CREANDO Y MANEJANDO TABLAS.TTEEMMAA 1100.. CCR R EEAANNDDOO YY MMAANNEEJJAANNDDOO TTAABBLLAASS.. 10.1.Create the DEPARTMENT table based on the table instance chart givenbelow. Enter the syntax in a script called p10q1.sql , then execute the script tocreate 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. Includeonly columns that you need.
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 createthe 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)
10.6.Create the EMPLOYEE2 table based on the structure of the EMP table,include only the EMPNO, ENAME and DEPTNO columns. Name the columnsin 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 definitionsdescribing the tables. Confirm your additions in the data dictionary.
TEMA 11. INCLUYENDO CONSTRAINTS.TTEEMMAA 1111.. IINNCCLLUUYYEENNDDOO CCOONNSSTTR R AAIINNTTSS.. 11.1.Add a table level PRIMARY KEY constraint to the EMPLOYEE tableusing the ID column. The constraint should be enabled at creation. 11.2.Create a PRIMARY KEY constraint on the DEPARTMENT table using theID column. The constraint should be enabled at creation.
11.3.Add a foreign key reference on the EMPLOYEE table that will ensure thatthe employee is not assigned to a nonexistent department.
11.4.Confirm that the constraints were added by queryingUSER_CONSTRAINTS. Note the types and names of the constraints. Saveyour statement text in a file called p11q4.sql .
CONSTRAINT_NAME C
----------------------- --DEPARTMENT_ID_PK PEMPLOYEE_ID_PK PEMPLOYEE_DEPT_ID_FK R
11.5.Display the object names and types from the USER_OBJECTS datadictionary view EMPLOYEE and DEPARTMENT tables. You may want toformat the columns for readability. Notice that the new tables and a new indexwere created.
OBJECT_NAME OBJECT_TYPE------------------------ ---------------------DEPARTMENT TABLEDEPARTMENT_ID_PK INDEXEMPLOYEE TABLEEMPLOYEE_ID_PK INDEX
11.6.Modify the EMPLOYEE table. Add a SALARY column of NUMBER datatype, precision 7.
TEMA 12. CREANDO VISTAAS.TTEEMMAA 1122.. CCR R EEAANNDDOO VVIISSTTASS.. 12.1.Create a view called EMP_VU based on the employee number, employeename, and department number from the EMP table. Change the heading for theemployee name to EMPLOYEE. 12.2. Display the content’s of the EMP_VU view.
EMPNO EMPLOYEE DEPTNO---------- ----------------- -------------7839 KING 107698 BLAKE 307782 CLARK 107566 JONES 207654 MARTIN 307499 ALLEN 30
7844 TURNER 307900 JAMES 307521 WARD 307902 FORD 207369 SMITH 207788 SCOTT 207876 ADAMS 207934 MILLER 10
14 rows selected.
12.3.Select the view_name and text from the data dictionary USER_VIEWS.
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, andDEPARTMENT_ID. Do not allow an employee to be reassigned to another
12.8.Create a view called SALARY_VU based on the employee name,department name, salary and salary grade for all employees. Label the columnsEmployee, Department, Salary and Grade, respectively.
TEMA 13. OTROS OBJETOS DE BASE DE DATOS.TTEEMMAA 1133.. OOTTR R OOSS OOBBJJEETTOOSS DDEE BBAASSEE DDEE DDAATTOOSS..
13.1.Create a sequence to be used with the DEPARTMENT table’s primary keycolumn. The sequence should start at 60 and have a maximum value of 200. Haveyour 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 thescript p13q2.sql . Execute your script.
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 theID column. Create a customized prompt to enter the department name. Executeyour script. Add two departments named Education and Administration.Confirm your additions.
13.4.Create a non-unique index on the FOREIGN KEY column in theEMPLOYEE table.
13.5.Display the indexes and uniqueness that exist in the data dictionary for the
TEMA 15. REPASO. TTEEMMAA 1155.. R R EEPPAASSOO.. 15.1.Create the tables based on the table instance charts below. Choose theappropriate 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
KeyType
PK
Null/Unique
NN,U NN NN
DefaultValue
SystemDate
DataType
Number Varchar2 Varchar2 Varchar2 Varchar2 Varchar2 Date
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
RENTAL_MEMBER_ID_FK R RENTALRENTAL_COPY_ID_TITLE_ID_FK R RENTALRESERVATION_RESDATE_MEM_TIT_PK P RESERVATIONRESERVATION_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 andthe TITLE table. a. Member number for the MEMBER table: start with 101; do not allowcaching of the values. Name the sequence member_id_seq.
b. Title number for the TITLE table: start with 92; no caching. Name thesequence title_id_seq.
c Verify the existence of the sequences in the data dictionary.
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 identifyeach title. Remember that single quotation marks in a character field must bespecially handled. Verify your additions.
TITLE------------------------Willie and Christmas TooAlien AgainThe GlobMy Day Off Miracles on IceSoda Gang6 rows selected.
All of Willie’s friends madea Christmas list for Santa, butWillie has yet to add his own
wish list.
G CHILD 05-OCT-95
Alien Again Yet another installation of science fiction history. Canthe heroine save the planetfrom the alien life form?
R SCIFI 19-MAY-95
The Glob A meteor crashes near asmall American town andunleashed carnivorous goo inthis 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 onIce
A six-year-old has doubtsabout Santa Claus but shediscovers that miracles reallydo exist.
PG DRAMA 12-SEP-95
Soda Gang After discovering a cache of drugs, a young couple findthemselves pitted against avicious gang.
NR ACTION 01-JUN-95
b. Add data to the MEMBER table. Write a script named p15q4b.sql to promptusers for the information. Execute the script. Be sure to use the sequence to addthe member numbers.
FirstName
Last Name Address State Phone Join Date
Carmen 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
c. Add the following movie copies in the TITLE_COPY table:
Title Copy Number StatusWillie and Christmas Too 1 Available
Alien 1 Available2 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 ago
93 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 theavailability of each copy and its expected return date if rented. Query all rowsfrom the view.
TITLE COPY_ID STATUS EXP_RET_D------------------------------ -------------- -------------- ------------------Alien Again 1 AVAILABLEAlien Again 2 RENTED 05-NOV-97Miracles on Ice 1 AVAILABLE
My Day Off 1 AVAILABLEMy Day Off 2 AVAILABLE My Day Off 3 RENTED 06-NOV-97Soda Gang 1 AVAILABLE 04-NOV-97The Glob 1 AVAILABLEWillie and Christmas Too 1 AVAILABLE 05-NOV-979 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 andclassified as a Sci-fi movie. The release date is 07-JUL-77. The description is
“Futuristic interstellar action movie. Can the rebels save the humans from theevil Empire?” Be sure to add a title copy record for two copies.
b. Enter two reservations. One reservation is for Carmen Velasquez, who wantsto 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 therental was recorded by using the view you created.
TITLE COPY_ID STATUS EXP_RET_D-------------------------------- ------------ -------------------- ----------------Alien Again 1 AVAILABLEAlien Again 2 RENTED 05-NOV-97
Interstellar Wars 1 RENTED 08-NOV-97Interstellar Wars 2 AVAILABLEMiracles on Ice 1 AVAILABLEMy Day Off 1 AVAILABLEMy Day Off 2 AVAILABLEMy Day Off 3 RENTED 06-NOV-97Soda Gang 1 AVAILABLE 04-NOV-97The Glob 1 AVAILABLEWillie and Christmas Too 1 AVAILABLE 05-NOV-979 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 thevideo. The column should have a total length of eight digits and two decimalplaces. 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 DATEPRICE NUMBER(8,2)
b. Create a script named p15q7b.sql to update each video with a price accordingto the following list. Note: Have the title id numbers available for this exercise.
Title PriceWillie and Christmas Too 25Alien Again 35The Glob 35
My Day Off 35Miracles on Ice 98
Soda Gang 35Interstellar Wars 29
c. Ensure that in the future all titles will contain a price value. Verify theconstraint.
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 containeach 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-97Molly Urguhart Miracles on Ice 02-NOV-97 2Carmen Velasquez Willie and Christmas 03-NOV-97 1
TooWillie and Christmas 03-NOV-97 1TooAlien Again 05-NOV-97
TEMA 16. DECLARACIÓN DE VARIABLES.TTEEMMAA 1166.. DDEECCLLAAR R AACCIIÓÓNN DDEE VVAAR R IIAABBLLEESS.. Declare variables. 16.1.Evaluate each of the following declarations. Determine which of them are
e. DECLARETYPE 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 theresulting 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 thesePL/SQL variables to SQL*Plus host variables and print the results of thePL/SQL variables to the screen. Execute your PL/SQL block. Save your PL/SQLblock 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
17.2.Suppose you embed a subblock within a block, as shown on the previouspage. You declare two variables, V_CUSTOMER and V_CREDIT_RATING, inthe 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
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 throughSQL*Plus substitution variables. The first number should be divided by thesecond number and have the second number added to the result. The resultshould be written to a PL/SQL variable and printed to the screen.
Please enter the first number: 2Please 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/SQLblock through SQL*Plus substitution variables and the bonus needs to beconverted from a whole number to a decimal (for example, 15 to .15). If thesalary is null, set it to zero before computing the total compensation. Execute thePL/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: 50000Please enter the bonus percentage: 10PL/SQL procedure successfully completed.G_TOTAL--------------55000
TEMA 18.INTERACTUANDO CON ORACLE SERVER.TTEEMMAA 1188..IINNTTEER R AACCTTUUAANNDDOO CCOONN OOR R AACCLLEE SSEER R VVEER R .. 18.1.Create a PL/SQL block that selects the maximum department number inthe 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.
TEMA 19.ESTRUCTURAS DE CONTROL.TTEEMMAA 1199..EESSTTR R UUCCTTUUR R AASS DDEE CCOONNTTR R OOLL.. 19.1.Run the script/home/db/InformaciónGeneral/practicasdb2000/tema19/lab19_1.sql to create theMESSAGES table. Write a PL/SQL block to insert numbers into theMESSAGES 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
-----------------1234579
10
19.2.Create a PL/SQL block that computes the commission amount for a givenemployee based on the employee’s salary.
/home/db/InformaciónGeneral/practicasdb2000/tema19/lab19_2.sql to insert anew 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 theemployee to 10% of the salary.
d. If the employee’s salary is between $1,000 and $1,500, set the commissionamount for the employee to 15% of the salary.
e. If the employee’s salary exceeds $1,500, set the commission amount for theemployee to 20% of the salary.
f. If the employee’s salary is NULL, set the commission amount for the employeeto 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 07499 ALLEN 1600 3207934 MILLER 1300 1957369 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 f f oorr ssttoorriinngg aasstteerriissk k ((**)).. 19.55..CCrreeaattee aa PPLL//SSQQLL bblloocck k tthhaatt rreewwaarrddss aann eemmppllooyyeeee bbyy aappppeennddiinngg aann aasstteerriissk k iinn tthhee SSTTAAR R SS ccoolluummnn f f oorr eevveerryy $$110000 oof f tthhee eemmppllooyyeeee''ss ssaallaarryy.. R R oouunndd tthhee eemmppllooyyeeee’’ss ssaallaarryy ttoo tthhee nneeaarreesstt wwhhoollee nnuummbbeerr.. SSaavvee yyoouurr PPLL//SSQQLL bblloocck k ttoo aa f f iillee ccaalllleedd p p1199qq55 . .ssqql l . .
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. Forexample, if the employee has a salary amount of $800, the string of asterisksshould 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 whohas a salary.
Please enter the employee number: 7934PL/SQL procedure successfully completed.Please enter the employee number: 8000
TEMA 20.TRABAJANDO CON TIPOS COMPUESTOS.TTEEMMAA 2200..TTR R AABBAAJJAANNDDOO CCOONN TTIIPPOOSS CCOOMMPPUUEESSTTOOSS.. 20.1.Run the script/home/db/InformaciónGeneral/practicasdb2000/tema20/lab20_1.sql to create anew table for storing employees and their salaries.
20.2.Write a PL/SQL block to retrieve the name and salary of a given employeefrom the EMP table based on the employee’s number, incorporate PL/SQLtables.
a. Declare two PL/SQL tables, ENAME_TABLE and SAL_TABLE, totemporarily store the names and salaries.
b. As each name and salary is retrieved within the loop, store them in thePL/SQL tables.
c. Outside the loop, transfer the names and salaries from the PL/SQL tables intothe TOP_DOGS table.
d. Empty the TOP_DOGS table and test the practice.
Please enter the employee number: 7934PL/SQL procedure successfully completed.
Please enter the employee number: 7876PL/SQL procedure successfully completed.
NAME SALARY--------------- ---------ADAMS 1100
TEMA 21.CUR R SORES.TTEEMMAA 2211..CCUURSSOOR R EESS.. 21.1.Create a PL/SQL block that determines the top employees with respect tosalaries. 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 thenumber of employees in the EMP table. Empty the TOP_DOGS table aftereach test.
Please enter the number of top money makers: 5
NAME SALARY----------- ------KING 5000FORD 3000SCOTT 3000JONES 2975BLAKE 2850
21.2.Consider the case where several employees have the same salary. If oneperson 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 bedisplayed.
c. Delete all rows from TOP_DOGS and test the practice.Please enter the number of top money makers: 2
NAME SALARY------------ -------------KING 5000FORD 3000SCOTT 3000 Please enter the number of top money makers: 3
TEMA 22.CUR R SORES EXPLÍCITOS AVANZADOS.TTEEMMAA 2222..CCUURSSOOR R EESS EEXXPPLLÍÍCCIITTOOSS AAVVAANNZZAADDOOSS..
22.1.Write a query to retrieve all the departments and the employees in eachdepartment. Insert the results in the MESSAGES table. Use a cursor to retrievethe department number and pass the department number to a cursor to retrievethe employees in that department.
RESULTS------------------------KING - Department 10CLARK - Department 10MILLER - Department 10JONES - Department 20FORD - Department 20SMITH - Department 20SCOTT - Department 20ADAMS - Department 20BLAKE - Department 30MARTIN - Department 30
ALLEN - Department 30TURNER - Department 30JAMES - Department 30WARD - Department 3014 rows selected.
22.2.Modify p19q5.sql to incorporate the FOR UPDATE and WHERECURRENT OF functionality in cursor processing.
appropriate exception handler and insert into the MESSAGES table, themessage “No employee with a salary of <salary>.”
c. If the salary entered returns only one row, insert into the MESSAGES tablethe employee’s name and the salary amount.
d. Handle any other exception with an appropriate exception handler and insertinto the MESSAGES table, the message “Some other error occurred.”
e. Test the block for a variety of test cases. RESULTS--------------------------------------------SMITH - 800More 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 thespecified department does not exist.
b. Execute the PL/SQL block by entering a department that does not exist.
Please enter the department number: 50Please enter the department location: HOUSTONPL/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 makeplus or minus $100 of the salary value entered.
a. If there is no employee within that salary range, print a message to the userindicating that is the case. Use an exception for this case.
b. If there are one or more employees within that range, the message shouldindicate how many employees are in that salary range.
c. Handle any other exception with an appropriate exception handler, themessage 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: 3000PL/SQL procedure successfully completed. G_MESSAGE----------------------------------------------------------There are 3 employee(s) with a salary between 2900 and 3100 Please enter the salary: 6000PL/SQL procedure successfully completed.
There are no employee salary between 5900 and 6100
TEMA 24.OPERADORESS DE CONJUNTOS.TTEEMMAA 2244..OOPPEER R AADDOOR R EES 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 wasfilled during the same period in 1982.
JOB---------
ANALYST
24.3.Write a compound query to produce a list of products showing discountpercentages, product id, and old and new actual price. Products under $10 arereduced by 10%, products between $10 and $30 are reduced by 15%, productsover $30 are reduced by 20%, and products over $40 are not reduced at all.
10% off 100870 2.8 2.5210% off 100871 4.8 4.3210% off 100871 5.6 5.0410% off 102130 3.4 3.0610% off 200376 2.4 2.1610% off 200380 4 3.615% off 100860 30 25.515% off 101860 24 20.415% off 101863 12.5 10.62520% off 100860 32 25.620% off 100860 35 28
24.5. List the department number for departments without the job titleANALYST .
DEPTNO------------
10
3040
24.6.List all job titles in department 10 and 20 that do not occur in bothdepartments.
JOB------------------ANALYSTPRESIDENT
TEMA 25. SUBCONSULTAAS COR ELACIONADAS.TTEEMMAA 2255.. SSUUBBCCOONNSSUULLTTASS CCOOR R R R R EELLAACCIIOONNAADDAASS.. 25.1.Write a query to display the top three earners in the EMP table. Displaytheir names and salaries.
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 salaryin their department. Display employee number, salary, department number,and the average salary for the department. Sort by average salary.