5

As per the title: In SQL server is a check constraint applied before or after a default constraint on insert?

So taking the following table (Unnecessary columns omitted for brevity)...

CREATE TABLE [dbo].[Customer](
    [CountryCode] [varchar](5) NULL CONSTRAINT [CK_Customer_DefaultCountryCode]  DEFAULT ([app].[GetUnknownCountryIsoCountryCode]()),
) ON [PRIMARY]

...Which also has the following check constraint...

ALTER TABLE [admin].[Customer]  WITH CHECK 
    ADD  CONSTRAINT [CK_CustomerHasCountryWhenIntercompanyBusinessModel] 
    CHECK  (
        ([app].[BusinessModelMustHaveCountry]([BusinessModelId]) = (1) AND [app].[CheckCountryCodeExists]([CountryCode]) = (1) OR 
        [app].[BusinessModelMustHaveCountry]([BusinessModelId]) <> (1))
    )
GO

... will the default constraint be applied and populate the default value before the check constraint is applied?

2
  • 2
    I would assume the default is applied first - it'll decide what to try insert before trying to insert it and verifying the check constraint. It should be easy to test the behaviour. One thing to note: default constraints do not fire if a NULL value is inserted, even for NOT NULL columns, and some people expect them to. Commented Dec 15, 2016 at 12:19
  • @DavidSpillett +1 for the extra information about NULL inserts in NOT NULL columns. I'd did not know that - Thank you
    – Dib
    Commented Dec 15, 2016 at 12:47

1 Answer 1

11

The check constraint is applied after.

You can see this from the fact that the following succeeds.

DECLARE @T TABLE(X INT DEFAULT 1 CHECK (X = 1)); 

INSERT @T DEFAULT VALUES;

Also the execution plan shows that the assert operator operates on the values output from the table insert operator so is checking the values that were actually inserted.

enter image description here

0

Your Answer

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

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