How to create a required many-to-many relationship in SQLite?

Viewed 52

Suppose I have a schema like this:

CREATE TABLE Artist (
  ArtistID INTEGER NOT NULL,
  ArtistName TEXT NOT NULL,
  PRIMARY KEY (ArtistID)
);

CREATE TABLE Song (
  SongID INTEGER NOT NULL,
  SongTitle TEXT NOT NULL,
  PRIMARY KEY (SongID)
);

CREATE TABLE SongArtist (
  SongID INTEGER NOT NULL,
  ArtistID INTEGER NOT NULL,
  PRIMARY KEY (SongID, ArtistID),
  FOREIGN KEY (SongID) REFERENCES Song(SongID),
  FOREIGN KEY (ArtistID) REFERENCES Artist(ArtistID)
);

By defining a column as NOT NULL I can semantically say that having a value in it is required. How would I make a many-to-many relationship required, but only in one direction?

In this situation, what I mean is this: How can I say that a Song row must have at least one Artist row associated with it through the SongArtist join table? If I were to represent a song as the JSON object below, this would be equivalent to saying that the songArtistIds array must have a length of 1 or higher.

{
  songId: 745194,
  songTitle: "Title",
  songArtistIds: [523214]
}

However, an Artist row need not be associated with any Song row necessarily. An artist can have 0 or more songs, but a song must have 1 or more artists. How can I enforce this in SQLite? Also, if the answer is that I cannot do this in SQLite, then what alternative do I have for an embedded application?

0 Answers
Related