I have a table called, ‘Songs’. This is the table structure.
- The table has an AlbumID column, which will be a foreign key reference to the Album table.
- The Songs table also has a ‘status’ column. Where it can be either ‘Released’ or ‘Unreleased’.
Currently, the AlbumID column is NOT NULL. And has to be filled in.
However, I was curious if anything similar to something like a conditional null exists. I wanted it to be that the AlbumID field is only NOT NULL, if the status = "Released". If the song is released, then you have to enter the AlbumID. If the song is not released, AlbumID does not need to be filled.
Here is the structure of my SongsInfo table right now.
SongID int(11) NOT NULL AUTO_INCREMENT,
SongName varchar(100) NOT NULL,
AlbumID int(11) NOT NULL,
ArtistID int(11) NOT NULL,
GenreID int(11) NOT NULL,
PRIMARY KEY (SongID),
FOREIGN KEY (AlbumID) REFERENCES AlbumInfo(AlbumID),
FOREIGN KEY (ArtistID) REFERENCES ArtistInfo(ArtistID),
FOREIGN KEY (GenreID) REFERENCES GenreInfo(GenreID)
2
Answers
You can get this behavior with a check constraint:
You can use a
CHECK
constraint, as in:Then, the following INSERTs succeed:
But the following INSERT fails as expected:
See running example at db<>fiddle.