DB2 exemplos simples - Types of constraints - Foreign key (referential) constraints



Desenvolvido por DORNELLES Carlos Alberto - Analista de Sistemas - Brasília DF. - cad_cobol@hotmail.com

DB2 exemplos simples - Types of constraints- Foreign key (referential) constraints

As restrições de chave estrangeira (também conhecidas como restrições referenciais ou restrições de integridade referencial) permitem a definição de relacionamentos necessários entre e dentro das tabelas.
Foreign key constraints (also known as referential constraints or referential integrity constraints) enable definition of required relationships between and within tables.

Por exemplo, uma restrição típica de chave estrangeira pode afirmar que cada funcionário na tabela EMPLOYEE deve ser membro de um departamento existente, conforme definido na tabela DEPARTMENT.
For example, a typical foreign key constraint might state that every employee in the EMPLOYEE table must be a member of an existing department, as defined in the DEPARTMENT table.

Integridade referencial é o estado de um banco de dados no qual todos os valores de todas as chaves estrangeiras são válidos.
Uma chave estrangeira é uma coluna ou um conjunto de colunas em uma tabela cujos valores são obrigados a corresponder a pelo menos uma chave primária ou valor de chave única de uma linha em sua tabela pai.
Uma restrição referencial é a regra de que os valores da chave estrangeira são válidos apenas se uma das seguintes condições for verdadeira:

Referential integrity is the state of a database in which all values of all foreign keys are valid.
A foreign key is a column or a set of columns in a table whose values are required to match at least one primary key or unique key value of a row in its parent table.
A referential constraint is the rule that the values of the foreign key are valid only if one of the following conditions is true:

  • Eles aparecem como valores de uma chave pai.
    They appear as values of a parent key.
  • Algum componente da chave estrangeira é nulo.
    Some component of the foreign key is null.

Para estabelecer esse relacionamento, você definiria o número do departamento na tabela EMPLOYEE como a chave estrangeira e o número do departamento na tabela DEPARTMENT como a chave primária.
To establish this relationship, you would define the department number in the EMPLOYEE table as the foreign key, and the department number in the DEPARTMENT table as the primary key.

A Figura 1 mostra como um registro com uma chave inválida é impedido de ser adicionado a uma tabela quando existe uma restrição de chave estrangeira entre duas tabelas:
Figure 1 shows how a record with an invalid key is prevented from being added to a table when a foreign key constraint exists between two tables:

Figura 1. Restrições de chave primária e estrangeira
Figure 1. Foreign and primary key constraints

Empregado com número de departamento inválido não pode ser adicionado à tabela de empregados.
Employee with invalid department number cannot be added to the employee table.

A tabela que contém a chave-pai é chamada de tabela-pai da restrição referencial, e a tabela que contém a chave estrangeira é considerada dependente dessa tabela.
The table that contains the parent key is called the parent table of the referential constraint, and the table that contains the foreign key is said to be a dependent of that table.

As restrições referenciais podem ser definidas na instrução CREATE TABLE ou ALTER TABLE.
As restrições referenciais são aplicadas pelo gerenciador do banco de dados durante a execução das instruções INSERT, UPDATE, DELETE, ALTER TABLE, MERGE, ADD CONSTRAINT e SET INTEGRITY.

Referential constraints can be defined in the CREATE TABLE statement or the ALTER TABLE statement.
Referential constraints are enforced by the database manager during the execution of INSERT, UPDATE, DELETE, ALTER TABLE, MERGE, ADD CONSTRAINT, and SET INTEGRITY statements.

As regras de integridade referencial envolvem os seguintes termos:
Referential integrity rules involve the following terms:

Tabela 1. Termos de integridade referencial
Table 1. Referential integrity terms

Conceito/Concept Termos/Terms
Parent key Uma chave primária ou uma chave única de uma restrição referencial.
A primary key or a unique key of a referential constraint.
Parent row Uma linha que possui pelo menos uma linha dependente.
A row that has at least one dependent row.
Parent table Uma tabela que contém a chave pai de uma restrição referencial.
Uma tabela pode ser um pai em um número arbitrário de restrições referenciais.
Uma tabela que é pai em uma restrição referencial também pode ser dependente em uma restrição referencial.

A table that contains the parent key of a referential constraint.
A table can be a parent in an arbitrary number of referential constraints.
A table that is the parent in a referential constraint can also be the dependent in a referential constraint.
Dependent table Uma tabela que contém pelo menos uma restrição referencial em sua definição.
Uma tabela pode ser dependente de um número arbitrário de restrições referenciais.
Uma tabela que é dependente em uma restrição referencial também pode ser o pai em uma restrição referencial.

A table that contains at least one referential constraint in its definition.
A table can be a dependent in an arbitrary number of referential constraints.
A table that is the dependent in a referential constraint can also be the parent in a referential constraint.
Descendent table Uma mesa é descendente da mesa T se for dependente de T ou descendente de um dependente de T.
A table is a descendent of table T if it is a dependent of T or a descendent of a dependent of T.
Dependent row Uma linha que possui pelo menos uma linha pai.
A row that has at least one parent row.
Descendent row Uma linha é descendente da linha r se for dependente de r ou descendente de uma dependente de r.
A row is a descendent of row r if it is a dependent of r or a descendent of a dependent of r.
Referential cycle Um conjunto de restrições referenciais de modo que cada tabela do conjunto seja descendente de si mesma.
A set of referential constraints such that each table in the set is a descendent of itself.
Self-referencing table Uma tabela que é pai e dependente na mesma restrição referencial.
A restrição é chamada de restrição de autorreferência.

A table that is a parent and a dependent in the same referential constraint.
The constraint is called a self-referencing constraint.
Self-referencing row Uma linha que é pai de si mesma.
A row that is a parent of itself.

O objetivo de uma restrição referencial é garantir que os relacionamentos da tabela sejam mantidos e que as regras de entrada de dados sejam seguidas.
Isso significa que enquanto uma restrição referencial está em vigor, o gerenciador de banco de dados garante que para cada linha em uma tabela filho que possui um valor não nulo em suas colunas de chave estrangeira, existe uma linha em uma tabela pai correspondente que possui um valor correspondente em sua chave pai.

The purpose of a referential constraint is to guarantee that table relationships are maintained and that data entry rules are followed.
This means that while a referential constraint is in effect, the database manager guarantees that for each row in a child table that has a non-null value in its foreign key columns, a row exists in a corresponding parent table that has a matching value in its parent key.

Quando uma operação SQL tenta alterar os dados de forma que a integridade referencial seja comprometida, uma restrição de chave estrangeira (ou referencial) pode ser violada.
O gerenciador de banco de dados lida com esses tipos de situações, impondo um conjunto de regras que estão associadas a cada restrição referencial.
Este conjunto de regras consiste em:

When an SQL operation attempts to change data in such a way that referential integrity becomes compromised, a foreign key (or referential) constraint could be violated.
The database manager handles these types of situations by enforcing a set of rules that are associated with each referential constraint.
This set of rules consist of:

  • Uma regra de inserção
    An insert rule
  • Uma regra de atualização
    An update rule
  • Uma regra de exclusão
    A delete rule

Quando uma operação SQL tenta alterar os dados de forma que a integridade referencial seja comprometida, uma restrição referencial pode ser violada.
Por exemplo,
When an SQL operation attempts to change data in such a way that referential integrity will be compromised, a referential constraint could be violated.
For example,

  • Uma operação de inserção pode tentar adicionar uma linha de dados a uma tabela filho que possui um valor em suas colunas de chave estrangeira que não corresponde a um valor na chave pai da tabela pai correspondente.
    An insert operation could attempt to add a row of data to a child table that has a value in its foreign key columns that does not match a value in the corresponding parent table's parent key.

  • Uma operação de atualização pode tentar alterar o valor nas colunas de chave estrangeira de uma tabela filho para um valor que não tem nenhum valor correspondente na chave pai da tabela pai correspondente.
    An update operation could attempt to change the value in a child table's foreign key columns to a value that has no matching value in the corresponding parent table's parent key.

  • Uma operação de atualização pode tentar alterar o valor na chave pai de uma tabela pai para um valor que não tenha um valor correspondente nas colunas de chave estrangeira da tabela filho.
    An update operation could attempt to change the value in a parent table's parent key to a value that does not have a matching value in a child table's foreign key columns.

  • Uma operação de exclusão pode tentar remover um registro de uma tabela pai que possui um valor correspondente nas colunas de chave estrangeira da tabela filho.
    A delete operation could attempt to remove a record from a parent table that has a matching value in a child table's foreign key columns.

O gerenciador de banco de dados lida com esses tipos de situações, impondo um conjunto de regras que estão associadas a cada restrição referencial.
Este conjunto de regras consiste em:
The database manager handles these types of situations by enforcing a set of rules that are associated with each referential constraint.
This set of rules consists of:

  • Uma regra de inserção
    An insert rule
  • Uma regra de atualização
    An update rule
  • Uma regra de exclusão
    A delete rule

Inserir regra - Insert rule

A regra de inserção de uma restrição referencial é que um valor de inserção não nulo da chave estrangeira deve corresponder a algum valor da chave pai da tabela pai.
O valor de uma chave estrangeira composta é nulo se qualquer componente do valor for nulo.
Esta regra está implícita quando uma chave estrangeira é especificada.

The insert rule of a referential constraint is that a non-null insert value of the foreign key must match some value of the parent key of the parent table.
The value of a composite foreign key is null if any component of the value is null.
This rule is implicit when a foreign key is specified.

Regra de atualização - Update rule

A regra de atualização de uma restrição referencial é especificada quando a restrição referencial é definida.
As opções são NO ACTION e RESTRICT.
A regra de atualização se aplica quando uma linha do pai ou uma linha da tabela dependente é atualizada.

The update rule of a referential constraint is specified when the referential constraint is defined.
The choices are NO ACTION and RESTRICT.
The update rule applies when a row of the parent or a row of the dependent table is updated.

Quando um valor em uma coluna da chave pai é atualizado, as seguintes regras se aplicam:
When a value in a column of the parent key is updated, the following rules apply:

  • Se alguma linha da tabela dependente corresponder ao valor original da chave, a atualização será rejeitada quando a regra de atualização for RESTRICT.
    If any row in the dependent table matches the original value of the key, the update is rejected when the update rule is RESTRICT.

  • Se alguma linha na tabela dependente não tiver uma chave pai correspondente quando a instrução de atualização for concluída (excluindo gatilhos AFTER), a atualização será rejeitada quando a regra de atualização for NO ACTION.
    If any row in the dependent table does not have a corresponding parent key when the update statement is completed (excluding AFTER triggers), the update is rejected when the update rule is NO ACTION.

O valor das chaves exclusivas pai não pode ser alterado se a regra de atualização for RESTRICT e houver uma ou mais linhas dependentes.
No entanto, se a regra de atualização for NO ACTION, as chaves exclusivas pai podem ser atualizadas, desde que cada filho tenha uma chave pai no momento em que a instrução de atualização for concluída.
Um valor de atualização não nulo de uma chave estrangeira deve ser igual a um valor da chave primária da tabela pai do relacionamento.

The value of the parent unique keys cannot be changed if the update rule is RESTRICT and there are one or more dependent rows.
However, if the update rule is NO ACTION, parent unique keys can be updated as long as every child has a parent key by the time the update statement completes.
A non-null update value of a foreign key must be equal to a value of the primary key of the parent table of the relationship.

Além disso, o uso de NO ACTION ou RESTRICT como regras de atualização para restrições referenciais determina quando a restrição é aplicada.
Uma regra de atualização de RESTRICT é aplicada antes de todas as outras restrições, incluindo aquelas restrições referenciais com regras de modificação, como CASCADE ou SET NULL.
Uma regra de atualização de NO ACTION é aplicada após outras restrições referenciais.
Observe que o SQLSTATE retornado é diferente dependendo se a regra de atualização é RESTRICT ou NO ACTION.

Also, the use of NO ACTION or RESTRICT as update rules for referential constraints determines when the constraint is enforced.
An update rule of RESTRICT is enforced before all other constraints, including those referential constraints with modifying rules such as CASCADE or SET NULL.
An update rule of NO ACTION is enforced after other referential constraints.
Note that the SQLSTATE returned is different depending on whether the update rule is RESTRICT or NO ACTION.

No caso de uma linha dependente, a regra de atualização NO ACTION fica implícita quando uma chave estrangeira é especificada.
NO ACTION significa que um valor de atualização não nulo de uma chave estrangeira deve corresponder a algum valor da chave pai da tabela pai quando a instrução de atualização for concluída.

In the case of a dependent row, the NO ACTION update rule is implicit when a foreign key is specified.
NO ACTION means that a non-null update value of a foreign key must match some value of the parent key of the parent table when the update statement is completed.

O valor de uma chave estrangeira composta é nulo se qualquer componente do valor for nulo.
The value of a composite foreign key is null if any component of the value is null.

Excluir regra - Delete rule

A regra de exclusão de uma restrição referencial é especificada quando a restrição referencial é definida.
As opções são NO ACTION, RESTRICT, CASCADE ou SET NULL.
SET NULL pode ser especificado apenas se alguma coluna da chave estrangeira permitir valores nulos.

The delete rule of a referential constraint is specified when the referential constraint is defined.
The choices are NO ACTION, RESTRICT, CASCADE, or SET NULL.
SET NULL can be specified only if some column of the foreign key allows null values.

Se a tabela identificada ou a tabela base da visão identificada for um pai, as linhas que são selecionadas para exclusão não devem ter nenhum dependente em um relacionamento com uma regra de exclusão de RESTRICT, e o DELETE não deve cascatear para linhas descendentes que possuem dependentes em um relacionamento com uma regra de exclusão de RESTRICT.

If the identified table or the base table of the identified view is a parent, the rows that are selected for delete must not have any dependents in a relationship with a delete rule of RESTRICT, and the DELETE must not cascade to descendent rows that have dependents in a relationship with a delete rule of RESTRICT.

Se a operação de exclusão não for impedida por uma regra de exclusão RESTRICT, as linhas selecionadas serão excluídas.
Todas as linhas que são dependentes das linhas selecionadas também são afetadas:
If the delete operation is not prevented by a RESTRICT delete rule, the selected rows are deleted.
Any rows that are dependents of the selected rows are also affected:

  • As colunas anuláveis ??das chaves estrangeiras de quaisquer linhas que são seus dependentes em um relacionamento com uma regra de exclusão de SET NULL são definidas com o valor nulo.
    The nullable columns of the foreign keys of any rows that are their dependents in a relationship with a delete rule of SET NULL are set to the null value.

  • Quaisquer linhas que são seus dependentes em um relacionamento com uma regra de exclusão de CASCADE também são excluídas e as regras mencionadas anteriormente se aplicam, por sua vez, a essas linhas.
    Any rows that are their dependents in a relationship with a delete rule of CASCADE are also deleted, and the rules mentioned previously apply, in turn, to those rows.

A regra de exclusão de NO ACTION é verificada para garantir que qualquer chave estrangeira não nula se refira a uma linha pai existente após as outras restrições referenciais terem sido aplicadas.
The delete rule of NO ACTION is checked to enforce that any non-null foreign key refers to an existing parent row after the other referential constraints have been enforced.

A regra de exclusão de uma restrição referencial se aplica apenas quando uma linha da tabela pai é excluída.
Mais precisamente, a regra se aplica apenas quando uma linha da tabela pai é o objeto de uma operação de exclusão ou exclusão propagada (definida na seção a seguir) e essa linha tem dependentes na tabela dependente da restrição referencial.
Considere um exemplo onde P é a tabela pai, D é a tabela dependente e p é uma linha pai que é o objeto de uma operação de exclusão ou exclusão propagada.

The delete rule of a referential constraint applies only when a row of the parent table is deleted.
More precisely, the rule applies only when a row of the parent table is the object of a delete or propagated delete operation (defined in the following section), and that row has dependents in the dependent table of the referential constraint.
Consider an example where P is the parent table, D is the dependent table, and p is a parent row that is the object of a delete or propagated delete operation.

A regra de exclusão funciona da seguinte maneira:
The delete rule works as follows:

  • Com RESTRICT ou NO ACTION, ocorre um erro e nenhuma linha é excluída.
    With RESTRICT or NO ACTION, an error occurs and no rows are deleted.

  • Com CASCADE, a operação de exclusão é propagada para os dependentes de p na tabela D.
    With CASCADE, the delete operation is propagated to the dependents of p in table D.

  • Com SET NULL, cada coluna anulável da chave estrangeira de cada dependente de p na tabela D é definida como nula.
    With SET NULL, each nullable column of the foreign key of each dependent of p in table D is set to null.

Qualquer tabela que pode estar envolvida em uma operação de exclusão em P é dita como excluída conectada a P.
Assim, uma tabela é excluída conectada à tabela P se for dependente de P ou dependente de uma tabela da qual excluir operações da cascata P.

Any table that can be involved in a delete operation on P is said to be delete-connected to P.
Thus, a table is delete-connected to table P if it is a dependent of P, or a dependent of a table to which delete operations from P cascade.

As seguintes restrições se aplicam a relacionamentos de exclusão conectados:
The following restrictions apply to delete-connected relationships:

  • Quando uma tabela é conectada para exclusão a si mesma em um ciclo referencial de mais de uma tabela, o ciclo não deve conter uma regra de exclusão de RESTRICT ou SET NULL.
    When a table is delete-connected to itself in a referential cycle of more than one table, the cycle must not contain a delete rule of either RESTRICT or SET NULL.

  • Uma tabela não deve ser uma tabela dependente em um relacionamento CASCADE (auto-referenciando ou referenciando outra tabela) e ter um relacionamento de autorreferência com uma regra de exclusão de RESTRICT ou SET NULL.
    A table must not both be a dependent table in a CASCADE relationship (self-referencing or referencing another table) and have a self-referencing relationship with a delete rule of either RESTRICT or SET NULL.

  • Quando uma tabela é conectada para exclusão a outra tabela por meio de vários relacionamentos em que tais relacionamentos têm chaves estrangeiras sobrepostas, esses relacionamentos devem ter a mesma regra de exclusão e nenhum deles pode ser SET NULL.
    When a table is delete-connected to another table through multiple relationships where such relationships have overlapping foreign keys, these relationships must have the same delete rule and none of these can be SET NULL.

  • Quando uma tabela é conectada para exclusão a outra tabela por meio de vários relacionamentos em que um dos relacionamentos é especificado com a regra de exclusão SET NULL, a definição de chave estrangeira deste relacionamento não deve conter nenhuma chave de distribuição ou coluna de chave MDC, uma coluna de chave de particionamento de tabela ou coluna de chave RCT.
    When a table is delete-connected to another table through multiple relationships where one of the relationships is specified with delete rule SET NULL, the foreign key definition of this relationship must not contain any distribution key or MDC key column, a table-partitioning key column, or RCT key column.

  • Quando duas tabelas são conectadas por exclusão à mesma tabela por meio de relacionamentos CASCADE, as duas tabelas não devem ser conectadas por exclusão uma à outra, onde os caminhos de exclusão conectados terminam com a regra de exclusão RESTRICT ou SET NULL.
    When two tables are delete-connected to the same table through CASCADE relationships, the two tables must not be delete-connected to each other where the delete connected paths end with delete rule RESTRICT or SET NULL.