I want to create a database for my program. Most likely I will use SQLite, although others are an option.
I will have columns a
, b
, c
, d
. a
is unique and will be my primary key. b
, c
, d
are allowed to contain duplicate value.
However, I don't want combinations of b
, c
, d
to repeat. For instance, sample valid db:
a b c d
0 18 n kiwi
1 12 v kiwi
2 15 t orange
3 12 j kiwi
4 12 t banana
5 31 f apple
6 10 h kiwi
7 15 y orange
8 20 b apple
9 1 m grapefruit
10 7 s apple
11 4 h banana
12 31 t egg
Sample invalid db (rows 2
and 7
):
a b c d
0 18 n kiwi
1 12 v kiwi
2 15 y orange
3 12 j kiwi
4 12 t banana
5 31 f apple
6 10 h kiwi
7 15 y orange
8 20 b apple
9 1 m grapefruit
10 7 s apple
11 4 h banana
12 31 t egg
Is there standard database rule or concept that applies to this?
I can of course simply do validation in my code, by manually querying the db. I believe I could also construct a fifth bcd
column, which concatenates the other three, and is required to be unique. But both of these seem hacky. Is it possible to somehow "declare the columns unique in combination only" in a more direct and obvious way?
For instance, I could declare (b, c, d)
as my composite primary key (not sure if SQLite supports this but I think SQL does). That should accomplish my goal. However, I don't want these columns to actually be my PK.
Best Answer
Create an index instead. It has the same as the unique constraint.