-1

So I'm developing an e-commerce website, and I have a product with many categories.

So my concern is, what if I have 1000 products and each of them has 5 categories, so is it unavoidable to have 5000 rows on my table whereas I only have 1000 products? Or is there any other way to implement it? I'm using postgresql for my database.

My simplified table structures:

products table

| id | item_code | category_id | 

category table

| id | description |
  • 3
    What's the problem with 5000 rows? This is considered extremely tiny these days. I usually don't start performance testing with less than a million rows. – a_horse_with_no_name Apr 3 at 9:19
  • 2
    Don't you think you need a third table? – Sami Apr 3 at 9:41
2

You need to create a third table which will hold the ProductId and the CategoryId, both are a PRIMARY KEY (composite primary key).

So your tables will be like:

Products table: ProductId PK

+-----------+-----------+
| ProductId | item_code |
+-----------+-----------+
|           |           |
+-----------+-----------+

Categories table: CategoryId PK

+------------+-------------+
| CategoryId | Description |
+------------+-------------+
|            |             |
+------------+-------------+

ProductCategories table:

ProductId, CategoryId PK

ProductId FK Reference Products(ProductId)

CategoryId FK Reference Categories(CategoryId)

+-----------+------------+
| ProductId | CategoryId |
+-----------+------------+
|           |            |
+-----------+------------+

Colnclusion:

+-------------------+------------+-------+-----------------+------------------+
|     TableName     | ColumnName | Kind  | ReferencedTable | ReferencedColumn |
+-------------------+------------+-------+-----------------+------------------+
| Products          | ProductId  | PK    |                 |                  |
| Categories        | CategoryId | PK    |                 |                  |
| ProductCategories | ProductId  | PK/FK | Products        | ProductId        |
| ProductCategories | CategoryId | PK/FK | Categories      | CategoryId       |
+-------------------+------------+-------+-----------------+------------------+
  • 1
    Note that in Postgres you could also use an array for the categories. That makes the schema simpler, but it comes at a price (namely there are chances it will be less efficient when querying, and a bit cumbersome when updating). – dezso Apr 4 at 9:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.