Database Design – Best Practices for Inventory Database Design

data modelingdatabasedatabase-design

I am starting to design a typical product based MySQL database but I keep running in circles on how to design the tables.

I have many types of products

  • Jeans
  • Tshirts
  • Dresses

Which have many of the same attributes

  • Size
  • Price
  • Colour

But some of the products have specific attributes, like length or logo or package.

Do I make a separate table for every product even though many of the columns are the same, or do I make a general product table and then have some sub-tables for specific products?

Best Answer

Do not make a table for every product.

This problem has been solved many ways. Try this:

Make a product (or products) table, put your common product attributes in the product table, then make an attribute table and a productattribute table, something like:

attribute
---------
attributeId
attributeName
attributeDescription


productattribute
----------------
productId
attributeId
attributeValue

Then you can assign arbitrary attributes to your products.

You can take the schema a little further if you like, using:

attribute
---------
attributeId
attributeName
attributeDescription
attributeType // [float, int, varchar, etc.]


productAttribute
----------------
productId
attributeId
attributeValueFloat
attributeValueInt
attributeValueVarChar

This technique complicates your schema a bit, so be aware of what you are getting into if you decide to use the extra columns to store values by data type.

An alternative that might just suit your needs a little better would be to use a NoSQL Store like MongoDB for your products. Then you can store the attributes you need for each type of product without resorting to the complexity of a relational database schema.