Professional Documents
Culture Documents
After completing this module, you will be able to: Describe the concept and benefits of referential integrity. Explain the concepts behind relationships that occur among tables. Use the INSERT and UPDATE statements to make changes to a table that has references to other tables. Describe the access rights you need to create and replace triggers.
Referential Integrity
Reasons to implement RI Data integrity and consistency Increases development productivity users dont have to code SQL statements to enforce referential constraints Optimized performance Teradata chooses the most efficient method to enforce the referential constraints User applications may rely on Referential Integrity for their functionality Relationships among tables based on the definition of: A primary key - referenced column A foreign key - referencing column Referenced columns must be defined as: Unique columns Not Null columns Prevents database corruption when performing INSERT, UPDATEs, and DELETEs.
A row cannot exist with a non-null value for a referencing column if an equal value does not exist in a referenced column.
Referential Model
Employee
Employee Number PK 100001 100797 100002 100471 100389 Dept Number FK 1001 1048 1001 1028 1023 Emp_Mgr Number FK ? 100791 100001 100442 100381 Job Code FK 3000 3017 3001 3017 3018 DeBosse Myers Smith Roberts Ball Ibee Ruth Steve Rich Jason 200000.00 41000.00 110000.00 40000.00 64000.00 Last Name First Name Salary Amount
Job
Job Code PK 3000 3001 3017 3018 3045 President Senior Mgmt Analyst L2 Analyst L1 Assembler L4 Job Description
Employee_Phone
Employee Number FK 100001 100001 100389 100797 100797 937 937 858 770 310 5100001 4100001 4852815 9082445 5554512 1001 1001 815 445 ? Area Code PK Phone Number Extension
Department
Dept Number PK 1048 1050 1028 1023 1001 Design SW Design Services Engineering SW Engineering Disk Leadership Team Dept Name Dept_Mgr Number FK 100791 100811 100441 100381 100001 1000000.00 1000000.00 3000000.00 2000000.00 5000000.00 Budget Amount
Second approach:
1. Create the tables and define the Primary Keys. 2. Create the Foreign Key references. 3. Populate the tables.
The Department table has a nullable foreign key reference to the Employee table.
The Job table references no other table. The Employee table has foreign key reference to the Department and Job tables. Compress is not allowed on either the referencing or referenced columns. The data types must be the same.
Circular References
Employee
Employee Number PK1 : 100341 Dept Number FK2 : 1022
Department
Dept Number PK2 : 1022 : Engineering CPU Dept Name Dept_Mgr Number FK1 : 100341
To Insert rows:
(Employee_Number, Dept_Number, . . .) (100341, NULL, . . .); (Dept_Number, Dept_Name, Dept_Mgr_Number) (1022, 'Engineering CPU', 100341);
To Delete rows:
DELETE Employee WHERE Employee_Number = 100341; (error, referencing column) UPDATE Department SET Dept_Mgr_Number = NULL WHERE Dept_Number = 1022 ; DELETE Employee WHERE Employee_Number = 100341; (success)
Note: FK1 and FK2 must allow NULLs for these operations to work.
Before creating the References constraints, populate the tables with user data.
CREATE SET TABLE Emp_Phone ( employee_number INTEGER NOT NULL ,area_code SMALLINT NOT NULL ,phone_number INTEGER NOT NULL ,extension INTEGER , PRIMARY KEY (employee_number, area_code, phone_number) ) PRIMARY INDEX (employee_number);
ALTER TABLE Employee ADD CONSTRAINT emp_mgr_ref FOREIGN KEY (emp_mgr_number) REFERENCES Employee (employee_number);
ALTER TABLE Department ADD CONSTRAINT dept_mgr_ref FOREIGN KEY (dept_mgr_number) REFERENCES Employee (employee_number); ALTER TABLE Emp_Phone ADD CONSTRAINT phone_emp_ref FOREIGN KEY (employee_number) REFERENCES Employee (employee_number);
DEPARTMENT DEPT NUMBER PK UPI DEPT NAME USI DEPT MGR NUMBER FK BUDGET AMOUNT
EXTENSION
DBC.RI_Distinct_Parents
DBC.RI_Child_Tables
DBC.RI_Parent_Tables
DBC.All_RI_Children View
Provides information about all tables in child-parent order.
DBC.All_RI_Children
IndexID ChildKeyColumn InconsistencyFlag IndexName ParentDB CreatorName ChildDB ParentTable CreateTimeStamp ChildTable ParentKeyColumn
Example: List all of the referential integrity constraints in the child database.
SELECT
Example Results:
ID 0 0 8 4 0 IndexName dept_mgr_ref emp_dept_ref emp_mgr_ref emp_job_ref phone_emp_ref
Indexid ,IndexName ,ChildTable ,ChildKeyColumn ,ParentTable ,ParentKeyColumn FROM DBC.ALL_RI_Children WHERE ChildDB = USER ORDER BY 3, 4 ;
ChildTable Department Employee Employee Employee Emp_Phone ChildKeyColumn dept_mgr_number dept_number emp_mgr_number job_code employee_number
(FORMAT z9) AS ID
DBC.All_RI_Parents View
Provides information about all tables in parent-child order.
DBC.All_RI_Parents
IndexID ParentKeyColumn InconsistencyFlag IndexName ChildDB CreatorName ParentDB ChildTable CreateTimeStamp ParentTable ChildKeyColumn
Example: List all of the referential integrity constraints in the parent database.
SELECT
Example Results:
ID 0 0 0 8 4 IndexName emp_dept_ref phone_emp_ref dept_mgr_ref emp_mgr_ref emp_job_ref
Indexid ,IndexName ,ParentTable ,ParentKeyColumn ,ChildTable ,ChildKeyColumn FROM DBC.ALL_RI_Parents WHERE ParentDB = USER ORDER BY 3, 4 ;
ParentTable Department Employee Employee Employee Job ParentKeyColumn dept_number employee_number employee_number employee_number job_code
(FORMAT 'z9') AS ID
Additional RI Views
These two additional views can be used to reduce duplicate rows for multi-column foreign keys. DBC.RI_DISTINCT_Children
IndexID ParentTable IndexName InconsistencyFlag ChildDB CreatorName ChildTable CreateTimeStamp ParentDB
DBC.RI_DISTINCT_Parents
IndexID ChildTable IndexName InconsistencyFlag ParentDB CreatorName ParentTable CreateTimeStamp ChildDB
These two additional views can be used if internal Table ID information is needed. DBC.RI_Child_Tables
IndexID IndexName ParentDbID ParentTID CreateTimeStamp ChildDbID ParentKeyFID ChildTID InconsistencyFlag ChildKeyFID CreatorName
DBC.RI_Parent_Tables
IndexID IndexName ChildDbID ChildTID CreateTimeStamp ParentDbID ChildKeyFID ParentTID InconsistencyFlag ParentKeyFID CreatorName
ParentCount how many foreign keys does a table have or how many parents does
the table reference?
ChildCount how many foreign keys reference this table or how many children does
the table have? Example: List the tables objects in the database TFACT and identify parent and child counts. SELECT TableName ,TableKind ,ParentCount ,ChildCount DBC.Tables DatabaseName = 'TFACT' TableKind = 'T' 2, 1 ;
TableKind T T T T T ParentCount 1 3 1 0 0 ChildCount 1 3 0 1 0
Example Results:
The status of a Referential integrity constraint is classified as follows: Unresolved reference constraints - the FK exists, but the PK does not.
Creating a table with a Foreign Key before creating the table with Parent
Key (Primary Key).
Restoring a table with a Foreign Key and the Parent Key (Primary Key) table
does not exist or hasn't been restored.
Inconsistent reference constraint - both the FK and the PK exist, but the
constraint is marked as inconsistent.
When either the child or parent table is restored, the reference constraint
for the child table is marked as inconsistent.
Invalid Rows - both the FK and the PK exist and are considered
consistent, but specific foreign key values are identified as invalid.
Creating a table with a Foreign Key before creating the table with Parent Key
(Primary Key).
Restoring a table with a Foreign Key and the Parent Key (Primary Key) table does not
exist or hasn't been restored. DBC.Databases2
DatabaseName
DatabaseID
UnresolvedRICount
Results:
DatabaseName PD DatabaseID 0000FE03 UnresolvedRICount 2
FROM WHERE
Restore the Parent Table to resolve the references constraint, but the references constraint is marked as inconsistent.
Example: SELECT
IndexID (FORMAT 'z9') AS ID ,IndexName ,ChildTable ,ChildKeyColumn ,ParentTable ,ParentKeyColumn ,InconsistencyFlag AS ICF FROM DBC.ALL_RI_Children WHERE ChildDB = 'PD' ORDER BY 3, 4 ;
ID 0 0 8 4 0 IndexName dept_mgr_ref emp_dept_ref emp_mgr_ref emp_job_ref phone_emp_ref ChildTable Department Employee Employee Employee Emp_Phone ChildKeyColumn dept_mgr_number dept_number emp_mgr_number job_code employee_number ParentTable Employee Department Employee Job Employee ParentKeyColumn employee_number dept_number employee_number job_code employee_number ICF Y Y Y Y Y
Results:
FK Constraints are now removed from the table and the table may be updated with
inconsistent foreign key values before the References constraint is created.
What is a Trigger?
A Trigger may be defined as:
Any of the following SQL statements may be applied to triggers: CREATE DROP SHOW ALTER RENAME REPLACE HELP
TRIGGERS
DELETE DATABASE or DELETE USER cause all triggers to be dropped. Privileges are required to create and drop triggers. GRANT REVOKE CREATE DROP TRIGGER
CREATE TRIGGER privilege on the subject table or the database. SELECT privilege on any column referenced in a WHEN clause or a triggered SQL
statement subquery.
INSERT, UPDATE, or DELETE privileges on the triggered SQL statement target table,
depending on the triggered SQL statement.
DROP TRIGGER privilege on the subject table or the database. The exception is
when you use the REPLACE TRIGGER statement when no target trigger exists and you instead create a new trigger.
INSERT, UPDATE, or DELETE privileges on the triggered SQL statement target table,
depending on the triggered SQL statement.
Trigger Example
CREATE SET TABLE Employee (Name CHAR(15), Deptid INTEGER, Salary DECIMAL(10,2), Job_Title CHAR(15)) PRIMARY INDEX (Name);
CREATE SET TABLE Salarylog (UserName CHAR(30), EmpName CHAR(30), OldSalary DECIMAL(10,2), NewSalary DECIMAL(10,2)) PRIMARY INDEX (UserName); Create a trigger that places a new row into the Salarylog table whenever there is a salary increase greater than 10%. CREATE TRIGGER RaiseTrig AFTER UPDATE OF (Salary) ON Employee REFERENCING OLD AS OldRow NEW AS NewRow FOR EACH ROW WHEN ((NewRow.Salary - OldRow.Salary)/OldRow.Salary > 0.10) ( INSERT INTO SalaryLog VALUES (USER, NewRow.Name, OldRow.Salary, NewRow.Salary); );
UPDATE Employee SET salary = salary * 1.25 UPDATE Employee SET salary = salary * 1.05 UPDATE Employee SET salary = 50000 SELECT * FROM Employee; Name Deptid Salary ========= ====== ======= carol 3333 50000.00 debbie 4444 42000.00 larry 2222 22000.00 joe 2222 30000.00 allan 1111 25000.00 SELECT * FROM Salarylog; UserName EmpName ========= =========== PAYADMIN allan PAYADMIN carol
Review Questions
1. Number the following steps 1 to 3 based on the recommendations of this module. ___ ___ ___ Create references Create data tables Populate the tables
2. Answer the following statements about Primary and Foreign Keys as true or false. ___ ___ ___ ___ ___ ___ A PK value can be set to NULL as long as there are no FK values referencing that PK value. A PK value can be set to a different value as long as there are no FK values referencing that PK value. A FK value can be set to NULL. A PK can be implemented as a NOT NULL NUPI. A FK can only be implemented on indexed columns. A PK is always implemented as a UNIQUE INDEX.
3. A trigger executes (fires) when either an ______, ______, or _______ statement modifies a specified column or columns in a table.
2. Answer the following statements about Primary and Foreign Keys as true or false. False A PK value can be set to NULL as long as there are no FK values referencing that PK value. True True A PK value can be set to a different value as long as there are no FK values referencing that PK value. A FK value can be set to NULL.
False A PK can be implemented as a NOT NULL NUPI. False A FK can only be implemented on indexed columns. True A PK is always implemented as a UNIQUE INDEX.
3. A trigger executes (fires) when either an INSERT, UPDATE, or DELETE statement modifies a specified column or columns in a table.
Lab Exercises
Lab Exercise 9-1
Purpose In this lab, you will use BTEQ or (Teradata SQL Assistant) to establish References constraints between 4 populated tables and view the associated data dictionary entries. What you need Populated PD tables and empty tables in your database Tasks 1. Use INSERT/SELECT to place all rows from the populated PD tables into your empty tables. Verify the number of rows in your tables. PD.Employee PD.Department PD.Job PD.Emp_Phone to populate to populate to populate to populate Employee Department Job Emp_Phone Count = _______ Count = _______ Count = _______ Count = _______
2. Use the GRANT statement to GRANT yourself the REFERENCES access rights on the tables.
Lab Exercises
Lab Exercise 9-1 (cont.)
Tasks 3. Create a References constraint between the Employee.Dept_Number column and the Department.Dept_Number column.
What is the name of the Employee RI error table? How many rows are in this table? ______
_______________
4. Use the DBC.All_RI_Children view (qualify the ChildDB to your database) and verify this References constraint. What is the IndexID of this constraint? _______
Lab Exercises
Lab Exercise 9-1 (cont.)
Tasks 5. Create the References constraint between the Employee.Job_code column and the Job.Job_Code column. What is the name of the Employee RI error table? _______________ How many rows are in this table? ______ Which job code is not represented in the job table? _______ 6. Use the DBC.All_RI_Children view (qualify the ChildDB to your database) and verify this References constraint. What is the IndexID of this constraint? ________ 7. Create the References constraint between the Employee.Emp_Mgr_Number column and the Employee.Employee_Number column. What is the name of the Employee RI error table? _______________ How many rows are in this table? ______ Which employee does not have a manager (Emp_Mgr_Number is 0 or NULL)? _______ 8. Use the DBC.All_RI_Children view (qualify the ChildDB to your database) and verify this References constraint. What is the IndexID of this constraint? _______
Lab Exercises
Lab Exercise 9-1 (cont.)
Tasks 9. Create a References constraint between the Department.Dept_Mgr_Number column and the Employee.Employee_Number column. What is the name of the Department RI error table? How many rows are in this table? ______ _______________
10. Use the DBC.All_RI_Children view (qualify the ChildDB to your database) and verify this References constraint. What is the IndexID of this constraint? _______ 11. Create a References constraint between the Emp_Phone.Employee_Number column and the Employee.Employee_Number column. What is the name of the Emp_Phone RI error table? How many rows are in this table? ______ _______________
12. Use the DBC.All_RI_Children view (qualify the ChildDB to your database) and verify this References constraint. What is the IndexID of this constraint? _______
INSERT INTO Employee SELECT * FROM PD.Employee; SELECT COUNT(*) FROM Employee; Count = 1000 INSERT INTO Department SELECT * FROM PD.Department; SELECT COUNT(*) FROM Department; Count = 60
INSERT INTO Job SELECT * FROM PD.Job; SELECT COUNT(*) FROM Job; Count = 66
INSERT INTO Emp_Phone SELECT * FROM PD.Emp_Phone SELECT COUNT(*) FROM Emp_Phone; Count = 2000
2.
Use the GRANT statement to GRANT yourself the REFERENCES access rights on the tables.
GRANT REFERENCES ON Employee TO tljc20; GRANT REFERENCES ON Department TO tljc20; GRANT REFERENCES ON Job TO tljc20;
ALTER TABLE Employee ADD CONSTRAINT emp_dept_ref FOREIGN KEY (dept_number) REFERENCES Department (dept_number) ;
What is the name of the Employee RI error table? EMPLOYEE_0 How many rows are in this table? 1 Which department is not represented in the department table? 1000 4. Use the DBC.All_RI_Children view (qualify the ChildDB to your database) and verify this References constraint. What is the IndexID of this constraint? 0
SELECT
Indexid (FORMAT 'z9') AS ID ,IndexName ,ChildTable ,ChildKeyColumn ,ParentTable ,ParentKeyColumn DBC.ALL_RI_Children ChildDB = USER 3, 4 ;
ChildTable Employee ChildKeyColumn dept_number ParentTable Department ParentKeyColumn dept_number
ID IndexName emp_dept_ref
ALTER TABLE Employee ADD CONSTRAINT emp_job_ref FOREIGN KEY (job_code) REFERENCES Job (job_code);
What is the name of the Employee RI error table? EMPLOYEE_4 How many rows are in this table? 1 Which job code is not represented in the job table? 3000 6. Use the DBC.All_RI_Children view (qualify the ChildDB to your database) and verify this References constraint. What is the IndexID of this constraint? 4
SELECT
Indexid (FORMAT 'z9') AS ID ,IndexName ,ChildTable ,ChildKeyColumn ,ParentTable ,ParentKeyColumn DBC.ALL_RI_Children ChildDB = USER 3, 4 ;
ChildTable Employee Employee ChildKeyColumn dept_number job_code ParentTable Department Job ParentKeyColumn dept_number job_code
ALTER TABLE Employee ADD CONSTRAINT emp_mgr_ref FOREIGN KEY (emp_mgr_number) REFERENCES Employee (employee_number);
What is the name of the Employee RI error table? EMPLOYEE_8 How many rows are in this table? 1 Which employee does not have a manager (Emp_Mgr_Number is 0 or NULL)? 100001
SELECT
Indexid (FORMAT 'z9') AS ID ,IndexName ,ChildTable ,ChildKeyColumn ,ParentTable ,ParentKeyColumn DBC.ALL_RI_Children ChildDB = USER 3, 4 ;
ChildTable Employee Employee Employee ChildKeyColumn dept_number emp_mgr_number job_code ParentTable Department Employee Job ParentKeyColumn dept_number employee_number job_code
ALTER TABLE Department ADD CONSTRAINT dept_mgr_ref FOREIGN KEY (dept_mgr_number) REFERENCES Employee (employee_number);
What is the name of the Department RI error table? DEPARTMENT_0 How many rows are in this table? 0 10. Use the DBC.All_RI_Children view (qualify the ChildDB to your database) and verify this References constraint. What is the IndexID of this constraint? 0
SELECT
Indexid (FORMAT 'z9') AS ID ,IndexName ,ChildTable ,ChildKeyColumn ,ParentTable ,ParentKeyColumn DBC.ALL_RI_Children ChildDB = USER 3, 4 ;
ID 0 0 8 4
ALTER TABLE Emp_Phone ADD CONSTRAINT phone_emp_ref FOREIGN KEY (employee_number) REFERENCES Employee (employee_number);
What is the name of the Emp_Phone RI error table? EMP_PHONE_0 How many rows are in this table? 0
12. Use the DBC.All_RI_Children view (qualify the ChildDB to your database) and verify this References constraint.
What is the IndexID of this constraint? 0
SELECT
Indexid (FORMAT 'z9') AS ID ,IndexName ,ChildTable ,ChildKeyColumn ,ParentTable ,ParentKeyColumn DBC.ALL_RI_Children ChildDB = USER 3, 4 ;
ChildTable Department Employee Employee Employee Emp_Phone ChildKeyColumn dept_mgr_number dept_number emp_mgr_number job_code employee_number ParentTable Employee Department Employee Job Employee ParentKeyColumn employee_number dept_number employee_number job_code employee_number