I have this table:
CREATE TABLE public.data_source__instrument (
instrument_id int4 NOT NULL,
data_source_id int4 NOT NULL,
CONSTRAINT data_source__instrument__pk PRIMARY KEY (data_source_id, instrument_id)
);
For clarity, here's an example of the data I might have in this table:
instrument_id | data_source_id |
---|---|
1 | 1 |
1 | 2 |
1 | 3 |
2 | 2 |
2 | 3 |
I would like to be able to set a favourite data source for each instrument. I'd also like each instrument to have 1 and only 1 favourite data source.
The solution I came up with is the below:
CREATE TABLE public.data_source__instrument (
instrument_id int4 NOT NULL,
data_source_id int4 NOT NULL,
fav_data_source boolean NULL, -- ### new column ###
CONSTRAINT data_source__instrument__pk PRIMARY KEY (data_source_id, instrument_id),
CONSTRAINT fav_data_source UNIQUE (instrument_id,fav_data_source) -- ### new constraint ###
);
I chose to mark favourites with the value true
and set non-favourite tuples to null
(because the unique constraint doesn't affect NULLs).
This solution will allow at most one true value per instrument in the fav_data_source
column.
Example:
instrument_id | data_source_id | fav_data_source |
---|---|---|
1 | 1 | true |
1 | 2 | null |
1 | 3 | null |
2 | 2 | null |
2 | 3 | true |
However, I'm not completely satisfied with this solution. For starters, it allows instruments without a favourite data source. Moreover, the value of the fav_data_source
could be set to false
which is confusing and not very useful (since it doesn't play well with the unique constraint).
Is there a better way of doing this? Am I overlooking something?
EDIT: Ideally, I'd prefer a simple solution to this problem and avoid using features like database triggers.