Composite Foreign Key Example

Introduction

In this example we have two tables, album and song and we're using the SQLite dialect.

We will link these together by using a foreign key.

The album table uses a composite primary key (album_artist,album_name), so the foreign key will be a composite foreign key to match.

The song_album column will reference the album_name column,
the song_artist column will reference the album_artist column.

Requirements

Tables and Fields

We've already created all of the tables and columns including those used by the foreign key.
We have added a primary key to both tables. The primary key on the album table includes both album_name and album_artist.

Inspector

You will need to use the inspector to complete this task.
Use the sidebar control in the window toolbar to display the right hand sidebar if it is not visible

Sidebar Control

If you want to follow along, either download the example starting file or paste the following text into a new empty SQLEditor document (with dialect SQLite).

/* SQLEditor (SQLite)*/ CREATE TABLE album ( album_artist TEXT, album_name TEXT, album_cover BINARY, PRIMARY KEY (album_artist,album_name) ); CREATE TABLE song ( song_id INTEGER PRIMARY KEY, song_artist TEXT, song_album TEXT, song_name TEXT );



Procedure

There are 9 steps:

  1. Create a foreign key object in the song table. Use the popup menu or
    Menu->Object->Add Foreign Key
  2. Drag from the new foreign key object to the album table title bar
  3. Make sure the foreign key that you added is still selected. Click to select it if it isn't.
  4. Add the first column pair to the foreign key by using the [+] button at the bottom of the inspector
  5. select song_artist under column in the field pair section of the inspector
  6. select album_artist under references column
  7. Add the second column pair to the foreign key by using the [+] button at the bottom of the inspector
  8. select song_album under column
  9. select album_name under references column

Video

Download instead.

Output

The foreign key is now complete.

The source (left) sidebar should show the SQL:

/* SQLEditor (SQLite)*/ CREATE TABLE album ( album_artist TEXT, album_name TEXT, album_cover BINARY, PRIMARY KEY (album_artist,album_name) ); CREATE TABLE song ( song_id INTEGER PRIMARY KEY, song_artist TEXT, song_album TEXT, song_name TEXT, FOREIGN KEY (song_artist,song_album) REFERENCES album (album_artist,album_name) );

Download Example Files

Starting File: Starting File

End File: End File

Support Updates


Contact Us

To contact us with a support issue please email:

support@malcolmhardie.com