SQL Server Constraints – Is a Check Constraint Applied Before or After a Default Constraint on Insert?

check-constraintsconstraintdefault valuesql server

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?

Best Answer

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