Creating business rules and constraints on your SQL tables is actually a part of the database design phase. We treat it as a separate topic as these rules can be added later instead of creating them at the same time as the tables. This is really a good thing as none of us can think of everything during the design phase.
There are two kinds of business rules and constraints – those that perform referential integrity of the tables and those that apply actual business rules. These two kinds of constraints are sometimes confused, but we will try to keep them separate in our explanation.
This chapter will group the constraints by their type. This will include indexes, NOT NULL attribute, primary keys, foreign keys, table checks, and informational constraints. In many cases, a constraint can fit into more than one category, which is why we will group them by Db2 type rather than by their constraint type.
NOT NULL Attribute
In this table, the emp_num column must contain data, even if it is just a single blank. The NOT NULL constraint ensures that the column always has some data in it. It may not necessarily be valid data (we will discuss this topic later), but it must contain data of some type.
The columns name, location, and create_date may all have the NULL type assigned to them. This is the default for all columns that do not include the NOT NULL phrase as a part of the column definition.
This will add the NOT NULL clause to the name column without modifying the data type.
Primary Key
Here we have modified the emp_num column so that Db2 will add one to the highest existing integer in the entire column and assign that to the new emp_num column automatically when a new row is inserted into the table.
You should not think of the primary key as a unique index even though that is what is created underneath. While they have many of the same characteristics, they are not the same. For one thing, a table can have only one primary key, but it can have many unique and nonunique indexes.
Indexes
Unique indexes: This type of index prevents an entry in the indexed column from appearing more than once in the table. The UNIQUE keyword specifies this kind of index.
Nonunique indexes: This type of index will improve the ability of Db2 to read the table when it is used in the WHERE clause of a SELECT statement.
An index can also be dropped with the DROP INDEX statement.
A word of warning is needed for indexes at this point. Try not to go overboard when creating indexes. You may think that indexing all columns in a table will give you the best access times for all your queries. This is completely untrue and will instead cause most of the indexes to be ignored.
Foreign Keys
The department table defines all departments within the organization. The employee table has a dept column that references the dept_num column in the department table. What this means is that when you try to insert a new record in the employee table, the system will check to make sure that the dept column value exists in the dept_num column in the department table. If no corresponding department number is found in the department table, then the INSERT will fail.
Foreign keys are a type of referential constraint, or sometimes known as a foreign key constraint. A foreign key can refer to either a primary key or an index. In the case of an index, the index must be a single column, but it does not need to be a unique index.
In the preceding example, the UNIQUE keyword ensures that all dept_num numbers are unique in the department table. An attempt to insert a duplicate department number in the table will be rejected.
CHECK and Unique Constraints
The salary column must have a value greater than or equal to 5000 when a row is inserted into or updated in the table. The job column must have one of the three values specified (case sensitive). The constraint expression can have the values as specified previously, or it could be a sub–SELECT statement that returns the set of specified valid values.
DEFAULT Constraint
Note that the ssn field is not referenced. Normally this could cause a problem with the INSERT statement. But in this case, a default value for ssn has been specified, so no error is raised.
Triggers
The subject on which the trigger is defined – tables or views
The event that initiates the trigger – an INSERT, UPDATE, or DELETE action
The activation time of the trigger – a BEFORE or AFTER event
The granularity that specifies whether the trigger’s actions are performed once for the table or once for each of the affected rows – a FOR EACH STATEMENT or FOR EACH ROW action
- The action that the trigger performs – one or more of the following elements:
- a.
CALL statement
- b.
DECLARE and/or SET statement
- c.
WHILE and/or FOR loop
- d.
IF, SIGNAL, ITERATE, LEAVE, and GET DIAGNOSTIC statements
- e.
SELECT statement
- f.
INSERT, UPDATE, DELETE, and MERGE SQL statements (only for AFTER and INSTEAD OF triggers)
BEFORE triggers are activated before an UPDATE or INSERT operation, and the values that are being updated or inserted can be changed before the database is modified.
AFTER triggers are activated after an INSERT, UPDATE, or DELETE operation and are used to maintain relationships between data or keep audit trail information.
INSTEAD OF triggers define how to perform an INSERT, UPDATE, or DELETE operation on a view where these operations are otherwise not allowed.
TriggerName: Identifies the name to assign to the trigger to be created.
TriggerEvent: Specifies the triggered action associated with the trigger to be executed whenever one of the events is applied to the subject table or subject view.
TableName: Identifies the name of the table (the subject) on which the trigger is defined.
ViewName: Identifies the name of the view (the subject) on which the trigger is defined.
CorrelationName: A temporary table name that identifies the row state before triggering the SQL operation.
Identifier: A temporary table name that identifies the set of affected rows before triggering the SQL operation.
Action: Specifies the action to perform when a trigger is activated. A trigger action is composed of an SQL procedure statement and an optional condition for the execution of the SQL procedure statement.
While there are almost an infinite number of ways to use triggers, we will show only four simple examples. These examples can be used as the basis for other triggers you create.
Summary
In this chapter, we have introduced the concept of business rules and constraints. These rules and constraints can help you implement the rules your organization may have established for the upkeep of their data. They can also help implement organizational characteristics for the organization as well as establish relationships between different sections of the company.