There is no conclusion that composite primary keys are bad.
Best practice is to have some columns or columns that uniquely identify a row. But in some tables, a single column alone is not enough to uniquely identify a row.
SQL (and the relational model) allows you to use a composite primary key. In some cases, this is a good practice. Or another way to look at it is not a bad practice in all cases.
Some people believe that each table should have an integer column that automatically generates unique values and should serve as a primary key. Some people also claim that this primary key column should always be called id . But these are conventions, not necessarily best practices. Conventions have certain benefits, as they simplify certain decisions. But conventions are also restrictive.
You may have an order with several payments, because some people buy on layaway , otherwise they have several payment sources (for example, two credit cards) or two different people want to pay for a share of the order (I often go to a restaurant with a friend, and we each pay for our own food, so staff processes half the order on each of our credit cards).
I would develop a system that you describe as follows:
Products : product_id (PK) Orders : order_id (PK) LineItems : product_id is (FK) to Products order_id is (FK) to Orders (product_id, order_id) is (PK) Payments : order_id (FK) payment_id - ordinal for each order_id (order_id, payment_id) is (PK)
It is also related to the concept of identifying relationships . If he determines that the payment exists only because there is order, then make part of the primary key order.
Note that the LineItems table also lacks its own auto-increment, a primary key with one column. The many-to-many table is a classic example of the good use of a composite primary key.
Bill Karwin Sep 27 '14 at 19:58 2014-09-27 19:58
source share