Search code examples
sqlpostgresqlconstraintscreate-tablenotnull

Attribute that is not null when an other attribute is also not null in SQL


I wanted to create a table for Articles, that can have (but don't need to have) a link to an img-Source. For all Articles that have the link also an img-Type is needed (which should be 'png', 'svg' or 'jpg'). I don't quite understand how I can make the img-Type field not null only for values where the img-Src field is not null.

Here is my code (without not null/null constraints for the fields img-Type and img-Src)

create TABLE Article(
articleID varchar(15) primary key ,
articleDescription varchar (80) null ,
imgSrc varchar (20)  ,
imgType  char(3),
check imgType = 'png' or imgType = 'svg' or imgType = 'jpg'
);

Solution

  • add a new constraint where you check if both values are null or both values are not null

    check (imgSrc is not null and imgType is not null 
        or imgSrc is null and imgType is null)