Practical Project Report

Size: px
Start display at page:

Download "Practical Project Report"

Transcription

1 Practical Project Report May 11, 2017 I. People: II. Roles: Effort in both coding PL/SQL and writing III. Introduction: The topic of my project is DB queries using Oracle PL/SQL. This is my first time to play Oracle PL/SQL. The purpose of this project is to explore and learn Oracle PL/SQL, and understand some issues related to the database. I wrote DB queries based on the Company database and used features of PL/SQL including conditional and sequential control, loops, exceptions, records and collections, cursors, dynamic SQL, and procedures, functions, packages and triggers for this project. IV. Description: For this project, I used Oracle Linux Server VM. The database on the VM is Oracle Database 12c Release 1 Enterprise Edition. I used Oracle SQL Developer, which is an integrated development environment (IDE) and a graphical user interface for working with SQL in Oracle databases. In addition, the Company Database from our textbook was used in this project. At the beginning, what is PL/SQL? This is the first question which appeared in my mind when I decided to choose this project. PL/SQL is the abbreviation for Procedural Language extensions to the Structured Query Language. We use SQL in the relational databases, but the SQL has some limitations. So, Oracle introduced PL/SQL in order to overcome some limitations of SQL. In addition, it offers people who would like to build mission-critical applications with the Oracle database a more complete programming solution. The program units of PL/SQL are compiled by the Oracle database server. Also they are stored inside the database. In addition, both PL/SQL and SQL at run-time would run within the same server process and bring optical efficiency. Oracle PL/SQL has several characteristics, which are a highly structured, readable and accessible; standard and portable for Oracle development; embedded; high-performance and highly integrated database language. PL/SQL has a tight integration with SQL, which is the one of the most significant aspects. For example, people do not need ODBC or JDBC to run SQL statements in their PL/SQL programs. Also, it can allow people to closely control which lines of program execute. The reason is that it has IF, CASE statements, different kinds of loops including the FOR loop, the WHILE loop and the simple loop and the GOTO statement which makes you unconditionally branch from one part of the program to another. In addition, it provides a powerful mechanism corresponding to raising and handling errors. Then, I would like to talk about what I used to write my queries. 1. Conditional and sequential control, loops, exceptions In PL/SQL, there are two kinds of control statements, which are conditional control statements and

2 sequential control statements. These control statements are like the control statements in other programming languages such as C++ and Java. They can be IF-THEN statement, IT-THEN-ELSE statements, IF-THEN-ELSIF statements and CASE STATEMNT. They can help direct the flow of execution via people s program according to a condition. In PL/SQL, there are three kinds of loops which I mentioned before. For the simple loop, it can be terminated when an EXIT statement is executed. When people are not sure how many times they want the loop to execute or they want the loop to run at least one time, they can choose to use this kind of loop. For the while loop, when people are not sure how many times they want the loop body to execute or they have a condition to terminate the loop, they can choose to use this kind of loop. However, they do not have to carry out the loop body at least once. For the numeric for loop, when they want to execute the loop body a fixed number of times and do not want to stop the looping prematurely, they can choose this kind of loop. For the cursor FOR loop, it is a shortcut to process explicit cursors. In this kind of loop, the open, fetch, exit, and close operation occur implicitly and the record is implicitly declared. In PL/SQL, there are two types of exceptions, which are the system exception and the user-defined exception. For the system exception, it is usually raised by the PL/SQL runtime engine when an error condition is detected by the runtime engine. For the user-defined exception, a user can create his or her own exceptions based on the need of his or her program. 2. Records and Collections A record is a composite data structure. In PL/SQL, people can easily create records according to their tables in the database, and then can access each columns via the fields of records. Also, using records in PL/SQL can have some benefits, which are data abstraction, aggregating operations and making code cleaner. In PL/SQL, there are three kinds of collections, which are Associative arrays, Nested tables and VARRAYs. For an Associative array, it has several characteristics which are one-dimensional, unbounded and sparse. The elements in this kind of array must have same data type. It is also a table containing a set of key-value pairs. The key can be either a string or an integer. For a Nested table, it is similar with one-dimensional array containing an arbitrary number of elements. However, the size of a nested table can increase dynamically. For a VARRY, it is a fixed-size sequential collection of elements with the same type. Every element in this kind of collection has an index which is associated with it, and the size of this kind of collection can be changed dynamically. 3. Cursors In PL/SQL, there are two types of cursors, which are implicit cursors and explicit cursors. What is a cursor? A cursor is a pointer to a memory area containing the results of a query which is run against one or more tables in the database. For implicit cursors, they are created automatically by the Oracle database no matter when an SQL statement is executed. For example, when a SELECT INTO statement is executed, it can return a single row from the database directly into a data structure of PL/SQL such as records. In addition, users cannot control an implicit cursor and the information in it. For explicit cursors, they are user-defined cursors. Users can have more controls and can explicitly perform every operation against the cursor. Usually, when people would like to get multiple rows from the tables by using SQL statements, they can choose to use explicit cursors. 4. Dynamic SQL If a SQL statement is constructed at runtime and then executed, this kind of SQL statement will be dynamic. In my project, I used EXECUTE IMMEDIATE statement to execute DDL statements in a PL/SQL block. With minimum of syntactic fuss, it will be easy for EXECUTE IMMEDIATE statements

3 to carry out dynamic SQL statements and PL/SQL blocks. 5. Procedures, functions, package In PL/SQL, a procedure does not return a value directly and is primarily used to perform an action. A procedure can have parameters or does not have to have parameters. It can also include executable statements and exceptions. A procedure call in PL/SQL is a standalone executable statement. A function in PL/SQL returns a single value and is primarily used to compute and return a value. A function call in PL/SQL can just exist as part of an executable statement. A powerful and significant element in PL/SQL is the package, which is a kind of structure where people can organize their programs and other PL/SQL elements such as different types, variables and cursors. In the specification of a package, it can list all the elements in that package. The implementation code about how to implement the package specification will be in a package body. Also, there are some benefits for packages. By using packages, people can easily enhance and maintain applications, improve total application performance, support build-in weakness and minimize the need of recompile code. 6. Triggers Triggers are named program units stored in the database and include event-condition-action rules. No matter when a certain type of event happens in the database, triggers check the conditions over the database. If the condition is true, a corresponding action will be executed automatically. Using triggers can move the logic monitoring the database from the applications into the database system. Also, triggers can enforce integrity constraints. Some constraint systems are limited, so people can use triggers to enforce more expressive integrity constrains. Also, when constraints are violated, triggers can do automatic repair for them by specifying the repair as the action portion of the trigger. For triggers on the Oracle database, people can use them to perform validation on changes which are made to tables, perform automate maintenance of the database and applying rules which consider the activity of acceptable database administration in a granular manner. In PL/SQL, there are five kinds of events to which trigger code can be attached. These events are Data Manipulation Language (DML) statements, Data Definition Language (DDL) statements, Database events, INSTEAD OF and Suspended statements. For events of DML and DDL statements, no matter when the DDL and DML are executed, the corresponding DML and DDL triggers will be fired. For database events, the corresponding triggers can be fired no matter when the database launch or is shut down or no matter when a user signs in or off. The INSTEAD OF triggers are alternatives to DML triggers, but they control operations on views instead of tables. For events about suspended statements, the triggers can be used for alerting people of problems about lack of tablespace or quotas exceeded. In this project, I used what I just mentioned before to compose my database queries by using Oracle PL/SQL based on the Company database. For all of implemented queries in detail, please go to the section of Appendix (Queries for this project) to check. I put the comments for each queries to explain what they are used for. Also, the screenshots of results of each query are attached in the last section of this report. V. Analysis: In this section, I will briefly compare Oracle PL/SQL with PL/pgSQL first. Then, I would like to talk about interesting issues I found while I was working on this project. 1. Oracle PL/SQL vs PL/pgSQL

4 In the section of Description, I already introduced Oracle PL/SQL. However, in the PostgreSQL database system, it also has a language called PL/pgSQL, which is a loadable procedural language for that database system. PL/pgSQL is similar to Oracle PL/SQL in many aspects. It is a block-structured and imperative language. Also, all variables in PL/pgSQL program have to be declared. In addition, it has assignments, loops and conditionals. In PL/pgSQL, the function body must be written as a string literal. In PL/pgSQL, there are no packages, so it needs to use schemas to organize functions into groups instead of packages. In PL/pgSQL, there are no package-level variables because there are no packages. In PL/SQL, there are packages and there are package-level variables. Integer FOR loops with REVERSE and FOR loops over queries (other than cursors) work differently between PL/pgSQL and PL/SQL. In addition, there are different notational differences for the use of cursor variables between both of them. 2. Performance between string indexing and integer indexing A procedure called test_associative_array_index which I wrote by using two associative arrays is to demonstrate the performance of string indexing and integer indexing. So, the data types of keys of these two arrays are string and integer. The keys are SSN and FNAME from Company database. For this procedure, you can give two values as parameters, which are the length of the string index and the number of iteration times. The procedure will also check the users inputs. In this procedure, I used a built-in method in PL.SQL to increase the string length. Also, I called a third-party procedure in my procedure to calculate the elapsed CPU time. The cost of using string indexing would depend on the length of the string index which people use. During using the string indexes, the database can take the string and hashes it into an integer. So, the hash function and the conflict resolution are very important and can also determine the performance. The maximum size of the VARCHAR2 data types which I used in the procedure has been increased from 4000 to bytes according to the documentations from Oracle website. That is why I set as the size of VARCHAR2, which is the maximum size. For integer indexing, I used a data type called PLS_INTEGER. According to the documentation from Oracle website, this data type stores signed integers in the range -2,147,483,648 through 2,147,483,647 and is represented in 32 bits. Also, according to Oracle website, PLS_INTEGER values require less storage, and its operations use hardware arithmetic, so the operations of this kind of type are quicker than NUMBER operations using library arithmetic. From the Figure 1 below, it shows that the performances between string indexing and integer indexing are close when the length of string index is quite small which is that the length would be 150characters or fewer in this case. When the length of string index increases, hashing overhead will increase substantially and can make CPU elapsed time increase. So, it needs to be careful to choose string indexing and use appropriate length of string index to index when people consider string indexing. Figure 1 Results of comparing string indexing and integer indexing.

5 3. The fired order of triggers When I read books and search information about PL/SQL online, I found that the versions of Oracle Database which are lower than 11g cannot guarantee the order in which multiple DML triggers would be fired. Although the Oracle Database I used for this project was 12c, I still created two triggers which are ADD_WORKING_HOURS_BY_TEN and ADD_WORKING_HOURS_BY_TWENTY to do an experiment and check what the fired order would be for these two triggers. First, I created ADD_WORKING_HOURS_BY_TEN and then created ADD_WORKING_HOURS_BY_TWENTY. In each of these two triggers, I included printing information statement in order to make me check which trigger is fired first easily. At the second time, I created ADD_WORKING_HOURS_BY_TWENTY first, and then created ADD_WORKING_HOURS_BY_TEN. From the Figure 2 below, it displays the results of fired orders of two triggers during two executions. So, for these two triggers, if ADD_WORKING_HOURS_BY_TEN is created first, it will be fired after ADD_WORKING_HOURS_BY_TWENTY does. If ADD_WORKING_HOURS_BY_TWENTY is created first, it will be fired after ADD_WORKING_HOURS_BY_TEN does. Fortunately, from Oracle Database 11g and the later versions, we can use the FOLLOWS clause to ensure the fired order for triggers. Then, it can help guarantee the final result of a corresponding query. Figure 2 Results of fired orders of two triggers during two executions 4. Statement level triggers vs Row level triggers In DML triggers, when a trigger is created with specifying FOR EACH ROW option, the trigger will activate for each row processed by a statement. This kind of trigger is a row level trigger. If FOR EACH ROW is not specified, the default behavior will be fired only once for the statement. This kind of trigger is a statement level trigger. In another words, an event is triggered for each row inserted, updated or deleted for the row level trigger. An event is triggered for each SQL statement executed for the statement level trigger. I wrote 4 triggers which are TESTING_ST_A_TGR, TESTING_RL_B_TGR, TESTING_RL_A_TGR and TESTING_RL_A_TGR. They are applied to the DEPT_LOCATIONS table. Each trigger extends a collection (t_p_info_tab) which I declared and created in the COMPANY_DB package and saves an information message with the trigger information and the action when it is fired. In addition, the statement trigger (TESTING_ST_A_TGR) can display the elements of the collection and empty it. From the figure 3 below, it displays the order of statement level triggers and row level triggers fired in which the timing points. Statement level trigger (BEFORE) is fired first. Then, row level trigger (BEFORE) is fired once for each affected row. Then, row level trigger (AFTER) is fired once for each affected row. The events will alternates between row level triggers (BEFORE and AFTER). Eventually, the statement level trigger (AFTER) is fired.

6 Figure 3 Results of Statement level triggers and Row level triggers. 5. Avoiding cyclic cascading triggers Cyclic cascading triggers are undesirable situations. In this kind of situation, more than one trigger would get into an infinite loop. It can make the database crash, so it should avoid this kind situation when people create a trigger. Here is an example about cyclic cascading triggers. There are two tables, which are X and Y and two triggers, which are X_T and Y_T. X_T is an INSERT trigger on table X and Y_T is an UPDATE trigger on table Y. The action of X_T is to make an update on the table Y. The action of Y_T is to make an insertion on the table X. When a row is inserted into table X, X_T will be fired and make an update on the table Y. Then, Y_T will be fired because table Y is updated and make an insertion on the table X. Then, the cyclic situation happens and will continue and get into an infinite loop. 6. Mutating Table Errors In the Appendix (Queries for this project) of this report, there is a trigger, which is UPDATE_A_DEPARTMENT_NAME. The purpose of this trigger would be to check if the department name is duplicated. If the name is duplicated, the trigger will be fired and display an error message. However, when I tested this trigger, I got a mutating table error from Oracle SQL developer. From the Figure 4 below, it shows the error which I got. This error is related to the row level trigger. When a row level trigger tries to check or change a table which is already experiencing change through the DML, which could be an INSERT, UPDATE, or DELETE statement, this mutating table error will happen. In another words, when a row level trigger tries to read or write the table from which the trigger was fired, this error will happen. So, it needs to be careful and avoid this kind of error. For the statement level triggers, they are no restrictions to both read and change the triggering table. Here, in my point of view, I think it would be better to use UNIQUE constraint instead of writing a trigger for checking if the department is duplicated on the DEPARTMENT table. Comparing with triggers enforcing the same rules, constraints are easier to write and less error-prone. Certainly, triggers can enforce some complex business rules which constraints cannot do in some situations. Figure 4 a Mutating Table Error

7 VI. Conclusion: After finishing this practical project about DB queries using Oracle PL/SQL, I had better understanding on PL/SQL and its programming concepts. Also, I learned what factors can affect the performance of string indexing, and in which situations I shall choose string indexing and integer indexing. In addition, I had better understanding about triggers. Triggers can be used for complicated or complex business rules or purposes. When they interact with each other and with the database, it will be important to completely understand how they act. References Feuerstein, S. (2014). Oracle PL/SQL Programming (6th ed). Sebastopol, CA: O Reilly Media, Inc. Murach, J. (2008). Murach s Oracle SQL and PL/SQL. Fresno, CA: Mike Murach & Associates. PostgreSQL. (2017). PostgreSQL Documentation. Retrieved from Appendix (Queries for this project) -- Procedure to create all tables of Company DB create or replace PROCEDURE CREATE_ALL_TABLES IS EXECUTE IMMEDIATE 'DROP TABLE DEPENDENT'; EXECUTE IMMEDIATE 'DROP TABLE WORKS_ON'; EXECUTE IMMEDIATE 'DROP TABLE PROJECT'; EXECUTE IMMEDIATE 'DROP TABLE DEPT_LOCATIONS'; EXECUTE IMMEDIATE 'ALTER TABLE EMPLOYEE DROP CONSTRAINT EMPLOYEE_DEPARTMENT_FK'; EXECUTE IMMEDIATE 'DROP TABLE DEPARTMENT'; EXECUTE IMMEDIATE 'DROP TABLE EMPLOYEE'; EXECUTE IMMEDIATE 'CREATE TABLE EMPLOYEE' ' (FNAME VARCHAR2(32),' 'MINIT VARCHAR2(1),' 'LNAME VARCHAR2(32),' 'SSN VARCHAR2(9) NOT NULL,' 'BDATE DATE,' 'ADDRESS VARCHAR(128),' 'SEX VARCHAR2(1),' 'SALARY NUMBER(8),' 'SUPER_SSN VARCHAR2(9) REFERENCES EMPLOYEE (SSN),' 'DNO NUMBER(2),'

8 'CONSTRAINT EMPLOYEE_PK PRIMARY KEY (SSN))'; EXECUTE IMMEDIATE 'CREATE TABLE DEPARTMENT' ' (DNAME VARCHAR2(32) NOT NULL,' 'DNUMBER NUMBER(2) NOT NULL,' 'MGR_SSN VARCHAR2(9),' 'MGR_START_DATE DATE,' 'CONSTRAINT DEPARTMENT_PK PRIMARY KEY (DNUMBER),' 'CONSTRAINT DEPARTMENT_EMPLOYEE_FK FOREIGN KEY (MGR_SSN) REFERENCES EMPLOYEE (SSN))'; EXECUTE IMMEDIATE 'CREATE TABLE DEPT_LOCATIONS' ' (DNUMBER NUMBER(2) NOT NULL,' 'DLOCATION VARCHAR2(32) NOT NULL,' 'CONSTRAINT DEPT_LOCATIONS_PK PRIMARY KEY (DNUMBER, DLOCATION),' 'CONSTRAINT DEPTLOCATIONS_DEPARTMENT_FK FOREIGN KEY(DNUMBER) REFERENCES DEPARTMENT (DNUMBER))'; EXECUTE IMMEDIATE 'CREATE TABLE PROJECT' ' (PNAME VARCHAR2(32),' 'PNUMBER NUMBER(2) NOT NULL,' 'PLOCATION VARCHAR2(32),' 'DNUM NUMBER(2),' 'CONSTRAINT PROJECT_PK PRIMARY KEY (PNUMBER),' 'CONSTRAINT PROJECT_DEPARTMENT_FK FOREIGN KEY (DNUM) REFERENCES DEPARTMENT (DNUMBER))'; EXECUTE IMMEDIATE 'CREATE TABLE WORKS_ON' ' (ESSN VARCHAR2(9) NOT NULL,' 'PNO NUMBER(2) NOT NULL,' 'HOURS REAL,' 'CONSTRAINT WORKSON_PK PRIMARY KEY (ESSN, PNO),' 'CONSTRAINT WORKSON_EMPLOYEE_FK FOREIGN KEY (ESSN) REFERENCES EMPLOYEE (SSN),' 'CONSTRAINT WORKSON_PROJECT_FK FOREIGN KEY (PNO) REFERENCES PROJECT (PNUMBER))'; EXECUTE IMMEDIATE 'CREATE TABLE DEPENDENT' ' (ESSN VARCHAR2(9) NOT NULL,' 'DEPENDENT_NAME VARCHAR2(64) NOT NULL,' 'SEX VARCHAR2(1),' 'BDATE DATE,' 'RELATIONSHIP VARCHAR2(16),' 'CONSTRAINT DEPENDENT_PK PRIMARY KEY (ESSN, DEPENDENT_NAME),' 'CONSTRAINT DEPENDENT_EMPLOYEE_FK FOREIGN KEY (ESSN) REFERENCES EMPLOYEE (SSN))'; EXECUTE IMMEDIATE 'ALTER TABLE EMPLOYEE ADD CONSTRAINT EMPLOYEE_DEPARTMENT_FK FOREIGN KEY (DNO) REFERENCES DEPARTMENT (DNUMBER)'; DBMS_OUTPUT.PUT_LINE('All tables of Company DB were created!');

9 EXCEPTION WHEN OTHERS THEN NULL; END CREATE_ALL_TABLES; -- A procedure for inserting an employee create or replace PROCEDURE INSERT_AN_EMPLOYEE ( fname_param IN EMPLOYEE.FNAME%TYPE, minit_param IN EMPLOYEE.MINIT%TYPE, lname_param IN EMPLOYEE.LNAME%TYPE, ssn_param IN EMPLOYEE.SSN%TYPE, bdate_param IN VARCHAR2, address_param IN EMPLOYEE.ADDRESS%TYPE, sex_param IN EMPLOYEE.SEX%TYPE, salary_param IN EMPLOYEE.SALARY%TYPE, super_ssn_param IN EMPLOYEE.SUPER_SSN%TYPE DEFAULT NULL, dno_param IN EMPLOYEE.DNO%TYPE DEFAULT NULL ) IS ex_invalid_ssn EXCEPTION; ex_invalid_salary EXCEPTION; ex_invalid_bdate EXCEPTION; IF (LENGTH(ssn_param)!= 9) THEN RAISE ex_invalid_ssn; IF (salary_param < 0 OR LENGTH(TO_CHAR(salary_param)) > 8) THEN RAISE ex_invalid_salary; IF (TRUNC(MONTHS_BETWEEN(TO_DATE(SYSDATE, 'YYYY-MM-DD'),TO_DATE(bdate_param,'YYYY-MM-DD')))/ 12 > 100 OR TRUNC(MONTHS_BETWEEN(TO_DATE(SYSDATE, 'YYYY-MM-DD'),TO_DATE(bdate_param,'YYYY-MM-DD')))/ 12 < 18) THEN RAISE ex_invalid_bdate; INSERT INTO EMPLOYEE (FNAME, MINIT, LNAME, SSN, BDATE, ADDRESS, SEX, SALARY, SUPER_SSN, DNO) VALUES (fname_param, minit_param, lname_param, ssn_param, TO_DATE(bdate_param,'YYYY-MM-DD'), address_param, sex_param, salary_param, super_ssn_param, dno_param); DBMS_OUTPUT.PUT_LINE('An employee was added into the EMPLOYEE table!'); EXCEPTION WHEN DUP_VAL_ON_INDEX THEN

10 DBMS_OUTPUT.PUT_LINE('Duplicate value on SSN!'); WHEN ex_invalid_ssn THEN DBMS_OUTPUT.PUT_LINE('The ssn must be 9 digits!'); WHEN ex_invalid_salary THEN DBMS_OUTPUT.PUT_LINE('The salary cannot be a negative integer and cannot be more than 8 digits!'); WHEN ex_invalid_bdate THEN DBMS_OUTPUT.PUT_LINE('The date of birth is invalid!'); WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('An error was encountered - ' SQLCODE ' -ERROR- ' SQLERRM); END INSERT_AN_EMPLOYEE; -- A procedure for inserting a department create or replace PROCEDURE INSERT_A_DEPARTMENT ( dname_param IN DEPARTMENT.DNAME%TYPE, dnumber_param IN DEPARTMENT.DNUMBER%TYPE, mgr_ssn_param IN DEPARTMENT.MGR_SSN%TYPE, mgr_start_date_param IN VARCHAR2 ) IS ex_invalid_ssn EXCEPTION; ex_invalid_sdate EXCEPTION; ex_invalid_dno EXCEPTION; IF (LENGTH(mgr_ssn_param)!= 9) THEN RAISE ex_invalid_ssn; IF (dnumber_param <= 0 OR RAISE ex_invalid_dno; LENGTH(TO_CHAR(dnumber_param)) > 2) THEN IF (TO_DATE(mgr_start_date_param,'YYYY-MM-DD') > TO_DATE(SYSDATE, 'YYYY-MM-DD') OR TRUNC(MONTHS_BETWEEN(TO_DATE(SYSDATE, 'YYYY-MM-DD'),TO_DATE(mgr_start_date_param,'YYYY-MM-DD')))/ 12 > 100) THEN RAISE ex_invalid_sdate; INSERT INTO DEPARTMENT (DNAME, DNUMBER, MGR_SSN, MGR_START_DATE) VALUES (dname_param, dnumber_param, mgr_ssn_param, TO_DATE(mgr_start_date_param,'YYYY-MM-DD')); DBMS_OUTPUT.PUT_LINE('A department was added into the DEPARTMENT table!'); EXCEPTION WHEN DUP_VAL_ON_INDEX THEN DBMS_OUTPUT.PUT_LINE('Duplicate value on DNO!'); WHEN ex_invalid_ssn THEN

11 DBMS_OUTPUT.PUT_LINE('The mgr_ssn must be 9 digits!'); WHEN ex_invalid_sdate THEN DBMS_OUTPUT.PUT_LINE('The start date is invalid!'); WHEN ex_invalid_dno THEN DBMS_OUTPUT.PUT_LINE('The department number should be a positive integer and cannot be more than 2 digits!'); WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('An error was encountered - ' SQLCODE ' -ERROR- ' SQLERRM); END INSERT_A_DEPARTMENT; -- A procedure for inserting a dept_location create or replace PROCEDURE INSERT_A_DEPT_LOCATION ( dnumber_param IN DEPT_LOCATIONS.DNUMBER%TYPE, dlocation_param IN DEPT_LOCATIONS.DLOCATION%TYPE ) IS ex_invalid_dno EXCEPTION; IF (dnumber_param <= 0 OR LENGTH(TO_CHAR(dnumber_param)) > 2) THEN RAISE ex_invalid_dno; INSERT INTO DEPT_LOCATIONS (DNUMBER, DLOCATION) VALUES (dnumber_param, dlocation_param); DBMS_OUTPUT.PUT_LINE('A dept_location was added into the DEPT_LOCATIONS table!'); EXCEPTION WHEN DUP_VAL_ON_INDEX THEN DBMS_OUTPUT.PUT_LINE('Duplicate values!'); WHEN ex_invalid_dno THEN DBMS_OUTPUT.PUT_LINE('The department number should be a positive integer and cannot be more than 2 digits!'); WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('An error was encountered - ' SQLCODE ' -ERROR- ' SQLERRM); END INSERT_A_DEPT_LOCATION; -- A procedure for inserting a works_on create or replace PROCEDURE INSERT_A_WORKS_ON ( essn_param IN WORKS_ON.ESSN%TYPE, pno_param IN WORKS_ON.PNO%TYPE, hours_param IN WORKS_ON.HOURS%TYPE ) IS ex_invalid_pno EXCEPTION; ex_invalid_essn EXCEPTION; ex_invalid_hours EXCEPTION;

12 IF (pno_param <= 0 OR LENGTH(pno_param) > 2) THEN RAISE ex_invalid_pno; IF (LENGTH(essn_param)!= 9) THEN RAISE ex_invalid_essn; IF (hours_param <= 0) THEN RAISE ex_invalid_hours; INSERT INTO WORKS_ON (ESSN, PNO, HOURS) VALUES (essn_param, pno_param, hours_param); DBMS_OUTPUT.PUT_LINE('A works_on was added into the WORKS_ON table!'); EXCEPTION WHEN DUP_VAL_ON_INDEX THEN DBMS_OUTPUT.PUT_LINE('Duplicate values!'); WHEN ex_invalid_essn THEN DBMS_OUTPUT.PUT_LINE('The essn must be 9 digits!'); WHEN ex_invalid_pno THEN DBMS_OUTPUT.PUT_LINE('The project number should be a positive integer and cannot be more than 2 digits!'); WHEN ex_invalid_hours THEN DBMS_OUTPUT.PUT_LINE('The hours should be a positive number!'); WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('An error was encountered - ' SQLCODE ' -ERROR- ' SQLERRM); END INSERT_A_WORKS_ON; -- A procedure for inserting a project create or replace PROCEDURE INSERT_A_PROJECT ( pname_param IN PROJECT.PNAME%TYPE, pnumber_param IN PROJECT.PNUMBER%TYPE, plocation_param IN PROJECT.PLOCATION%TYPE, dnum_param IN PROJECT.DNUM%TYPE ) IS ex_invalid_pnumber EXCEPTION; ex_invalid_dno EXCEPTION; IF (pnumber_param <= 0 OR LENGTH(TO_CHAR(pnumber_param)) > 2) THEN RAISE ex_invalid_pnumber; IF (dnum_param <= 0 OR RAISE ex_invalid_dno; LENGTH(TO_CHAR(dnum_param)) > 2) THEN

13 INSERT INTO PROJECT (PNAME, PNUMBER, PLOCATION, DNUM) VALUES (pname_param, pnumber_param, plocation_param, dnum_param); DBMS_OUTPUT.PUT_LINE('A project was added into the PROJECT table!'); EXCEPTION WHEN DUP_VAL_ON_INDEX THEN DBMS_OUTPUT.PUT_LINE('Duplicate value on Pnumber!'); WHEN ex_invalid_dno THEN DBMS_OUTPUT.PUT_LINE('The department number should be a positive integer and cannot be more than 2 digits!'); WHEN ex_invalid_pnumber THEN DBMS_OUTPUT.PUT_LINE('The project number should be a positive integer and cannot be more than 2 digits!'); WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('An error was encountered - ' SQLCODE ' -ERROR- ' SQLERRM); END INSERT_A_PROJECT; -- A procedure for inserting a dependent create or replace PROCEDURE INSERT_A_DEPENDENT ( essn_param IN DEPENDENT.ESSN%TYPE, dependent_name_param IN DEPENDENT.DEPENDENT_NAME%TYPE, sex_param IN DEPENDENT.SEX%TYPE, bdate_param IN DEPENDENT.BDATE%TYPE, relationship_param IN DEPENDENT.RELATIONSHIP%TYPE ) IS ex_invalid_essn EXCEPTION; ex_invalid_bdate EXCEPTION; IF (LENGTH(essn_param)!= 9) THEN RAISE ex_invalid_essn; IF (TO_DATE(bdate_param,'YYYY-MM-DD') > TO_DATE(SYSDATE, 'YYYY-MM-DD') OR TRUNC(MONTHS_BETWEEN(TO_DATE(SYSDATE, 'YYYY-MM-DD'),TO_DATE(bdate_param,'YYYY-MM-DD')))/ 12 > 120) THEN RAISE ex_invalid_bdate; INSERT INTO DEPENDENT (ESSN, DEPENDENT_NAME, SEX, BDATE, RELATIONSHIP) VALUES (essn_param, dependent_name_param, sex_param, TO_DATE(bdate_param,'YYYY-MM-DD'), relationship_param); DBMS_OUTPUT.PUT_LINE('A dependent was added into the DEPENDENT table!'); EXCEPTION WHEN DUP_VAL_ON_INDEX THEN DBMS_OUTPUT.PUT_LINE('Duplicate values!');

14 WHEN ex_invalid_essn THEN DBMS_OUTPUT.PUT_LINE('The essn must be 9 digits!'); WHEN ex_invalid_bdate THEN DBMS_OUTPUT.PUT_LINE('The date of birth is invalid!'); WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('An error was encountered - ' SQLCODE ' -ERROR- ' SQLERRM); END INSERT_A_DEPENDENT; -- A procedure for updating an employee's department number create or replace PROCEDURE UPDATE_AN_EMPLOYEE ( dno_param IN EMPLOYEE.DNO%TYPE, ssn_param IN EMPLOYEE.SSN%TYPE ) IS ex_invalid_ssn EXCEPTION; ex_invalid_dno EXCEPTION; c_ssn NUMBER; c_dno NUMBER; CURSOR c1 IS SELECT SSN FROM EMPLOYEE WHERE SSN = ssn_param; CURSOR c2 IS SELECT DNUMBER FROM DEPARTMENT WHERE DNUMBER = dno_param; IF (LENGTH(ssn_param)!= 9) THEN RAISE ex_invalid_ssn; IF (dno_param <= 0 OR LENGTH(TO_CHAR(dno_param)) > 2) THEN RAISE ex_invalid_dno; OPEN c1; OPEN c2; FETCH c1 INTO c_ssn; FETCH c2 INTO c_dno; IF (c1%found AND c2%found ) THEN UPDATE EMPLOYEE SET DNO=c_dno WHERE SSN=c_ssn; DBMS_OUTPUT.PUT_LINE('The employee was updated with a department number!'); ELSIF (c1%notfound) THEN DBMS_OUTPUT.PUT_LINE('The employee which you want to update does not exist!'); ELSE DBMS_OUTPUT.PUT_LINE('The department number which you used does not exist!'); CLOSE c1; CLOSE c2;

15 EXCEPTION WHEN ex_invalid_ssn THEN DBMS_OUTPUT.PUT_LINE('The ssn must be 9 digits!'); WHEN ex_invalid_dno THEN DBMS_OUTPUT.PUT_LINE('The department number should be a positive integer and cannot be more than 2 digits!'); WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('An error was encountered - ' SQLCODE ' -ERROR- ' SQLERRM); END UPDATE_AN_EMPLOYEE; -- A procedure to populate all tables create or replace PROCEDURE POPULATE_ALL_TABLES AS INSERT_AN_EMPLOYEE('James', 'E', 'Borg', ' ', ' ', '450 Stone, Houston, TX', 'M', 55000, NULL, NULL); INSERT_AN_EMPLOYEE('Franklin', 'T', 'Wong', ' ', ' ', '638 Voss, Houston, TX', 'M', 40000, ' ', NULL); INSERT_AN_EMPLOYEE('John', 'B', 'Smith', ' ', ' ', '731 Fondren, Houston, TX', 'M', 30000, ' ', NULL); INSERT_AN_EMPLOYEE('Jennifer', 'S', 'Wallace', ' ', ' ', '291 Berry, Bellaire, TX', 'F', 43000, ' ', NULL); INSERT_AN_EMPLOYEE('Alicia', 'J', 'Zelaya', ' ', ' ', '3321 Castle, Spring, TX', 'F', 25000, ' ', NULL); INSERT_AN_EMPLOYEE('Ramesh', 'K', 'Narayan', ' ', ' ', '975 Fire Oak, Humble, TX', 'M', 38000, ' ', NULL); INSERT_AN_EMPLOYEE('Joyce', 'A', 'English', ' ', ' ', '5631 Rice, Houston, TX', 'F', 25000, ' ', NULL); INSERT_AN_EMPLOYEE('Ahmad', 'V', 'Jabbar', ' ', ' ', '980 Dallas, Houston, TX', 'M', 25000, ' ', NULL); INSERT_A_DEPARTMENT('Research', 5, ' ', ' '); INSERT_A_DEPARTMENT('Administration', 4, ' ', ' '); INSERT_A_DEPARTMENT('Headquarters', 1, ' ', ' '); INSERT_A_DEPT_LOCATION(1, 'Houston'); INSERT_A_DEPT_LOCATION(4, 'Stafford'); INSERT_A_DEPT_LOCATION(5, 'Bellaire '); INSERT_A_DEPT_LOCATION(5, 'Sugarland '); INSERT_A_DEPT_LOCATION(5, 'Houston '); INSERT_A_PROJECT('ProductX', 1, 'Bellaire', 5); INSERT_A_PROJECT('ProductY', 2, 'Sugarland', 5); INSERT_A_PROJECT('ProductZ ', 3, 'Houston', 5); INSERT_A_PROJECT('Computerization', 10, 'Stafford', 4); INSERT_A_PROJECT('Reorganization', 20, 'Houston', 1); INSERT_A_PROJECT('Newbenefits', 30, 'Stafford', 4);

16 INSERT_A_WORKS_ON(' ', 1, 32.5); INSERT_A_WORKS_ON(' ', 2, 7.5); INSERT_A_WORKS_ON(' ', 3, 40.0); INSERT_A_WORKS_ON(' ', 1, 20.0); INSERT_A_WORKS_ON(' ', 2, 20.0); INSERT_A_WORKS_ON(' ', 2, 10.0); INSERT_A_WORKS_ON(' ', 3, 10.0); INSERT_A_WORKS_ON(' ', 10, 10.0); INSERT_A_WORKS_ON(' ', 20, 10.0); INSERT_A_WORKS_ON(' ', 30, 30.0); INSERT_A_WORKS_ON(' ', 10, 10.0); INSERT_A_WORKS_ON(' ', 10, 35.0); INSERT_A_WORKS_ON(' ', 30, 5.0); INSERT_A_WORKS_ON(' ', 30, 20.0); INSERT_A_WORKS_ON(' ', 20, 15.0); INSERT_A_WORKS_ON(' ', 20, NULL); INSERT_A_DEPENDENT(' ', 'Alice', 'F', ' ', 'Daughter'); INSERT_A_DEPENDENT(' ', 'Theodore', 'M', ' ', 'Son'); INSERT_A_DEPENDENT(' ', 'Joy', 'F', ' ', 'Spouse'); INSERT_A_DEPENDENT(' ', 'Abner', 'M', ' ', 'Spouse'); INSERT_A_DEPENDENT(' ', 'Michael', 'M', ' ', 'Son'); INSERT_A_DEPENDENT(' ', 'Alice', 'F', ' ', 'Daughter'); INSERT_A_DEPENDENT(' ', 'Elizabeth', 'F', ' ', 'Spouse'); UPDATE_AN_EMPLOYEE(5, ' '); UPDATE_AN_EMPLOYEE(5, ' '); UPDATE_AN_EMPLOYEE(4, ' '); UPDATE_AN_EMPLOYEE(4, ' '); UPDATE_AN_EMPLOYEE(5, ' '); UPDATE_AN_EMPLOYEE(5, ' '); UPDATE_AN_EMPLOYEE(4, ' '); UPDATE_AN_EMPLOYEE(1, ' '); END POPULATE_ALL_TABLES; -- Procedure to evaluate the performacne between String indexing and integer indexing create or replace PROCEDURE test_associative_array_index ( str_length IN PLS_INTEGER DEFAULT 150, how_many_iterations IN PLS_INTEGER DEFAULT ) IS -- Associative array types TYPE type_table_bynum IS TABLE OF EMPLOYEE%ROWTYPE INDEX BY PLS_INTEGER; --Maximum length of VARCHAR2 in PL/SQL is TYPE type_table_bystr IS TABLE OF EMPLOYEE%ROWTYPE INDEX BY VARCHAR2

17 (32767); -- Variable Declaration e_dnumber NUMBER; bynum_table type_table_bynum; bystr_table type_table_bystr; x NUMBER := 0; y NUMBER := 0; ex_invalid_str_length EXCEPTION; ex_invalid_iterations EXCEPTION; IF (str_length <=0) OR (str_length > 32767) THEN RAISE ex_invalid_str_length; IF (how_many_iterations <= 0) THEN RAISE ex_invalid_iterations; -- Using for loop to add records to the table FOR r IN (SELECT * FROM EMPLOYEE) LOOP bynum_table (TO_NUMBER(r.SSN)) := r; END LOOP; FOR r IN (SELECT * FROM EMPLOYEE) LOOP -- RPAD method to make the string index reach the length of the str_length input bystr_table (RPAD (r.fname, str_length, '#')) := r; END LOOP; DBMS_OUTPUT.PUT_LINE('Compare String and Integer Indexing, String Length = ' str_length ', Iterations = ' how_many_iterations); sf_timer.start_timer; WHILE (x < how_many_iterations) LOOP FOR r IN (SELECT * FROM EMPLOYEE) LOOP e_dnumber := bystr_table (RPAD (r.fname, str_length, '#')).DNO; END LOOP; x := x + 1; END LOOP; sf_timer.show_elapsed_time ('Table Index by VARCHAR2 '); sf_timer.start_timer;

18 WHILE (y < how_many_iterations) LOOP FOR r IN (SELECT * FROM EMPLOYEE) LOOP e_dnumber := bynum_table (TO_NUMBER(r.SSN)).DNO; END LOOP; y := y + 1; END LOOP; sf_timer.show_elapsed_time ('Table Index by PLS_INTEGER '); EXCEPTION WHEN ex_invalid_str_length THEN DBMS_OUTPUT.PUT_LINE('The string length cannot be less than or equal to 0 or greater than 32767!'); WHEN ex_invalid_iterations THEN DBMS_OUTPUT.PUT_LINE('The number of iterations cannot be less than or equal to 0!'); WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('An error was encountered - ' SQLCODE ' -ERROR- ' SQLERRM); END test_associative_array_index; create or replace PACKAGE COMPANY_DB IS /* For each department whose average employee salary is more than an avg_threshold, display the department name, department number, average employee salary and the number of employees working for that department.*/ PROCEDURE SHOW_DEPT_INFO_LIST_1(avg_threshold IN REAL); /*Get the highest salary among all employees*/ FUNCTION GET_MAX_SALARY_EM RETURN EMPLOYEE.SALARY%TYPE; /*Display the first names, last names, department number and salaries of all employees who work in the department that has the employee with the highest salary among all employees*/ PROCEDURE SHOW_LNAMES_HHSALARY_IN_DPT; /*Display the names, ssn of all employees whose supervisor s supervisor has a ssn from the input.*/ PROCEDURE SHOW_NAMES_SSN_SSS(ssn_param IN EMPLOYEE.SSN%TYPE); /*Display the names, salaries of employees who make at least (a threshold) more than the employee who is paid the least in the company.*/ PROCEDURE SHOW_NAMES_SALARY_THRESHOLD(threshold_param IN NUMBER); /*Display the names of employees who have no dependents.*/ PROCEDURE SHOW_NAMES_EM_NO_DEPENDENTS;

19 /*Give employees in a specified department a same bonus rate based on a threshold about total working hours */ PROCEDURE GIVE_BONUS(w_h_threshold IN WORKS_ON.HOURS%TYPE, bonus_rate IN NUMBER, dno_param IN DEPARTMENT.DNUMBER%TYPE); /*The following is used to perform timing points for the statement level trigger and the row level trigger*/ TYPE trigger_tab IS TABLE OF VARCHAR2(300); t_p_info_tab trigger_tab := trigger_tab(); END COMPANY_DB; create or replace PACKAGE BODY COMPANY_DB IS -- Implementation of the procedures and functions PROCEDURE SHOW_DEPT_INFO_LIST_1 ( avg_threshold IN REAL ) IS TYPE dept_info_rectype IS RECORD ( dept_name DEPARTMENT.DNAME%TYPE, dno EMPLOYEE.DNO%TYPE, avg_salary REAL, num_of_employees NUMBER); dept_ino_r dept_info_rectype; ex_invalid_avg_threshold EXCEPTION; v_count NUMBER; is_found_rec BOOLEAN := FALSE; IF (avg_threshold <= 0) THEN RAISE ex_invalid_avg_threshold; DBMS_OUTPUT.PUT_LINE('For each department whose average employee salary is more than $' avg_threshold ','); DBMS_OUTPUT.PUT_LINE('display the department name, department number, average employee salary and the number of employees working for that department.'); FOR rec IN (SELECT D.DNAME, E.DNO, AVG (E.SALARY), COUNT (*) FROM DEPARTMENT D, EMPLOYEE E WHERE D.DNUMBER = E.DNO GROUP BY D.DNAME, E.DNO HAVING AVG (E.SALARY) > avg_threshold

20 ORDER BY D.DNAME) LOOP is_found_rec := TRUE; dept_ino_r := rec; DBMS_OUTPUT.PUT_LINE('Department Name: ' dept_ino_r.dept_name ' Department Number: ' dept_ino_r.dno ' Average Employee Salary: ' dept_ino_r.avg_salary ' Number of Employees: ' dept_ino_r.num_of_employees); END LOOP; IF (is_found_rec = FALSE) THEN DBMS_OUTPUT.PUT_LINE('No Record!'); EXCEPTION WHEN ex_invalid_avg_threshold THEN DBMS_OUTPUT.PUT_LINE('The average salary threshold cannot be less than or equal to 0!'); WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('An error was encountered - ' SQLCODE ' -ERROR- ' SQLERRM); END SHOW_DEPT_INFO_LIST_1; FUNCTION GET_MAX_SALARY_EM RETURN EMPLOYEE.SALARY%TYPE IS max_salary EMPLOYEE.SALARY%TYPE; SELECT MAX(SALARY) INTO max_salary FROM EMPLOYEE; RETURN max_salary; EXCEPTION WHEN NO_DATA_FOUND THEN RETURN NULL; END GET_MAX_SALARY_EM; PROCEDURE SHOW_LNAMES_HHSALARY_IN_DPT IS CURSOR c1 IS SELECT LNAME, FNAME, DNO, SALARY FROM EMPLOYEE WHERE DNO = (SELECT DNO FROM EMPLOYEE WHERE SALARY = GET_MAX_SALARY_EM);

21 is_found_rec BOOLEAN := FALSE; FOR rec IN c1 LOOP is_found_rec := TRUE; DBMS_OUTPUT.PUT_LINE(rec.FNAME ' ' rec.lname ' who works in the department [' rec.dno '] that has the employee with the highest salary($' rec.salary ') among all employees'); END LOOP; IF (is_found_rec = FALSE) THEN DBMS_OUTPUT.PUT_LINE('No Record!'); EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('An error was encountered - ' SQLCODE ' -ERROR- ' SQLERRM); END SHOW_LNAMES_HHSALARY_IN_DPT; PROCEDURE SHOW_NAMES_SSN_SSS ( ssn_param IN EMPLOYEE.SSN%TYPE ) IS TYPE names_list IS TABLE OF VARCHAR2(65) INDEX BY EMPLOYEE.SSN%TYPE; list_of_names names_list; indx EMPLOYEE.SSN%TYPE; ex_invalid_ssn EXCEPTION; CURSOR c1 IS SELECT FNAME, LNAME, SSN FROM EMPLOYEE WHERE SUPER_SSN IN (SELECT SSN FROM EMPLOYEE WHERE SUPER_SSN = ssn_param); is_found_rec BOOLEAN := FALSE; IF (LENGTH(ssn_param)!= 9) THEN RAISE ex_invalid_ssn;

22 FOR rec IN c1 LOOP list_of_names(rec.ssn) := rec.fname ' ' rec.lname; END LOOP; DBMS_OUTPUT.PUT_LINE('The following employees whose supervisor s supervisor has a SSN: ' ssn_param); indx := list_of_names.first; WHILE (indx IS NOT NULL) LOOP is_found_rec := TRUE; DBMS_OUTPUT.PUT_LINE (list_of_names(indx) ', SSN: ' indx); indx := list_of_names.next (indx); END LOOP; IF (is_found_rec = FALSE) THEN DBMS_OUTPUT.PUT_LINE('No Record!'); EXCEPTION WHEN ex_invalid_ssn THEN DBMS_OUTPUT.PUT_LINE('The ssn must be 9 digits!'); WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('An error was encountered - ' SQLCODE ' -ERROR- ' SQLERRM); END SHOW_NAMES_SSN_SSS; PROCEDURE SHOW_NAMES_SALARY_THRESHOLD ( threshold_param IN NUMBER ) IS CURSOR c1 IS SELECT FNAME, LNAME FROM EMPLOYEE WHERE SALARY >= threshold_param + (SELECT MIN(SALARY) FROM EMPLOYEE) ORDER BY FNAME; r_count PLS_INTEGER := 0; arr_c PLS_INTEGER := 0;

23 TYPE n_array IS VARRAY(4) OF VARCHAR2(65); names_array n_array := n_array(); --call a constructor function to initialize the array is_found_rec BOOLEAN := FALSE; ex_invalid_threshold EXCEPTION; ex_invalid_arr_length EXCEPTION; IF (threshold_param < 0 OR LENGTH(TO_CHAR(threshold_param)) > 8) THEN RAISE ex_invalid_threshold; DBMS_OUTPUT.PUT_LINE('Display the names of employees who make at least $' threshold_param ' more than the employee who is paid the least in the company.'); FOR rec IN c1 LOOP is_found_rec := TRUE; arr_c := arr_c + 1; IF arr_c > 4 THEN RAISE ex_invalid_arr_length; EXIT; names_array.extend; names_array(arr_c) := rec.fname ' ' rec.lname; END LOOP; IF (is_found_rec = FALSE) THEN DBMS_OUTPUT.PUT_LINE('No Record!'); ELSE FOR i IN 1.. arr_c LOOP DBMS_OUTPUT.PUT_LINE(i '. ' names_array(i)); END LOOP; EXCEPTION WHEN ex_invalid_threshold THEN DBMS_OUTPUT.PUT_LINE('The salary threshold cannot be a negative integer and cannot be more than 8 digits!'); WHEN ex_invalid_arr_length THEN DBMS_OUTPUT.PUT_LINE('The number of returned results of names is (' arr_c ') greater than the size of the array in this procedure'); DBMS_OUTPUT.PUT_LINE('Please modify the size of the array to display the names

24 correctly!'); WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('An error was encountered - ' SQLCODE ' -ERROR- ' SQLERRM); END SHOW_NAMES_SALARY_THRESHOLD; PROCEDURE SHOW_NAMES_EM_NO_DEPENDENTS IS TYPE names_list_t IS TABLE OF VARCHAR2 (65); /*call a constructor function to initialize the nested table*/ employees names_list_t := names_list_t(); ems_w_dependent names_list_t := names_list_t(); ems_wo_dependent names_list_t := names_list_t(); CURSOR c1 IS SELECT FNAME, LNAME FROM EMPLOYEE ORDER BY FNAME; CURSOR c2 IS SELECT DISTINCT E.FNAME, E.LNAME FROM EMPLOYEE E, DEPENDENT D WHERE E.SSN = D.ESSN ORDER BY E.FNAME; is_found_rec_1 BOOLEAN := FALSE; is_found_rec_2 BOOLEAN := FALSE; count1 PLS_INTEGER := 0; count2 PLS_INTEGER := 0; DBMS_OUTPUT.PUT_LINE('Display the names of employees who have no dependents.'); FOR rec IN c1 LOOP is_found_rec_1 := TRUE; count1 := count1 + 1; employees.extend; employees(count1) := rec.fname ' ' rec.lname; END LOOP; FOR rec IN c2 LOOP is_found_rec_2 := TRUE; count2 := count2 + 1; ems_w_dependent.extend;

25 ems_w_dependent(count2) := rec.fname ' ' rec.lname; END LOOP; IF (is_found_rec_1 = FALSE) THEN DBMS_OUTPUT.PUT_LINE('No Record of Employees!'); ELSE ems_wo_dependent := employees MULTISET EXCEPT ems_w_dependent; FOR rec IN ems_wo_dependent.first.. ems_wo_dependent.last LOOP DBMS_OUTPUT.put_line (ems_wo_dependent (rec)); END LOOP; EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('An error was encountered - ' SQLCODE ' -ERROR- ' SQLERRM); END SHOW_NAMES_EM_NO_DEPENDENTS; PROCEDURE GIVE_BONUS ( w_h_threshold IN WORKS_ON.HOURS%TYPE, bonus_rate IN NUMBER, dno_param IN DEPARTMENT.DNUMBER%TYPE ) IS ex_invalid_threshold EXCEPTION; ex_invalid_bonus_rate EXCEPTION; dept_name DEPARTMENT.DNAME%TYPE; CURSOR c1 IS SELECT E.SSN, E.FNAME, E.DNO, E.SALARY,SUM(W.HOURS) FROM EMPLOYEE E, WORKS_ON W WHERE E.DNO = dno_param AND E.SSN = W.ESSN GROUP BY E.SSN, E.SALARY, E.DNO, E.FNAME HAVING SUM(HOURS) >= w_h_threshold ORDER BY E.SSN; is_found_rec BOOLEAN := FALSE; IF (w_h_threshold < 0) THEN RAISE ex_invalid_threshold;

26 IF (bonus_rate < 0 OR bonus_rate > 1) THEN RAISE ex_invalid_bonus_rate; --Get the department name for the specified department SELECT DNAME INTO dept_name FROM DEPARTMENT WHERE DNUMBER = dno_param; DBMS_OUTPUT.PUT_LINE ('Applying Bonus Rate ' bonus_rate ' to the Employees Whose Total Working Hours Are More Than Or Equal to ' w_h_threshold ' in the ' dept_name ' Department'); FOR rec IN c1 LOOP is_found_rec := TRUE; UPDATE EMPLOYEE SET SALARY = rec.salary * (1 + bonus_rate) WHERE SSN = rec.ssn; -- Check if the record was update successfully. IF SQL%ROWCOUNT = 1 THEN DBMS_OUTPUT.PUT_LINE ('The bonus was applied to ' rec.fname ' (' rec.ssn ') in the ' dept_name ' department!'); ELSE DBMS_OUTPUT.PUT_LINE ('Fail to apply bonus to ' rec.fname ' (' rec.ssn ')!'); END LOOP; IF (is_found_rec = FALSE) THEN DBMS_OUTPUT.PUT_LINE('No employee meets the requirement of giving bonous in the ' dept_name ' department with total working hours, which is ' w_h_threshold '!'); EXCEPTION WHEN ex_invalid_threshold THEN DBMS_OUTPUT.PUT_LINE('The working hours threshold cannot be a negative number!'); WHEN ex_invalid_bonus_rate THEN

27 DBMS_OUTPUT.PUT_LINE('The bonus rate cannot be less than 0 or greater than 100!'); WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE ('The department number (' dno_param ') does not exist!'); WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('An error was encountered - ' SQLCODE ' -ERROR- ' SQLERRM); END GIVE_BONUS; END COMPANY_DB; -- Trigger to display the information about CREATE and DROP events create or replace TRIGGER CREATE_DROP_TRIGGER BEFORE DDL ON SCHEMA IF ORA_SYSEVENT = 'CREATE' THEN DBMS_OUTPUT.PUT_LINE ('DDL Trigger fired: ' ORA_DICT_OBJ_OWNER ' requested to create the ' ORA_DICT_OBJ_TYPE ' named ' ORA_DICT_OBJ_NAME); ELSIF ORA_SYSEVENT = 'DROP' THEN DBMS_OUTPUT.PUT_LINE ('DDL Trigger fired: ' ORA_DICT_OBJ_OWNER ' requested to drop the ' ORA_DICT_OBJ_TYPE ' named ' ORA_DICT_OBJ_NAME); END CREATE_DROP_TRIGGER; / -- Trigger to capitalize an employee's first name and last name during the inertion create or replace TRIGGER UPPERCASE_EM_NAMES_TRIGGER BEFORE INSERT ON EMPLOYEE FOR EACH ROW DBMS_OUTPUT.PUT_LINE ('The UPPERCASE_EM_NAMES_TRIGGER fired! The first name and last name of the employee will be capitalized!'); :NEW.FNAME := UPPER(:NEW.FNAME); :NEW.LNAME := UPPER(:NEW.LNAME); END UPPERCASE_EM_NAMES_TRIGGER; / -- Trigger to check the salary change of an employee create or replace TRIGGER CHECK_SALARY_CHANGE_TRIGGER AFTER UPDATE OF SALARY ON EMPLOYEE FOR EACH ROW

28 WHEN ((OLD.SALARY IS NULL AND NEW.SALARY IS NOT NULL) OR (OLD.SALARY!= NEW.SALARY) OR (OLD.SALARY IS NOT NULL AND NEW.SALARY IS NULL)) DBMS_OUTPUT.PUT_LINE('The CHECK_SALARY_CHANGE_TRIGGER fired!'); IF (:OLD.SALARY > :NEW.SALARY) THEN DBMS_OUTPUT.PUT_LINE('The employee''s salary was lowered!'); ELSE DBMS_OUTPUT.PUT_LINE('The employee''s salary was raised!'); END CHECK_SALARY_CHANGE_TRIGGER; / -- Trigger to save employees' salary history create or replace TRIGGER SALARY_HISTORY_TRIGGER BEFORE UPDATE OF SALARY ON EMPLOYEE FOR EACH ROW WHEN ((OLD.SALARY IS NULL AND NEW.SALARY IS NOT NULL) OR (OLD.SALARY!= NEW.SALARY) OR (OLD.SALARY IS NOT NULL AND NEW.SALARY IS NULL)) DBMS_OUTPUT.PUT_LINE('The SALARY_HISTORY_TRIGGER fired!'); INSERT INTO EMPLOYEE_SALARY_HISTORY(SSN, FNAME, LNAME, SALARY, DNO, CHANGED_TIME) VALUES ( :OLD.SSN, :OLD.FNAME, :OLD.LNAME, :OLD.SALARY, :OLD.DNO, SYSTIMESTAMP ); DBMS_OUTPUT.PUT_LINE('The employee''s salary history was stored into EMPLOYEE SALARY HISTORY TABLE!'); END SALARY_HISTORY_TRIGGER; / --The following two triggers used to test the order of triggers create or replace TRIGGER ADD_WORKING_HOURS_BY_TEN BEFORE INSERT ON WORKS_ON FOR EACH ROW DBMS_OUTPUT.PUT_LINE ('The trigger ADD_WORKING_HOURS_BY_TEN fired!'); :NEW.HOURS := :NEW.HOURS + 10;

29 END ADD_WORKING_HOURS_BY_TEN; / create or replace TRIGGER ADD_WORKING_HOURS_BY_TWENTY BEFORE INSERT ON WORKS_ON FOR EACH ROW FOLLOWS ADD_WORKING_HOURS_BY_TEN -- When this clause is specified, the order can be guaranteed. DBMS_OUTPUT.PUT_LINE ('The trigger ADD_WORKING_HOURS_BY_TWENTY fired!'); IF :NEW.HOURS > 1 THEN :NEW.HOURS := :NEW.HOURS + 20; END ADD_WORKING_HOURS_BY_TWENTY; / -- Testing statemet level triggers and row level triggers on the DEPT_LOCATIONS table --Statement level trigger create or replace TRIGGER TESTING_ST_B_TGR BEFORE INSERT OR UPDATE OR DELETE ON DEPT_LOCATIONS COMPANY_DB.t_p_info_tab.extend; CASE WHEN INSERTING THEN COMPANY_DB.t_p_info_tab(COMPANY_DB.t_p_info_tab.last) := 'Statement level: Before insert'; WHEN UPDATING THEN COMPANY_DB.t_p_info_tab(COMPANY_DB.t_p_info_tab.last) := 'Statement level: Before update'; WHEN DELETING THEN COMPANY_DB.t_p_info_tab(COMPANY_DB.t_p_info_tab.last) := 'Statement level: Before delete'; END CASE; END TESTING_ST_B_TGR; / -- Statement level trigger create or replace TRIGGER TESTING_ST_A_TGR AFTER INSERT OR UPDATE OR DELETE ON DEPT_LOCATIONS COMPANY_DB.t_p_info_tab.extend; CASE WHEN INSERTING THEN COMPANY_DB.t_p_info_tab(COMPANY_DB.t_p_info_tab.last) := 'Statement level: After insert'; WHEN UPDATING THEN

30 COMPANY_DB.t_p_info_tab(COMPANY_DB.t_p_info_tab.last) := 'Statement level: After update'; WHEN DELETING THEN COMPANY_DB.t_p_info_tab(COMPANY_DB.t_p_info_tab.last) := 'Statement level: After delete'; END CASE; -- Display the elements in the collection FOR trg IN COMPANY_DB.t_p_info_tab.first.. COMPANY_DB.t_p_info_tab.last LOOP DBMS_OUTPUT.put_line(COMPANY_DB.t_p_info_tab(trg)); END LOOP; -- Empty the collection COMPANY_DB.t_p_info_tab.delete; END TESTING_ST_A_TGR; / -- Row level trigger create or replace TRIGGER TESTING_RL_B_TGR BEFORE INSERT OR UPDATE OR DELETE ON DEPT_LOCATIONS FOR EACH ROW COMPANY_DB.t_p_info_tab.extend; CASE WHEN INSERTING THEN COMPANY_DB.t_p_info_tab(COMPANY_DB.t_p_info_tab.last) := 'Row level: Before insert (NEW.DUMBER = ' :NEW.DNUMBER ', NEW.DLOCATION = ' :NEW.DLOCATION ')'; WHEN UPDATING THEN COMPANY_DB.t_p_info_tab(COMPANY_DB.t_p_info_tab.last) := 'Row level: Before update (NEW.DUMBER = ' :NEW.DNUMBER ', NEW.DLOCATION = ' :NEW.DLOCATION ')'; WHEN DELETING THEN COMPANY_DB.t_p_info_tab(COMPANY_DB.t_p_info_tab.last) := 'Row level: Before delete (OLD.DUMBER = ' :OLD.DNUMBER ', OLD.DLOCATION = ' :OLD.DLOCATION ')'; END CASE; END TESTING_RL_B_TGR; / -- Row level trigger create or replace TRIGGER TESTING_RL_A_TGR AFTER INSERT OR UPDATE OR DELETE ON DEPT_LOCATIONS FOR EACH ROW

31 COMPANY_DB.t_p_info_tab.extend; CASE WHEN INSERTING THEN COMPANY_DB.t_p_info_tab(COMPANY_DB.t_p_info_tab.last) := 'Row level: After insert (NEW.DUMBER = ' :NEW.DNUMBER ', NEW.DLOCATION = ' :NEW.DLOCATION ')'; WHEN UPDATING THEN COMPANY_DB.t_p_info_tab(COMPANY_DB.t_p_info_tab.last) := 'Row level: After update (NEW.DUMBER = ' :NEW.DNUMBER ', NEW.DLOCATION = ' :NEW.DLOCATION ')'; WHEN DELETING THEN COMPANY_DB.t_p_info_tab(COMPANY_DB.t_p_info_tab.last) := 'Row level: After delete (OLD.DUMBER = ' :OLD.DNUMBER ', OLD.DLOCATION = ' :OLD.DLOCATION ')'; END CASE; END TESTING_RL_A_TGR; / /* Trigger to delete and update a corresponding record on the DEPT_LOCATIONS, EMPLOYEE and PROJECT tables after a department is removed from the DEPARTMENT table */ create or replace TRIGGER DELETE_A_DEPARTMENT AFTER DELETE ON DEPARTMENT FOR EACH ROW DBMS_OUTPUT.PUT_LINE ('The trigger DELETE_A_DEPARTMENT fired!'); DELETE FROM DEPT_LOCATIONS WHERE DNUMBER = :OLD.DNUMBER; UPDATE EMPLOYEE SET DNO = NULL WHERE DNO = :OLD.DNUMBER; UPDATE PROJECT SET DNUM = NULL WHERE DNUM = :OLD.DNUMBER; END DELETE_A_DEPARTMENT; / /* Trigger to update a corresponding record on the DEPT_LOCATIONS, EMPLOYEE and PROJECT tables when a department number is updated on the DEPARTMENT table */ create or replace TRIGGER UPDATE_A_DEPARTMENT_NUM AFTER UPDATE OF DNUMBER ON DEPARTMENT FOR EACH ROW DBMS_OUTPUT.PUT_LINE ('The trigger UPDATE_A_DEPARTMENT_NUM fired!'); UPDATE EMPLOYEE SET DNO = :NEW.DNUMBER WHERE DNO = :OLD.DNUMBER;

32 UPDATE PROJECT SET DNUM = :NEW.DNUMBER WHERE DNUM = :OLD.DNUMBER; UPDATE DEPT_LOCATIONS SET DNUMBER = :NEW.DNUMBER WHERE DNUMBER = :OLD.DNUMBER; END UPDATE_A_DEPARTMENT_NUM; / -- A MUTATION TABLE ERROR /* Trigger to check if the new department name is duplicated on the DEPARTMENT table before updating */ create or replace TRIGGER UPDATE_A_DEPARTMENT_NAME BEFORE UPDATE OF DNAME ON DEPARTMENT FOR EACH ROW DECLARE c_num NUMBER := 0; DBMS_OUTPUT.PUT_LINE ('The trigger UPDATE_A_DEPARTMENT_NAME fired!'); SELECT COUNT(*) INTO c_num FROM DEPARTMENT WHERE DNAME = :NEW.DNAME; IF (c_num > 0) THEN RAISE_APPLICATION_ERROR(-20001, 'The department name already existed!'); END UPDATE_A_DEPARTMENT_NAME; -- Testing code SET SERVEROUTPUT ON; EXECUTE IMMEDIATE 'DROP TABLE EMPLOYEE_SALARY_HISTORY'; CREATE_ALL_TABLES; END; / POPULATE_ALL_TABLES; COMMIT; END; / INSERT_AN_EMPLOYEE('Bob', 'E', 'Johnson', ' ', ' ', '450 Stone, Houston, TX', 'M', 55000, ' ', NULL); UPDATE_AN_EMPLOYEE(3, ' '); UPDATE_AN_EMPLOYEE(3, ' '); COMPANY_DB.SHOW_DEPT_INFO_LIST_1(-1000);

33 COMPANY_DB.SHOW_DEPT_INFO_LIST_1(70000); COMPANY_DB.SHOW_DEPT_INFO_LIST_1(30000); COMPANY_DB.SHOW_LNAMES_HHSALARY_IN_DPT; COMPANY_DB.SHOW_NAMES_SSN_SSS(' '); COMPANY_DB.SHOW_NAMES_SSN_SSS(' '); COMPANY_DB.SHOW_NAMES_SSN_SSS(' '); COMPANY_DB.SHOW_NAMES_SALARY_THRESHOLD( ); COMPANY_DB.SHOW_NAMES_SALARY_THRESHOLD(40000); COMPANY_DB.SHOW_NAMES_SALARY_THRESHOLD(10000); COMPANY_DB.SHOW_NAMES_SALARY_THRESHOLD(5000); COMPANY_DB.show_names_em_no_dependents; TEST_ASSOCIATIVE_ARRAY_INDEX(150, 15000); TEST_ASSOCIATIVE_ARRAY_INDEX(1500, 15000); TEST_ASSOCIATIVE_ARRAY_INDEX(15000, 15000); EXECUTE IMMEDIATE 'CREATE TABLE EMPLOYEE_SALARY_HISTORY' ' (ID NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY,' 'SSN VARCHAR2(9) NOT NULL,' 'FNAME VARCHAR2(32),' 'LNAME VARCHAR2(32),' 'SALARY NUMBER(8),' 'DNO NUMBER(2),' 'CHANGED_TIME TIMESTAMP)'; COMPANY_DB.GIVE_BONUS(-1, 0.1, 5); COMPANY_DB.GIVE_BONUS(40, 1.1, 4); COMPANY_DB.GIVE_BONUS(40, 0.1, 2); COMPANY_DB.GIVE_BONUS(40, 0.1, 1); COMPANY_DB.GIVE_BONUS(40, 0.1, 5); COMMIT; END; / -- Testing the fired order of triggers INSERT_A_WORKS_ON(' ', 3, 1); END; /

34 INSERT_A_WORKS_ON(' ', 10, 1); END; / INSERT_A_DEPT_LOCATION(1, 'Baltimore'); INSERT_A_DEPT_LOCATION(1, 'New York'); END; / UPDATE DEPARTMENT SET DNUMBER = 3 WHERE DNUMBER = 4; DELETE FROM DEPARTMENT WHERE DNUMBER = 1; END; / Screenshots of queries results

35

36

37

38

39

40

Database design process

Database design process Database technology Lecture 2: Relational databases and SQL Jose M. Peña jose.m.pena@liu.se Database design process 1 Relational model concepts... Attributes... EMPLOYEE FNAME M LNAME SSN BDATE ADDRESS

More information

Part 1 on Table Function

Part 1 on Table Function CIS611 Lab Assignment 1 SS Chung 1. Write Table Functions 2. Automatic Creation and Maintenance of Database from Web Interface 3. Transforming a SQL Query into an Execution Plan in Relational Algebra for

More information

Session Active Databases (2+3 of 3)

Session Active Databases (2+3 of 3) INFO-H-415 - Advanced Databes Session 2+3 - Active Databes (2+3 of 3) Consider the following databe schema: DeptLocation DNumber DLocation Employee FName MInit LName SSN BDate Address Sex Salary SuperSSN

More information

CIS611 Lab Assignment 1 SS Chung

CIS611 Lab Assignment 1 SS Chung CIS611 Lab Assignment 1 SS Chung 1. Creating a Relational Database Schema from ER Diagram, Populating the Database and Querying Over the database with SQL 2. Automatic Creation and Maintenance of Database

More information

Introduction to SQL. ECE 650 Systems Programming & Engineering Duke University, Spring 2018

Introduction to SQL. ECE 650 Systems Programming & Engineering Duke University, Spring 2018 Introduction to SQL ECE 650 Systems Programming & Engineering Duke University, Spring 2018 SQL Structured Query Language Major reason for commercial success of relational DBs Became a standard for relational

More information

Overview Relational data model

Overview Relational data model Thanks to José and Vaida for most of the slides. Relational databases and MySQL Juha Takkinen juhta@ida.liu.se Outline 1. Introduction: Relational data model and SQL 2. Creating tables in Mysql 3. Simple

More information

Querying a Relational Database COMPANY database For Lab4, you use the Company database that you built in Lab2 and used for Lab3

Querying a Relational Database COMPANY database For Lab4, you use the Company database that you built in Lab2 and used for Lab3 CIS30/530 Lab Assignment SS Chung Querying a Relational Database COMPANY database For Lab, you use the Company database that you built in Lab2 and used for Lab3 1. Update the following new changes into

More information

A taxonomy of SQL queries Learning Plan

A taxonomy of SQL queries Learning Plan A taxonomy of SQL queries Learning Plan a. Simple queries: selection, projection, sorting on a simple table i. Small-large number of attributes ii. Distinct output values iii. Renaming attributes iv. Computed

More information

SQL STRUCTURED QUERY LANGUAGE

SQL STRUCTURED QUERY LANGUAGE STRUCTURED QUERY LANGUAGE SQL Structured Query Language 4.1 Introduction Originally, SQL was called SEQUEL (for Structured English QUery Language) and implemented at IBM Research as the interface for an

More information

COSC344 Database Theory and Applications. σ a= c (P) S. Lecture 4 Relational algebra. π A, P X Q. COSC344 Lecture 4 1

COSC344 Database Theory and Applications. σ a= c (P) S. Lecture 4 Relational algebra. π A, P X Q. COSC344 Lecture 4 1 COSC344 Database Theory and Applications σ a= c (P) S π A, C (H) P P X Q Lecture 4 Relational algebra COSC344 Lecture 4 1 Overview Last Lecture Relational Model This Lecture ER to Relational mapping Relational

More information

ECE 650 Systems Programming & Engineering. Spring 2018

ECE 650 Systems Programming & Engineering. Spring 2018 ECE 650 Systems Programming & Engineering Spring 2018 Introduction to SQL Tyler Bletsch Duke University Slides are adapted from Brian Rogers (Duke) Structured Query Language SQL Major reason for commercial

More information

Database Technology. Topic 3: SQL. Olaf Hartig.

Database Technology. Topic 3: SQL. Olaf Hartig. Olaf Hartig olaf.hartig@liu.se Structured Query Language Declarative language (what data to get, not how) Considered one of the major reasons for the commercial success of relational databases Statements

More information

COSC344 Database Theory and Applications. Lecture 6 SQL Data Manipulation Language (1)

COSC344 Database Theory and Applications. Lecture 6 SQL Data Manipulation Language (1) COSC344 Database Theory and Applications Lecture 6 SQL Data Manipulation Language (1) COSC344 Lecture 56 1 Overview Last Lecture SQL - DDL This Lecture SQL - DML INSERT DELETE (simple) UPDATE (simple)

More information

Chapter 8 SQL-99: Schema Definition, Basic Constraints, and Queries

Chapter 8 SQL-99: Schema Definition, Basic Constraints, and Queries Copyright 2004 Pearson Education, Inc. Chapter 8 SQL-99: Schema Definition, Basic Constraints, and Queries Copyright 2004 Pearson Education, Inc. 1 Data Definition, Constraints, and Schema Changes Used

More information

Slides by: Ms. Shree Jaswal

Slides by: Ms. Shree Jaswal Slides by: Ms. Shree Jaswal Overview of SQL, Data Definition Commands, Set operations, aggregate function, null values, Data Manipulation commands, Data Control commands, Views in SQL, Complex Retrieval

More information

Advanced Databases. Winter Term 2012/13. Prof. Dr. Dietmar Seipel University of Würzburg. Advanced Databases Winter Term 2012/13

Advanced Databases. Winter Term 2012/13. Prof. Dr. Dietmar Seipel University of Würzburg. Advanced Databases Winter Term 2012/13 Advanced Databases Winter Term 2012/13 Prof. Dr. Dietmar Seipel University of Würzburg Prof. Dr. Dietmar Seipel Minit FName LName Sex Adress Salary N WORKS_FOR 1 Name Number Locations Name SSN EMPLOYEE

More information

Database Technology. Topic 2: Relational Databases and SQL. Olaf Hartig.

Database Technology. Topic 2: Relational Databases and SQL. Olaf Hartig. Topic 2: Relational Databases and SQL Olaf Hartig olaf.hartig@liu.se Relational Data Model Recall: DB Design Process 3 Relational Model Concepts Relational database: represent data as a collection of relations

More information

L130 - DATABASE MANAGEMENT SYSTEMS LAB CYCLE-1 1) Create a table STUDENT with appropriate data types and perform the following queries.

L130 - DATABASE MANAGEMENT SYSTEMS LAB CYCLE-1 1) Create a table STUDENT with appropriate data types and perform the following queries. L130 - DATABASE MANAGEMENT SYSTEMS LAB CYCLE-1 1) Create a table STUDENT with appropriate data types and perform the following queries. Roll number, student name, date of birth, branch and year of study.

More information

SQL. Copyright 2013 Ramez Elmasri and Shamkant B. Navathe

SQL. Copyright 2013 Ramez Elmasri and Shamkant B. Navathe SQL Copyright 2013 Ramez Elmasri and Shamkant B. Navathe Data Definition, Constraints, and Schema Changes Used to CREATE, DROP, and ALTER the descriptions of the tables (relations) of a database Copyright

More information

Some different database system architectures. (a) Shared nothing architecture.

Some different database system architectures. (a) Shared nothing architecture. Figure.1 Some different database system architectures. (a) Shared nothing architecture. Computer System 1 Computer System CPU DB CPU DB MEMORY MEMORY Switch Computer System n CPU DB MEMORY Figure.1 continued.

More information

COSC Assignment 2

COSC Assignment 2 COSC 344 Overview In this assignment, you will turn your miniworld into a set of Oracle tables, normalize your design, and populate your database. Due date for assignment 2 Friday, 25 August 2017 at 4

More information

Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification

Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification Chapter 5 Outline More Complex SQL Retrieval

More information

Translation of ER-diagram into Relational Schema. Dr. Sunnie S. Chung CIS430/530

Translation of ER-diagram into Relational Schema. Dr. Sunnie S. Chung CIS430/530 Translation of ER-diagram into Relational Schema Dr. Sunnie S. Chung CIS430/530 Learning Objectives Define each of the following database terms 9.2 Relation Primary key Foreign key Referential integrity

More information

Chapter 8. Joined Relations. Joined Relations. SQL-99: Schema Definition, Basic Constraints, and Queries

Chapter 8. Joined Relations. Joined Relations. SQL-99: Schema Definition, Basic Constraints, and Queries Copyright 2004 Pearson Education, Inc. Chapter 8 SQL-99: Schema Definition, Basic Constraints, and Queries Joined Relations Can specify a "joined relation" in the FROM-clause Looks like any other relation

More information

SQL-99: Schema Definition, Basic Constraints, and Queries. Create, drop, alter Features Added in SQL2 and SQL-99

SQL-99: Schema Definition, Basic Constraints, and Queries. Create, drop, alter Features Added in SQL2 and SQL-99 SQL-99: Schema Definition, Basic Constraints, and Queries Content Data Definition Language Create, drop, alter Features Added in SQL2 and SQL-99 Basic Structure and retrieval queries in SQL Set Operations

More information

Data Definition Language (DDL)

Data Definition Language (DDL) Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Database Lab (ECOM 4113) Lab 6 Data Definition Language (DDL) Eng. Mohammed Alokshiya November 11, 2014 Database Keys A key

More information

Chapter 4. Basic SQL. SQL Data Definition and Data Types. Basic SQL. SQL language SQL. Terminology: CREATE statement

Chapter 4. Basic SQL. SQL Data Definition and Data Types. Basic SQL. SQL language SQL. Terminology: CREATE statement Chapter 4 Basic SQL Basic SQL SQL language Considered one of the major reasons for the commercial success of relational databases SQL Structured Query Language Statements for data definitions, queries,

More information

SQL: A COMMERCIAL DATABASE LANGUAGE. Data Change Statements,

SQL: A COMMERCIAL DATABASE LANGUAGE. Data Change Statements, SQL: A COMMERCIAL DATABASE LANGUAGE Data Change Statements, Outline 1. Introduction 2. Data Definition, Basic Constraints, and Schema Changes 3. Basic Queries 4. More complex Queries 5. Aggregate Functions

More information

Query 2: Pnumber Dnum Lname Address Bdate 10 4 Wallace 291 Berry, Bellaire, TX Wallace 291 Berry, Bellaire, TX

Query 2: Pnumber Dnum Lname Address Bdate 10 4 Wallace 291 Berry, Bellaire, TX Wallace 291 Berry, Bellaire, TX 5.11 No violation, integrity is retained. Dnum = 2 does not exist. This can be solved by adding a foreign key referencing the department table, so the operation does not execute. Dnum = 4 already exists,

More information

ECE 650 Systems Programming & Engineering. Spring 2018

ECE 650 Systems Programming & Engineering. Spring 2018 ECE 650 Systems Programming & Engineering Spring 2018 Relational Databases: Tuples, Tables, Schemas, Relational Algebra Tyler Bletsch Duke University Slides are adapted from Brian Rogers (Duke) Overview

More information

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe CHAPTER 6 Basic SQL Slide 6-2 Chapter 6 Outline SQL Data Definition and Data Types Specifying Constraints in SQL Basic Retrieval Queries in SQL INSERT, DELETE, and UPDATE Statements in SQL Additional Features

More information

SQL: A COMMERCIAL DATABASE LANGUAGE. Complex Constraints

SQL: A COMMERCIAL DATABASE LANGUAGE. Complex Constraints SQL: A COMMERCIAL DATABASE LANGUAGE Complex Constraints Outline 1. Introduction 2. Data Definition, Basic Constraints, and Schema Changes 3. Basic Queries 4. More complex Queries 5. Aggregate Functions

More information

More SQL: Complex Queries, Triggers, Views, and Schema Modification

More SQL: Complex Queries, Triggers, Views, and Schema Modification Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 Outline More Complex SQL Retrieval Queries

More information

Translation of ER-diagram into Relational Schema. Dr. Sunnie S. Chung CIS430/530

Translation of ER-diagram into Relational Schema. Dr. Sunnie S. Chung CIS430/530 Translation of ER-diagram into Relational Schema Dr. Sunnie S. Chung CIS430/530 Learning Objectives Define each of the following database terms 9.2 Relation Primary key Foreign key Referential integrity

More information

Guides for Installing MS SQL Server and Creating Your First Database. Please see more guidelines on installing procedure on the class webpage

Guides for Installing MS SQL Server and Creating Your First Database. Please see more guidelines on installing procedure on the class webpage Guides for Installing MS SQL Server and Creating Your First Database Installing process Please see more guidelines on installing procedure on the class webpage 1. Make sure that you install a server with

More information

CS 348 Introduction to Database Management Assignment 2

CS 348 Introduction to Database Management Assignment 2 CS 348 Introduction to Database Management Assignment 2 Due: 30 October 2012 9:00AM Returned: 8 November 2012 Appeal deadline: One week after return Lead TA: Jiewen Wu Submission Instructions: By the indicated

More information

More SQL: Complex Queries, Triggers, Views, and Schema Modification

More SQL: Complex Queries, Triggers, Views, and Schema Modification Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 Outline More Complex SQL Retrieval Queries

More information

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe CHAPTER 7 More SQL: Complex Queries, Triggers, Views, and Schema Modification Slide 7-2 Chapter 7 Outline More Complex SQL Retrieval Queries Specifying Semantic Constraints as Assertions and Actions as

More information

SQL Introduction. CS 377: Database Systems

SQL Introduction. CS 377: Database Systems SQL Introduction CS 377: Database Systems Recap: Last Two Weeks Requirement analysis Conceptual design Logical design Physical dependence Requirement specification Conceptual data model (ER Model) Representation

More information

CSC 742 Database Management Systems

CSC 742 Database Management Systems CSC 742 Database Management Systems Topic #16: Query Optimization Spring 2002 CSC 742: DBMS by Dr. Peng Ning 1 Agenda Typical steps of query processing Two main techniques for query optimization Heuristics

More information

COSC344 Database Theory and Applications. Lecture 5 SQL - Data Definition Language. COSC344 Lecture 5 1

COSC344 Database Theory and Applications. Lecture 5 SQL - Data Definition Language. COSC344 Lecture 5 1 COSC344 Database Theory and Applications Lecture 5 SQL - Data Definition Language COSC344 Lecture 5 1 Overview Last Lecture Relational algebra This Lecture Relational algebra (continued) SQL - DDL CREATE

More information

SQL: Advanced Queries, Assertions, Triggers, and Views. Copyright 2012 Ramez Elmasri and Shamkant B. Navathe

SQL: Advanced Queries, Assertions, Triggers, and Views. Copyright 2012 Ramez Elmasri and Shamkant B. Navathe SQL: Advanced Queries, Assertions, Triggers, and Views Copyright 2012 Ramez Elmasri and Shamkant B. Navathe NULLS IN SQL QUERIES SQL allows queries that check if a value is NULL (missing or undefined or

More information

Chapter 19 Query Optimization

Chapter 19 Query Optimization Chapter 19 Query Optimization It is an activity conducted by the query optimizer to select the best available strategy for executing the query. 1. Query Trees and Heuristics for Query Optimization - Apply

More information

More SQL: Complex Queries, Triggers, Views, and Schema Modification

More SQL: Complex Queries, Triggers, Views, and Schema Modification Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 Outline More Complex SQL Retrieval Queries

More information

Outline. Textbook Chapter 6. Note 1. CSIE30600/CSIEB0290 Database Systems Basic SQL 2

Outline. Textbook Chapter 6. Note 1. CSIE30600/CSIEB0290 Database Systems Basic SQL 2 Outline SQL Data Definition and Data Types Specifying Constraints in SQL Basic Retrieval Queries in SQL INSERT, DELETE, and UPDATE Statements in SQL Additional Features of SQL Textbook Chapter 6 CSIE30600/CSIEB0290

More information

COSC344 Database Theory and Applications. Lecture 11 Triggers

COSC344 Database Theory and Applications. Lecture 11 Triggers COSC344 Database Theory and Applications Lecture 11 Triggers COSC344 Lecture 11 1 Overview Last Lecture - PL/SQL This Lecture - Triggers - Source: Lecture notes, Oracle documentation Next Lecture - Java

More information

Dr. Anis Koubaa. Advanced Databases SE487. Prince Sultan University

Dr. Anis Koubaa. Advanced Databases SE487. Prince Sultan University Advanced Databases Prince Sultan University College of Computer and Information Sciences Fall 2013 Chapter 15 Basics of Functional Dependencies and Normalization for Relational Databases Anis Koubaa SE487

More information

SQL- Updates, Asser0ons and Views

SQL- Updates, Asser0ons and Views SQL- Updates, Asser0ons and Views Data Defini0on, Constraints, and Schema Changes Used to CREATE, DROP, and ALTER the descrip0ons of the tables (rela0ons) of a database CREATE TABLE In SQL2, can use the

More information

DBMS LAB SESSION PAVANKUMAR MP

DBMS LAB SESSION PAVANKUMAR MP DBMS LAB SESSION Pavan Kumar M.P B.E,M.Sc(Tech) by Research,(Ph.D) Assistant Professor Dept of ISE J.N.N.College Of Engineering Shimoga http://pavankumarjnnce.blogspot.in Consider the schema for Company

More information

Basic SQL II. Dr Fawaz Alarfaj. ACKNOWLEDGEMENT Slides are adopted from: Elmasri & Navathe, Fundamentals of Database Systems MySQL Documentation

Basic SQL II. Dr Fawaz Alarfaj. ACKNOWLEDGEMENT Slides are adopted from: Elmasri & Navathe, Fundamentals of Database Systems MySQL Documentation Basic SQL II Dr Fawaz Alarfaj Al Imam Mohammed Ibn Saud Islamic University ACKNOWLEDGEMENT Slides are adopted from: Elmasri & Navathe, Fundamentals of Database Systems MySQL Documentation Lab 1 Review

More information

Announcement5 SQL5. Create%and%drop%table5. Basic%SFW%query5. Reading%a%table5. TDDD37%% Database%technology% SQL5

Announcement5 SQL5. Create%and%drop%table5. Basic%SFW%query5. Reading%a%table5. TDDD37%% Database%technology% SQL5 Announcement %% Database%technology% SQL Fang%Wei9Kleiner fang.wei9kleiner@liu.se hbp://www.ida.liu.se/~ Course%registration:%system%problems%from%registration% office.%be%patient. Registration%for%the%lab:%possible%without%being%

More information

CSIE30600 Database Systems Basic SQL 2. Outline

CSIE30600 Database Systems Basic SQL 2. Outline Outline SQL Data Definition and Data Types Specifying Constraints in SQL Basic Retrieval Queries in SQL INSERT, DELETE, and UPDATE Statements in SQL Additional Features of SQL CSIE30600 Database Systems

More information

SQL (Structured Query Language) Truong Tuan Anh CSE-HCMUT

SQL (Structured Query Language) Truong Tuan Anh CSE-HCMUT SQL (Structured Query Language) Truong Tuan Anh CSE-HCMUT Contents 1 The COMPANY Database 2 SQL developments: an overview 3 DDL: Create, Alter, Drop 4 DML: select, insert, update, delete 5 Triggers The

More information

Chapter 4. Basic SQL. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 4. Basic SQL. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 Basic SQL Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 Outline SQL Data Definition and Data Types Specifying Constraints in SQL Basic Retrieval Queries

More information

SQL (Structured Query Language) Truong Tuan Anh CSE-HCMUT

SQL (Structured Query Language) Truong Tuan Anh CSE-HCMUT SQL (Structured Query Language) Truong Tuan Anh CSE-HCMUT Contents 1 The COMPANY Database 2 SQL developments: an overview 3 DDL: Create, Alter, Drop 4 DML: select, insert, update, delete 5 Triggers The

More information

DATABASE CONCEPTS. Dr. Awad Khalil Computer Science & Engineering Department AUC

DATABASE CONCEPTS. Dr. Awad Khalil Computer Science & Engineering Department AUC DATABASE CONCEPTS Dr. Awad Khalil Computer Science & Engineering Department AUC s are considered as major components in almost all recent computer application systems, including business, management, engineering,

More information

DEPARTMENT DNAME DNUMBER MGRNAME MGRSTARTDATE

DEPARTMENT DNAME DNUMBER MGRNAME MGRSTARTDATE Figure D.1 A hierarchical schema. DEPARTMENT DNAME DNUMBER MGRNAME MGRSTARTDATE NAME SSN BDATE ADDRESS PNAME PNUMBER PLOCATION Figure D.2 Occurrences of Parent-Child Relationships. (a) Two occurrences

More information

Database Management System (15ECSC208) UNIT I: Chapter 2: Relational Data Model and Relational Algebra

Database Management System (15ECSC208) UNIT I: Chapter 2: Relational Data Model and Relational Algebra Database Management System (15ECSC208) UNIT I: Chapter 2: Relational Data Model and Relational Algebra Relational Data Model and Relational Constraints Part 1 A simplified diagram to illustrate the main

More information

ORACLE: PL/SQL Programming

ORACLE: PL/SQL Programming %ROWTYPE Attribute... 4:23 %ROWTYPE... 2:6 %TYPE... 2:6 %TYPE Attribute... 4:22 A Actual Parameters... 9:7 Actual versus Formal Parameters... 9:7 Aliases... 8:10 Anonymous Blocks... 3:1 Assigning Collection

More information

Relational Model. CS 377: Database Systems

Relational Model. CS 377: Database Systems Relational Model CS 377: Database Systems ER Model: Recap Recap: Conceptual Models A high-level description of the database Sufficiently precise that technical people can understand it But, not so precise

More information

Relational Algebra 1

Relational Algebra 1 Relational Algebra 1 Motivation The relational data model provides a means of defining the database structure and constraints NAME SALARY ADDRESS DEPT Smith 50k St. Lucia Printing Dilbert 40k Taringa Printing

More information

Relational Calculus: 1

Relational Calculus: 1 CSC 742 Database Management Systems Topic #8: Relational Calculus Spring 2002 CSC 742: DBMS by Dr. Peng Ning 1 Relational Calculus: 1 Can define the information to be retrieved not any specific series

More information

Chapter 3. Algorithms for Query Processing and Optimization

Chapter 3. Algorithms for Query Processing and Optimization Chapter 3 Algorithms for Query Processing and Optimization Chapter Outline 1. Introduction to Query Processing 2. Translating SQL Queries into Relational Algebra 3. Algorithms for External Sorting 4. Algorithms

More information

Slides by: Ms. Shree Jaswal

Slides by: Ms. Shree Jaswal Slides by: Ms. Shree Jaswal A trigger is a statement that is executed automatically by the system as a side effect of a modification to the database. To design a trigger mechanism, we must: Specify the

More information

Advanced Databases (SE487) Prince Sultan University College of Computer and Information Sciences

Advanced Databases (SE487) Prince Sultan University College of Computer and Information Sciences Advanced Databases (SE487) Prince Sultan University College of Computer and Information Sciences ER to Relational Mapping Anis Koubaa Chapter 9 Outline } Relational Database Design Using ER-to-Relational

More information

Course Notes on Relational Algebra

Course Notes on Relational Algebra Course Notes on Relational Algebra What is the Relational Algebra? Relational Algebra: Summary Operators Selection Projection Union, Intersection, Difference Cartesian Product Join Division Equivalences

More information

Database Programming with PL/SQL

Database Programming with PL/SQL Database Programming with PL/SQL Trapping Oracle Server Exceptions 1 Copyright 2013, Oracle and/or its affiliates. All rights Objectives This lesson covers the following objectives: Describe and provide

More information

CS5300 Database Systems

CS5300 Database Systems CS5300 Database Systems Views A.R. Hurson 323 CS Building hurson@mst.edu Note, this unit will be covered in two lectures. In case you finish it earlier, then you have the following options: 1) Take the

More information

The Relational Data Model and Relational Database Constraints

The Relational Data Model and Relational Database Constraints The Relational Data Model and Relational Database Constraints First introduced by Ted Codd from IBM Research in 1970, seminal paper, which introduced the Relational Model of Data representation. It is

More information

Relational Database Systems Part 01. Karine Reis Ferreira

Relational Database Systems Part 01. Karine Reis Ferreira Relational Database Systems Part 01 Karine Reis Ferreira karine@dpi.inpe.br Aula da disciplina Computação Aplicada I (CAP 241) 2016 Database System Database: is a collection of related data. represents

More information

Ref1 for STUDENT RECORD DB: Ref2 for COMPANY DB:

Ref1 for STUDENT RECORD DB: Ref2 for COMPANY DB: Lect#5: SQL Ref1 for STUDENT RECORD DB: Database Design and Implementation Edward Sciore, Boston College ISBN: 978-0-471-75716-0 Ref2 for COMPANY DB: Fund. of Database Systems, Elmasri, Navathe, 5th ed.,

More information

In Chapters 3 through 6, we presented various aspects

In Chapters 3 through 6, we presented various aspects 15 chapter Basics of Functional Dependencies and Normalization for Relational Databases In Chapters 3 through 6, we presented various aspects of the relational model and the languages associated with it.

More information

Algorithms for Query Processing and Optimization. 0. Introduction to Query Processing (1)

Algorithms for Query Processing and Optimization. 0. Introduction to Query Processing (1) Chapter 19 Algorithms for Query Processing and Optimization 0. Introduction to Query Processing (1) Query optimization: The process of choosing a suitable execution strategy for processing a query. Two

More information

Chapter 8: Relational Algebra

Chapter 8: Relational Algebra Chapter 8: elational Algebra Outline: Introduction Unary elational Operations. Select Operator (σ) Project Operator (π) ename Operator (ρ) Assignment Operator ( ) Binary elational Operations. Set Operators

More information

Chapter 6: RELATIONAL DATA MODEL AND RELATIONAL ALGEBRA

Chapter 6: RELATIONAL DATA MODEL AND RELATIONAL ALGEBRA Chapter 6: Relational Data Model and Relational Algebra 1 Chapter 6: RELATIONAL DATA MODEL AND RELATIONAL ALGEBRA RELATIONAL MODEL CONCEPTS The relational model represents the database as a collection

More information

Data Manipulation Language (DML)

Data Manipulation Language (DML) In the name of Allah Islamic University of Gaza Faculty of Engineering Computer Engineering Department ECOM 4113 DataBase Lab Lab # 3 Data Manipulation Language (DML) El-masry 2013 Objective To be familiar

More information

Basic SQL. Dr Fawaz Alarfaj. ACKNOWLEDGEMENT Slides are adopted from: Elmasri & Navathe, Fundamentals of Database Systems MySQL Documentation

Basic SQL. Dr Fawaz Alarfaj. ACKNOWLEDGEMENT Slides are adopted from: Elmasri & Navathe, Fundamentals of Database Systems MySQL Documentation Basic SQL Dr Fawaz Alarfaj Al Imam Mohammed Ibn Saud Islamic University ACKNOWLEDGEMENT Slides are adopted from: Elmasri & Navathe, Fundamentals of Database Systems MySQL Documentation MIDTERM EXAM 2 Basic

More information

COSC 304 Introduction to Database Systems SQL DDL. Dr. Ramon Lawrence University of British Columbia Okanagan

COSC 304 Introduction to Database Systems SQL DDL. Dr. Ramon Lawrence University of British Columbia Okanagan COSC 304 Introduction to Database Systems SQL DDL Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca SQL Overview Structured Query Language or SQL is the standard query language

More information

UNIT-V SQL Explain insert, delete and update statements in SQL with example.

UNIT-V SQL Explain insert, delete and update statements in SQL with example. UNIT-V SQL 2 1. Explain insert, delete and update statements in SQL with example. 8 Marks (Dec/Jan 2013 & June/July 2015) The Insert Operation This operation can violate all constraints in a relational

More information

Integrity Coded Relational Databases (ICRDB) - Protecting Data Integrity in Clouds

Integrity Coded Relational Databases (ICRDB) - Protecting Data Integrity in Clouds Integrity Coded Relational Databases (ICRDB) - Protecting Data Integrity in Clouds Jyh-haw Yeh Dept. of Computer Science, Boise State University, Boise, Idaho 83725, USA Abstract 1 Introduction Database-as-a-service

More information

Outline. Note 1. CSIE30600 Database Systems More SQL 2

Outline. Note 1. CSIE30600 Database Systems More SQL 2 Outline More Complex SQL Retrieval Queries Specifying Constraints as Assertions and Actions as Triggers Views (Virtual Tables) in SQL Schema Change Statements in SQL CSIE30600 Database Systems More SQL

More information

Simple SQL Queries (contd.)

Simple SQL Queries (contd.) Simple SQL Queries (contd.) Example of a simple query on one relation Query 0: Retrieve the birthdate and address of the employee whose name is 'John B. Smith'. Q0: SELECT BDATE, ADDRESS FROM EMPLOYEE

More information

CSEN 501 CSEN501 - Databases I

CSEN 501 CSEN501 - Databases I CSEN501 - Databases I Lecture 5: Structured Query Language (SQL) Prof. Dr. Slim slim.abdennadher@guc.edu.eg German University Cairo, Faculty of Media Engineering and Technology Structured Query Language:

More information

Course Notes on From Entity-Relationship Schemas to Relational Schemas

Course Notes on From Entity-Relationship Schemas to Relational Schemas Course Notes on From Entity-Relationship Schemas to Relational Schemas The chapter deals with practical database design: the construction of a relational schema from an E-R schema this stage of database

More information

DATA AND SCHEMA MODIFICATIONS CHAPTERS 4,5 (6/E) CHAPTER 8 (5/E)

DATA AND SCHEMA MODIFICATIONS CHAPTERS 4,5 (6/E) CHAPTER 8 (5/E) 1 DATA AND SCHEMA MODIFICATIONS CHAPTERS 4,5 (6/E) CHAPTER 8 (5/E) 2 LECTURE OUTLINE Updating Databases Using SQL Specifying Constraints as Assertions and Actions as Triggers Schema Change Statements in

More information

COSC 304 Introduction to Database Systems SQL. Dr. Ramon Lawrence University of British Columbia Okanagan

COSC 304 Introduction to Database Systems SQL. Dr. Ramon Lawrence University of British Columbia Okanagan COSC 304 Introduction to Database Systems SQL Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca SQL Queries Querying with SQL is performed using a SELECT statement. The general

More information

SQL Queries. COSC 304 Introduction to Database Systems SQL. Example Relations. SQL and Relational Algebra. Example Relation Instances

SQL Queries. COSC 304 Introduction to Database Systems SQL. Example Relations. SQL and Relational Algebra. Example Relation Instances COSC 304 Introduction to Database Systems SQL Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca SQL Queries Querying with SQL is performed using a SELECT statement. The general

More information

Introduction to Computer Science and Business

Introduction to Computer Science and Business Introduction to Computer Science and Business The Database Programming with PL/SQL course introduces students to the procedural language used to extend SQL in a programatic manner. This course outline

More information

Information Systems Development 37C Lecture: Final notes. 30 th March 2017 Dr. Riitta Hekkala

Information Systems Development 37C Lecture: Final notes. 30 th March 2017 Dr. Riitta Hekkala Information Systems Development 37C00200 Lecture: Final notes 30 th March 2017 Dr. Riitta Hekkala The course should have given you Introduction to the information system development process Understanding

More information

PL/SQL. Exception. When the PL/SQL engine cannot execute the PLSQL block it raise an error. Every Oracle error has an error number

PL/SQL. Exception. When the PL/SQL engine cannot execute the PLSQL block it raise an error. Every Oracle error has an error number PL/SQL Exception When the PL/SQL engine cannot execute the PLSQL block it raise an error. Every Oracle error has an error number Exceptions must be handled by name. PL/SQL predefines some common Oracle

More information

CS 338 Basic SQL Part II

CS 338 Basic SQL Part II CS 338 Basic SQL Part II Bojana Bislimovska Spring 2017 Major research Outline Basic Retrieval Queries Exercises Ambiguous Attribute Names Major research Same name can be used for two or more attributes

More information

Homework #4 1. Suppose that each of the following Update operations is applied directly to the database state shown in Figure 5.6.

Homework #4 1. Suppose that each of the following Update operations is applied directly to the database state shown in Figure 5.6. Homework #4 1. Suppose that each of the following Update operations is applied directly to the database state shown in Figure 5.6. Discuss all integrity constraints violated by each operation, if any,

More information

RELATIONAL DATA MODEL

RELATIONAL DATA MODEL RELATIONAL DATA MODEL 3.1 Introduction The relational model of data was introduced by Codd (1970). It is based on a simple and uniform data structure - the relation - and has a solid theoretical and mathematical

More information

Section I : Section II : Question 1. Question 2. Question 3.

Section I : Section II : Question 1. Question 2. Question 3. Computer Science, 60-415 Midterm Examiner: Ritu Chaturvedi Date: Oct. 27 th, 2011 Student Name: Student Number: INSTRUCTIONS (Please Read Carefully) Examination Period is 1 hour and 15 minutes Answer all

More information

Procedural Language Structured Query Language (PL/SQL)

Procedural Language Structured Query Language (PL/SQL) The Islamic University of Gaza Faculty of Engineering Dept. of Computer Engineering Database Lab (ECOM 4113) Lab 7 Procedural Language Structured Query Language (PL/SQL) Eng. Ibraheem Lubbad Structured

More information

Lecture 08. Spring 2018 Borough of Manhattan Community College

Lecture 08. Spring 2018 Borough of Manhattan Community College Lecture 08 Spring 2018 Borough of Manhattan Community College 1 The SQL Programming Language Recent versions of the SQL standard allow SQL to be embedded in high-level programming languages to help develop

More information

Introduction to Query Processing and Query Optimization Techniques. Copyright 2011 Ramez Elmasri and Shamkant Navathe

Introduction to Query Processing and Query Optimization Techniques. Copyright 2011 Ramez Elmasri and Shamkant Navathe Introduction to Query Processing and Query Optimization Techniques Outline Translating SQL Queries into Relational Algebra Algorithms for External Sorting Algorithms for SELECT and JOIN Operations Algorithms

More information

Assertions, Views, and Programming. CS157A Chris Pollett Oct. 31, 2005.

Assertions, Views, and Programming. CS157A Chris Pollett Oct. 31, 2005. Assertions, Views, and Programming CS157A Chris Pollett Oct. 31, 2005. Outline Assertions Views Database Programming Assertions It is useful to be able to specify general constraints in SQL -- i.e., other

More information

Structured Query Language (SQL)

Structured Query Language (SQL) Structured Query Language (SQL) SQL Chapters 6 & 7 (7 th edition) Chapters 4 & 5 (6 th edition) PostgreSQL on acsmysql1.acs.uwinnipeg.ca Each student has a userid and initial password acs!

More information