Search code examples
databaserelational-databaseentity-attribute-value

Best way to extend information on a relational database


Let's say that we have to store information of different types of product in a database. However, these products have different specifications. For example:

  • Phone: cpu, ram, storage...
  • TV: size, resolution...

We want to store each specification in a column of a table, and all the products (whatever the type) must have a different ID.

To comply with that, now I have one general table named Products (with an auto increment ID) and one subordinate table for each type of product (ProductsPhones, ProductsTV...) with the specifications and linked with the principal with a Foreign Key.

I find this solution inefficient since the table Products has only one column (the auto incremented ID).

I would like to know if there is a better approach to solve this problem using relational databases.


Solution

  • The short answer is no. The relational model is a first-order logical model, meaning predicates can vary over entities but not over other predicates. That means dependent types and EAV models aren't supported.

    EAV models are possible in SQL databases, but they don't qualify as relational since the domain of the value field in an EAV row depends on the value of the attribute field (and sometimes on the value of the entity field as well). Practically, EAV models tend to be inefficient to query and maintain.

    PostgreSQL supports shared sequences which allows you to ensure unique auto-incremented IDs without a common supertype table. However, the supertype table may still be a good idea for FK constraints.

    You may find some use for your Products table later to hold common attributes like Type, Serial number, Cost, Warranty duration, Number in stock, Warehouse, Supplier, etc...