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

SQL Check Constraint that requires a not null value in a column based on the value of another column

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

Problem

I have a table with the following two columns

  • OnSite BIT NOT NULL



  • ClientId INT NULL



I want to add a constraint that requires ClientId to be NOT NULL when OnSite is true(1).

I could not find anything on the site.

Thanks

Solution

You want to enforce the implication:

(OnSite=true) => (ClientId is not null)


This can be rewritten as:

(OnSite=false) or (ClientId is not null)


Your constraint therefore becomes:

CHECK ( OnSite=0 or ClientId is not null)

Code Snippets

(OnSite=true) => (ClientId is not null)
(OnSite=false) or (ClientId is not null)
CHECK ( OnSite=0 or ClientId is not null)

Context

StackExchange Database Administrators Q#66681, answer score: 9

Revisions (0)

No revisions yet.