---
title: "Initially immediate vs initially deferred"
author: "fantasyday"
date: "2009-02-09T13:40:00Z"
tags: []
slug: "initially-immediate-vs-initially-deferred"
draft: false
lastmod: "2009-02-09T13:55:07Z"
id: 325630
url: "https://fantasyday.iteye.com/blog/325630"
---

<span style="color:blue">Initially immediate</span>

This is the default when neither initially immediate nor initially deferred has been specified. 
The constraint is checked after each SQL statement.

```sql
create table init_immediate (
  id   number primary key initially immediate,
  data varchar2(50)
);
```


<span style="color:blue">Initially deferred</span>

The constraint is checked when a transaction ends.
drop table init_immediate;


```sql
create table init_immediate (
  id   number       primary key initially deferred,
  data varchar2(50) not null initially deferred
);


insert into init_immediate values ( null, 'one');
insert into init_immediate values (    3, null);
insert into init_immediate values (    8, 'eight');
insert into init_immediate values (    3, 'two');

update init_immediate set id = 1 where data = 'one';
update init_immediate set id = 2 where data = 'two';
update init_immediate set data = 'three' where id = 3;

commit;
```

It will be OK.

<span style="color:blue">ORA-02447</span>

A not deferrable constraint cannot be set to initially deferred, 
it raises an **ORA-02447: cannot defer a constraint that is not deferrable** which seems logical:

```sql
create table no_no_ora_02447 (
  id   number primary key not deferrable initially deferred,
  data varchar2(50)
);
```


<span style="color:blue">Deferrable constraint</span>

```sql
create table cons_deferrable_pk_tab (
  a number,
  b varchar2(10),
  c number not null deferrable,
  d date,
  primary key (a, b) deferrable
);

create table cons_deferrable_fk_tab (
  z,
  y,
  x varchar2(10),
  foreign key (z,y) references cons_deferrable_pk_tab deferrable
);
```


Now we insert data to the table will fails, because reference table has not been inserted data yet.

```sql
insert into cons_deferrable_fk_tab values (1, 'one', 'foo');
```

**ORA-02291: 整合性制約(ZOLO.SYS_C005382)に違反しました - 親キーがありません**


```sql
set constraints all deferred
```


And now the constraints are deferred, so we can insert data which still not inserted to the reference table.


```sql
insert into cons_deferrable_fk_tab values (1, 'one', 'foo');
```


Though commit will fail.

<span style="color:blue">set constraints </span>

```sql
set constraint[s] all { immediate | deferred };
set constraint[s] constraint-name-1 [, constraint-name-n ...] { immediate | deferred };
```