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

Create a Constraint such that only one of two fields must be filled

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

Problem

I have a table in SQL server where the users need to enter data in either of two columns. That is, One of the two must have data inputted but at the same time i don't want to allow users to input in both columns. It's either or but one is a must.

Solution

You need to use a check constraint:

create table kevin
(
  one   integer, 
  other integer,
  constraint only_one_value 
        check (        (one is null or other is null) 
               and not (one is null and other is null) )
);


This ensures that at least one of the columns has a value and that not both have a value.

If those are varchar columns you might want to check for empty values ('') as well. To do that use nullif() which converts a value to null if it is equal to the second argument of the function.

create table kevin
(
  one   integer, 
  other integer,
  constraint only_one_value 
        check (        (nullif(one,'') is null or nullif(other,'') is null) 
               and not (nullif(one,'') is null and nullif(other,'') is null) )
);

Code Snippets

create table kevin
(
  one   integer, 
  other integer,
  constraint only_one_value 
        check (        (one is null or other is null) 
               and not (one is null and other is null) )
);
create table kevin
(
  one   integer, 
  other integer,
  constraint only_one_value 
        check (        (nullif(one,'') is null or nullif(other,'') is null) 
               and not (nullif(one,'') is null and nullif(other,'') is null) )
);

Context

StackExchange Database Administrators Q#190505, answer score: 26

Revisions (0)

No revisions yet.