126

I read this about the SQL keyword DEFERRABLE in Database Systems - The Complete Book.

The latter [NOT DEFERRABLE] is default, and means that every time a database modification statement is executed, the constraint is checked immediately afterwards, if the modification could violate the foreign-key constraint.

However, if we declare a constraint to be DEFERRABLE, then we have the option of having it wait until a transaction is complete before checking the constraint.

We follow the keyword DEFERRABLE by either INITIALLY DEFERRED or INITIALLY IMMEDIATE. In the former case, checking will be deferred to just before each transaction commits. In the latter case, the check will be made immediately after each statement.

How is NOT DEFERRABLE different from DEFERRABLE INITIALLY IMMEDIATE? In both cases, it seems, any constraints are checked after each individual statement.

5 Answers 5

82

With DEFERRABLE INITIALLY IMMEDIATE you can defer the constraints on demand when you need it.

This is useful if you normally want to check the constraints at statement time, but for e.g. a batch load want to defer the checking until commit time.

The syntax how to defer the constraints is different for the various DBMS though.

With NOT DEFERRABLE you will never ever be able to defer the checking until commit time.

3
  • 1
    @romkyns: DEFERRABLE states the designer's intention that deferring the constraint is a worthwhile or necessary action. This is not the case for the vast majority of database constraints and labelling all as DEFERRABLE would lose this useful distinction.
    – onedaywhen
    Dec 21, 2011 at 15:44
  • 4
    @onedaywhen A colleague of mine has since pointed out a good valid reason, actually: you can rely on non-deferrable constraints at any point of any transaction, but deferrable ones are only definitely observed at the start of a transaction. Dec 21, 2011 at 16:28
  • @RomanStarkov Also, it a matter of performance. NOT DEFERRABLE is usually the fastest.
    – Teejay
    Dec 20, 2018 at 8:54
79

Aside from the other (correct) answers, when speaking of PostgreSQL, it must be stated that:

  • with NOT DEFERRABLE each row is checked at insert/update time

  • with DEFERRABLE (currently IMMEDIATE) all rows are checked at the end of the insert/update

  • with DEFERRABLE (currently DEFERRED) all rows are checked at the end of the transaction

So it's not correct to say that a DEFERRABLE constraint set to IMMEDIATE acts like a NOT DEFERRABLE one.


Let's elaborate on this difference:

CREATE TABLE example(
    row integer NOT NULL,
    col integer NOT NULL,
    UNIQUE (row, col) DEFERRABLE INITIALLY IMMEDIATE
);

INSERT INTO example (row, col) VALUES (1,1),(2,2),(3,3);

UPDATE example SET row = row + 1, col = col + 1;

SELECT * FROM example;

This correctly outputs:

output

But if we remove the DEFERRABLE INITIALLY IMMEDIATE instruction,

ERROR: duplicate key value violates unique constraint "example_row_col_key" DETAIL: Key ("row", col)=(2, 2) already exists. ********** Error **********

ERROR: duplicate key value violates unique constraint "example_row_col_key" SQL state: 23505 Detail: Key ("row", col)=(2, 2) already exists.


ADDENDUM (October 12, 2017)

This behavior is indeed documented here, section "Compatibility":

Also, PostgreSQL checks non-deferrable uniqueness constraints immediately, not at end of statement as the standard would suggest.

5
  • 1
    Interesting. It seems to me that there's basically no reason to prefer the "NOT DEFERRABLE" behaviour to the "IMMEDIATE" behaviour and that it would make sense for Postgres to be more forgiving and make NOT DEFERRABLE behave like "IMMEDIATE". The order in which rows are updated in an UPDATE statement isn't even documented or specced as far as I know, so isn't the behaviour of this mid-statement constraint checking is at least partially unspecified? I can't see why anyone would want that behaviour - but perhaps there's a reasonable use case for it that I lack the imagination to see.
    – Mark Amery
    Oct 11, 2017 at 15:23
  • 1
    Yes, basically the only reason to prefer NOT DEFERRABLE is speed (see here, section Non-deferred Uniqueness Constraints, "Be aware that this can be significantly slower than immediate uniqueness checking").
    – Teejay
    Oct 12, 2017 at 10:58
  • 1
    Also, DEFERRABLE constraint cannot be referenced as foreign keys in other tables (see here, section Parameters, "The referenced columns must be the columns of a non-deferrable unique or primary key constraint in the referenced table").
    – Teejay
    Oct 12, 2017 at 10:59
  • 1
    So as a rule of thumb, if it doesn't really matter to the business logic when the constraint is checked, then should I default to using NOT DEFERRABLE simply because it performs better?
    – davidtgq
    Oct 12, 2017 at 11:03
  • 1
    In our ORM we now use the following rules: 1) if the constraint is a PK, we use NOT DEFERRABLE 2) if at least one FK references the constraint, we use NOT DEFERRABLE as well 3) in the other cases, we use DEFERRABLE INITIALLY IMMEDIATE. This could slightly decreases performance of those constraints, but ensures maximum compatibility with other DBMS we use (Oracle, SqlServer). PK and FK are not an issue because we never update their values (which I think is a good programming habit for DBs).
    – Teejay
    Oct 12, 2017 at 11:12
32

Aside from the obvious of being able to defer, the difference is actually performance. If there wasn't a performance penalty then there would be no need to have an option to choose deferrable or not -- all constraints would simply be deferrable.

The performance penalty has to do with optimizations that the database can perform given the knowledge of how the data is restricted. For example, the index that is created to back a unique constraint in Oracle cannot be a unique index if the constraint is deferrable since temporarily allowing duplicates must be allowed. However, if the constraint is not deferrable then the index can be unique.

10

I'm very late to the party but I wanted to add that -- as of December 2018 -- only two databases I know of (there may be more) offer some level of implementation of this standard SQL feature:

Database    NOT DEFERRABLE  DEFERRABLE           DEFERRABLE 
                            INITIALLY IMMEDIATE  INITIALLY DEFERRED
----------  --------------  -------------------  ------------------
Oracle      N/A*1           Yes (default)        Yes
PostgreSQL  Yes (default)   Yes                  Yes
DB2         -               -                    -
SQL Server  -               -                    -
MySQL       -               -                    -
MariaDB     -               -                    -
SAP Sybase  -               -                    -
HyperSQL    -               -                    -
H2          -               -                    -
Derby       -               -                    -

*1 Even though Oracle 12c accepts the NOT DEFERRABLE constraint state, it actually ignores it and makes it work as DEFERRABLE INITIALLY IMMEDIATE.

As you see, Oracle does not implement the first type (NOT DEFERRABLE), and that's why developers using Oracle (the OP in this case) may get confused and consider the first two types equivalent.

Interestingly enough Oracle and PostgreSQL have a different default type. Maybe it has performance implications.

5

NOT DEFERRABLE - you cannot change the constraint checking, oracle checks it after each statement(i.e. directly after insert statement).

DEFERRABLE INITIALLY IMMEDIATE - oracle checks constraint after each statement. BUT, you can change it to after each transaction(i.e. after commit):

set constraint pk_tab1 deferred;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.