Oracle Essentials Oracle Database 11g (22 page)

BOOK: Oracle Essentials Oracle Database 11g
2.23Mb size Format: txt, pdf, ePub

Normalization provides benefits by avoiding storage of redundant data. Storing the department in every employee record not only would waste space but also would lead to a data maintenance issue. If the department name changed, you would have to update every employee record, even though no employees had actually changed departments. By normalizing the department data into a table and simply pointing to the appropriate row from the employee rows, youavoid both duplication of data and this type of problem.

Normalization also reduces the amount of data that any one row in a table contains.

The less data in a row, the less I/O is needed to retrieve it, which helps to avoid this performance bottleneck. In addition, the smaller the size of a row, the more rows are retrieved per data block, which increases the likelihood that more than one desired row will be retrieved in a single I/O operation. And the smaller the row, the more rows will be kept in Oracle’s system buffers, which also increases the likelihood that a row will be available in memory when it’s needed, thereby avoiding the need for any disk I/O at all.

Finally, the process of normalization includes the creation of foreign key relationships and other data constraints. These relationships build a level of data integrity directly into your database design.

Figure 4-3
shows a simple list of attributes grouped into entities and linked by a foreign key relationship.

Employee number

Employee name

Department number

Hire date

Job name

Department name

Salary

Title

Location

Commission

Figure 4-3. The normalization process

Data Design

|

103

However, there is an even more important reason to go through the process of designing a normalized database. Youcan benefit from normalization because of the planning process that normalizing a data design entails. By really thinking about the way the intended applications use data, you get a much clearer picture of the needs the system is designed to serve. This understanding leads to a much more focused database and application.

Gaining a deep understanding of the way your data will be used also helps with your other design tasks. For instance, once you’ve completed an optimal logical database design, youmust go back and consider what indexes youshould add to improve the anticipated performance of the database and whether youshou

ld designate any

tables as part of a cluster or hash cluster.

Since adding these types of performance-enhancing data structures doesn’t affect the logical representation of the database, youcan always make these types of modifications later when yousee the way an application uses the database in test mode or in production.

Constraints

A
constraint
enforces certain aspects of data integrity within a database. When you add a constraint to a particular column, Oracle automatically ensures that data violating that constraint is never accepted. If a user attempts to write data that violates a constraint, Oracle returns an error for the offending SQL statement.

Constraints may be associated with columns when you create or add the table containing the column (via a number of keywords) or after the table has been created with the SQL command ALTER TABLE. Since Oracle8, the following constraint types are supported:

NOT NULL

Youcan designate any column as NOT NULL. If any SQL operation leaves a NULL value in a column with a NOT NULL constraint, Oracle returns an error for the statement.

Unique

When you designate a column or set of columns as unique, users cannot add values that already exist in another row in the table for those columns, or modify existing values to match other values in the column.

The unique constraint is implemented by the creation of an index, which requires a unique value. If you include more than one column as part of a unique key, you will create a single index that will include all the columns in the unique key. If an index already exists for this purpose, Oracle will automatically use that index.

104

|

Chapter 4: Oracle Data Structures

Should You Normalize Your Data?

Whenever possible, we recommend that yougo through the process of designing a normalized structure for your database.

Data normalization has been proven, both theoretically and in decades of practice, to provide concrete benefits. In addition, the process of creating a normalized data design is intimately intertwined with the process of understanding the data requirements for your application system. You can improve even the simplest database by the discoveries made during the process of normalization.

However, there may be times when youfeel that the benefits of a fully normalized design will counteract the performance penalty that a design imposes on your production systems. For example, youmay have one, two, or three contact names to be placed in their own table, with a foreign key linking back to the main row for the organization.

But because you want to see all the contact names every time you request contact information, youmight decide to save the overhead and added development effort of the join and simply include the three contact names in your organization table. This technique is common in decision-support/data warehousing applications.

Of course, this violation of the rules of normalization limits the flexibility of your application systems—for example, if youlater decide that youneed four contact names, some modification of every application and report that uses the contact names will be necessary. Normalization leads to a more flexible design, which is a good thing in the constantly changing world we live in.

For this reason, we suggest that you always implement a fully normalized database design and then, if necessary, go back and denormalize certain tables as needed. With this approach, youwill at least have to make a conscious decision to “break” the normalization, which involves an active consideration of the price of denormalization.

If a column is unique but allows NULL values, any number of rows can have a NULL value, because the NULL indicates the absence of a value. To require a truly unique value for a column in every row, the column should be both unique and NOT NULL.

Primary key

Each table can have, at most, a single primary key constraint. The primary key may consist of more than one column in a table.

The primary key constraint forces each primary key to have a unique value. It enforces both the unique constraint and the NOT NULL constraint. A primary key constraint will create a unique index, if one doesn’t already exist for the specified column(s).

Constraints

|

105

Foreign key

The foreign key constraint is defined for a table (known as the
child
) that has a relationship with another table in the database (known as the
parent
). The value entered in a foreign key must be present in a unique or primary key of another specific table. For example, the column for a department ID in an employee table might be a foreign key for the department ID primary key in the department table.

A foreign key can have one or more columns, but the referenced key must have an equal number of columns. You can have a foreign key relate to the primary key of its own table, such as when the employee ID of a manager is a foreign key referencing the ID column in the same table.

A foreign key can contain a NULL value if it’s not forbidden through another constraint.

By requiring that the value for a foreign key exist in another table, the foreign key constraint enforces referential integrity in the database. Foreign keys not only provide a way to join related tables but also ensure that the relationship between the two tables will have the required data integrity.

Normally, youcannot delete a row in a parent table if it causes a row in the child table to violate a foreign key constraint. However, youcan specify that a foreign key constraint causes a
cascade delete
, which means that deleting a referenced row in the parent table automatically deletes all rows in the child table that reference the primary key value in the deleted row in the parent table.

Check

A check constraint is a more general-purpose constraint. A check constraint is a Boolean expression that evaluates to either TRUE or FALSE. If the check constraint evaluates to FALSE, the SQL statement that caused the result returns an error. For example, a check constraint might require the minimum balance in a bank account to be over $100. If a user tries to update data for that account in a way that causes the balance to drop below this required amount, the constraint will return an error.

Some constraints require the creation of indexes to support them. For instance, the unique constraint creates an implicit index used to guarantee uniqueness. You can also specify a particular index that will enforce a constraint when you define that constraint.

All constraints can be either immediate or deferred. An
immediate constraint
is enforced as soon as a write operation affects a constrained column in the table. A
deferred constraint
is enforced when the SQL statement that caused the change in the constrained column completes. Because a single SQL statement can affect several rows, the choice between using a deferred constraint or an immediate constraint can significantly affect how the integrity dictated by the constraint operates. Youcan
106

|

Chapter 4: Oracle Data Structures

specify that an individual constraint is immediate or deferred, or you can set the timing for all constraints in a single transaction.

Finally, you can temporarily suspend the enforcement of constraints for a particular table. When youenable the operation of the constraint, youcan instruct Oracle to validate all the data for the constraint or simply start applying the constraint to the new data. When youadd a constraint to an existing table, youcan also specify whether you want to check all the existing rows in the table.

Triggers

You use constraints to automatically enforce data integrity rules whenever a user tries to write or modify a row in a table. There are times when youwant to use the same kind of timing for your own application-specific logic. Oracle includes
triggers
to give you this capability.

Although you can write triggers to perform the work of a constraint, Oracle has optimized the operation of constraints, so it’s best to always use a constraint instead of a trigger if possible.

A trigger is a block of code that is fired whenever a particular type of database event occurs to a table. There are three types of events that can cause a trigger to fire:

• A database UPDATE

• A database INSERT

• A database DELETE

You can, for instance, define a trigger to write a customized audit record whenever a user changes a row.

Triggers are defined at the row level. Youcan specify that a trigger be fired for each row or for the SQL statement that fires the trigger event. As with the previous discussion of constraints, a single SQL statement can affect many rows, so the specification of the trigger can have a significant effect on the operation of the trigger and the performance of the database.

There are three times when a trigger can fire:

• Before the execution of the triggering event

• After the execution of the triggering event

• Instead of the triggering event

Combining the first two timing options with the row and statement versions of a trigger gives youfour possible trigger implementations: before a statement, before a row, after a statement, and after a row.

Triggers

|

107

Oracle Database 11
g
introduced the concept of compound triggers; with this enhancement, a single trigger can have a section for the different timing implementations. Compound triggers help to improve performance, since the trigger has to be loaded only once for multiple timing options.

INSTEAD OF triggers were introduced with Oracle8. The INSTEAD OF trigger has a specific purpose: to implement data-manipulation operations on views that don’t normally permit them, such as a view that references columns in more than one base table for updates. You should be careful when using INSTEAD OF triggers because of the many potential problems associated with modifying the data in the underlying base tables of a view. There are many restrictions on when youcan use INSTEAD

OF triggers. Refer to your Oracle documentation for a detailed description of the forbidden scenarios.

Youcan specify a
trigger restriction
for any trigger. A trigger restriction is a Boolean expression that circumvents the execution of the trigger if it evaluates to FALSE.

Triggers are defined and stored separately from the tables that use them. Since they contain logic, they must be written in a language with capabilities beyond those of SQL, which is designed to access data. Oracle8 and later versions allow youto write triggers in PL/SQL, the procedural language that has been a part of Oracle since Version 6. Oracle8
i
and beyond also support Java as a procedural language, so you can create Java triggers with those versions.

Other books

A Dead Liberty by Catherine Aird
Coming Back Stronger by Bees, Drew
The Half-Child by Angela Savage
William by Sam Crescent
The Black Tattoo by Sam Enthoven
Love You to Death by Melissa Senate
El Arca de la Redención by Alastair Reynolds