Domanda

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!

È stato utile?

Soluzione

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.

Altri suggerimenti

There is no need for normalizing the value of score.

It's a value, it belongs to the first table.

That would create an unneeded link (to an integer), that wouldn't really impact performance per say, but it would affect readability.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top