Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

Working with Constraints

At the end of this exercise, the student may able to:

1. Load text file to a table.


2. Set foreign key to a table.
3. Test how REFERENCE works.
4. Test ON DELETE RESTRICT and ON DELETE CASCADE work.

Load text file to a table

One of the objectives of this activity is to set a database and create tables. Below is the entity
relationship diagram (ERD) of the tables we will create on a database. The name of the
company that we will set up with a database is Hope, Incorporated.

Let us drop existing tables (if there is any from our schema):

DROP TABLE employee;


DROP TABLE jobHistory;
DROP TABLE job;
DROP TABLE department;
Re-create table employee (just copy, paste and run):

CREATE TABLE employee (empNo VARCHAR(5) NOT NULL PRIMARY KEY,


lastName VARCHAR(15),
firstName VARCHAR(15),
gender CHAR(1) ,
birthDate DATE,
hireDate DATE,
sepDate DATE) ORGANIZE BY ROW;

Download ​EMPFILE.CSV​.

Open the file with Notepad. The content of the file is separated by a comma(comma-separated
values). Do not alter nor save the file.

Load text(csv) file to EMPLOYEE table.

Click ​LOAD | Load Data


Make sure that the ​My Computer​ is selected. Click ​browse Files​.

Select your download file EMPFILE.CSV. Click​ Next​ button from the right corner of LOAD DATA
interface.

Select the your schema set to your database. In the example, it is XKLO6953:
Select EMPLOYEE table that you have just created:

Click ​Next​ button.

Since we have created EMPLOYEE table before appending the file, column names were already
set. The EMPFILE has no header row (column names) --- it is just pure comma-separated data.

Click ​Header in first row​. This must be UNCHECKED. Make sure that the first row is SMITH,
JOHN and not SMITH, JANE.

Click ​Next​ button.


Click ​Begin Load​ button.

You should have the following screen in loading 32 rows to your table:

Go back on your RUNSQL interface editor and check if you have the loaded date by executing:

SELECT * FROM employee;

Let us apply constraint to our table. Copy, paste and run:

ALTER TABLE employee


ADD CONSTRAINT GENDER_CK CHECK (GENDER IN ('M','F')) ENFORCED;

CALL SYSPROC.ADMIN_CMD ('REORG TABLE employee');


Load text file with header rows

Open an EXCEL spreadsheet and type the following. Note: MAKE SURE YOU TYPE CORRECTLY.
iF IT IS IN UPPER CASE, TYPE IN UPPERCASE. NO EXTRA SPACES in deptCode values. You will get
a problem retrieving a file later if you will not follow:

Follow the saving procedure.

Click File | Save As | This PC | My Documents:

Save it as DEPFILE.CSV. Check if commas were inserted in the file. Open the file with Notepad.
You should have the following data inside the DEPFILE.CSV:

Let us create DEPARTMENT table on our schema.

Click ​LOAD | Load Data​ in DB2 Cloud:

Click ​Load More​ Data:

Click ​browse files​ and select ​DEPFILE.CSV​ in your ​My Documents​ folder:
Click ​Next​ button.

Select your schema. In the example the schema is XKLO6953:

Click ​New Table​:


Supply DEPARTMENT as table name. Click ​Create​ button

Click ​Next​ button:

You should have the following screen:

Click Next | Begin Load.


You must successfully load 8 rows from the file.

Click ​View Table​ to check the loaded data.

Go to ​RUNSQL​ interface.

Let us alter the DEPARTMENT table and apply constraints.

Copy, paste, and run:

ALTER TABLE department


ALTER COLUMN deptCode
SET NOT NULL;

CALL SYSPROC.ADMIN_CMD ('REORG TABLE department ');

ALTER TABLE department


ADD CONSTRAINT deptCode_pk PRIMARY KEY (deptCode ) ENFORCED;
CALL SYSPROC.ADMIN_CMD ('REORG TABLE department ');

ALTER TABLE department


ALTER COLUMN department
SET DATA TYPE VARCHAR(20);

CALL SYSPROC.ADMIN_CMD ('REORG TABLE department ');

Check the structure of the table. Copy, paste, run:

CALL SYSPROC.ADMIN_CMD ('DESCRIBE TABLE department ');

You should have the following output:

Let us check if the PRIMARY KEY constraint is working.

Copy, paste, and run:

INSERT INTO department


VALUES ('ACT', 'Accounting 2')

You should have the following error message because ACT is already existing at DEPARTMENT
table:
Check if DEPARTMENT column accepts more than 20 characters

INSERT INTO department


VALUES ('CCS', 'College of Computer Studies')

You should have the following error message:

Do the same with JOB table.


Type the following script:

Load the data from ​JOBFILE.CSV​.

At the end of the loading stage you should have the following data from JOB table:
Create composite and foreign keys

Create the jobHistory table. Thus, we define:

empNo, jobCode, effDate are set as primary key. More than one column set as primary key is
called ​composite key​. ​Primary key should not contain blank value that is why we indicate the
NOT NULL expression​.

Cross-REFERENCE empno and jobCode to employee and job tables respectively.

Type the following script:

All values that entered at ​empNo and ​jobCode are cross REFERENCE​d with employee and job
tables. The set up increases the referential integrity of the table which means no value will be
entered unless it exists on the two tables.
Alter again the table. Type the following scripts:

Salary​ has DECIMAL data type which has a size of 10 digits with 2 decimal point numbers based
on the CREATE TABLE definition. It has a CONSTRAINT with a name of ​salary_ck​. Only salary
with values greater or equal to 0.0 are accepted.

effDate has DATE data type. This monitors the effectivity date of the position on the job history
table.

deptCode is set as FOREIGN KEY. We limit the entry on deptCode column which has
REFERENCEd with department table. ​Foreign key is non-key or not primary key on one table
but primary key in another table. On our case, deptCode is foreign key but referenced with
department table which has its own deptCode set as primary key.

Check the structure of the table. You should have the following result:
Validate input row with constraints set
Let us check if our set constraints are working. Insert the following row:

We have the following error:

Let us check if empno = '00096 is existent in EMPLOYEE TABLE:

SELECT empno FROM employee


WHERE empno BETWEEN '00050' AND '00100';

There is no empNo 00096 in the employees table:


Check if there is PR3 in job:

SELECT * FROM job;

There is no PR3 in job:

Check if there is ITC in department table:

SELECT * FROM department;


There is no ITC in department table.

Notice on the above insert 00096, PR3, and ITC were non-existent at ​employee, job, and
department ​tables. j​obHistory columns are cross-REFERENCEd with these tables. Any value
not included on these referenced tables will be not accepted as an entry at jobHistory.

Since the jobHistory entry is intended for John Smith who works as Programmer 2 at IT
department, let us correct our insert table with the following script:
We have the following error:

Salary_ck is the constraint name we have set before to check if value correspond with the
range (negative values are not accepted). Remove the negative sign for the salary and re-enter
the script.

On​ ​Delete Restrict

Insert the following rows. Copy, paste and run:

INSERT INTO jobHistory


VALUES ('00003', 'PR2', '2010-05-11', 50000, 'IT'),
('00003', 'ANYS', '2010-12-01', 55000, 'IT'),
('00005', 'SA1', '2010-06-23', 36000, 'BR1'),
('00015', 'SA1', '2010-07-05', 36000, 'BR1');

Check the content of the table:

Try to delete empNo 00003 from employee table:

DELETE employee
WHERE empNo = '00003';

You can not just delete empNo 00003 from ​employee​ table because it is existing in ​jobHistory
table. You have the following error message:

This is the effect of​ ON DELETE RESTRICT​ that you have set in​ jobHistory​ when you altered the
table and specify a constraint.
But how do I delete employee 00003 from ​employee​ table if I want it to be removed totally
from employee table?

You need to delete first in ​jobHistory​ before you delete in​ employee​ table.

Copy, paste and run:

DELETE jobHistory
WHERE empNo = '00003';

DELETE employee
WHERE empNo = '00003';

SELECT * FROM jobHistory;

SELECT * FROM employee


WHERE empNo BETWEEN '00001' AND '00019';

This is now the content of your jobHistory table

This is now the content of your employee table:


On Delete Cascade

Take note of the following content of jobHistory and job tables:


What if I delete jobCode SA1 in job table? What will happen to SA1 job codes in jobHistory
table?

Copy, paste, and run the following scripts:

DELETE job
WHERE jobCode = 'SA1';

SELECT * FROM job;

SELECT * FROM jobHistory;


This is the updated content of ​job​:

This is the updated content of​ jobHistory​:

Deleting a row in the parent table job would mean automatic deletion in dependent table
jobHistory. The deletion were cascaded to the dependant table. This is the effect of​ ON
DELETE CASCAD​E on​ jobHistory​ table when you altered the table and specify a constraint.

You might also like