I have a table:
CREATE TABLE pupils (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
name TEXT, surname TEXT, address TEXT, score INTEGER
);
where score
is a percentage.
Is it more efficient to have the integer value in there or a foreign key to a table that is just a table like this?
CREATE TABLE score (percentage INTEGER PRIMARY KEY NOT NULL);
Obviously the table would be populated with 0-100.
My thoughts were if you have 1000's of pupils that keeping it as an integer column would mean queries were faster, but more space used and using the foreign key would mean less space used, but slower queries.
Not sure if this is correct?
So I thought I would throw it out there!
If you use the FOREIGN KEY to protect the score
value in the pupils
table, you still need to have a score column in pupils
. You can't have a FOREIGN KEY relationship without columns in both tables.
The only advantage of the FOREIGN KEY is that it would let you restrict the values allowed in the score
column to integers between 1 and 100. The same thing can be done, however, with a CHECK constraint on the column, without the need for the extra table.
If you use the FOREIGN KEY, your DDL would look like this:
CREATE TABLE pupils (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
name TEXT, surname TEXT, address TEXT, score INTEGER REFERENCES score(percentage)
);
Note that the score column is still there.
In this case the FOREIGN KEY approach adds an whole table and two indexes that have to be maintained. Much more efficient to use one table and a CHECK constraint.