HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlModerate

In SQL server is a check constraint applied before or after a default constraint on insert?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
afterinsertsqlapplieddefaultconstraintserverbeforecheck

Problem

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?

Solution

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.

Code Snippets

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

INSERT @T DEFAULT VALUES;

Context

StackExchange Database Administrators Q#158247, answer score: 11

Revisions (0)

No revisions yet.