Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good idea to design database with inheritance?

For example, I have 2 tables : 'customer' and 'staff'. They are almost the same, only 2 attributes are different. So should I create another table named 'person' contains all of the same attributes of 'customer' and 'staff' then create fk keys point to this 'person'? Something like inheritance in class design.

Is there any drawback to this method ?

like image 655
JatSing Avatar asked Sep 12 '11 06:09

JatSing


People also ask

What is inheritance in database design?

Inheritance enables you to share attributes between objects such that a subclass inherits attributes from its parent class.

What data model uses inheritance?

The Entity Data Model (EDM) supports inheritance for entity types. Inheritance in the EDM is similar to inheritance for classes in object-oriented programming languages.

Does SQL support inheritance?

SQL object inheritance is based on a family tree of object types that forms a type hierarchy. The type hierarchy consists of a parent object type, called a supertype, and one or more levels of child object types, called subtypes, which are derived from the parent.

Is a way to emulate object-oriented inheritance in relational database?

Single table inheritance is a way to emulate object-oriented inheritance in a relational database.


1 Answers

Yes, there is a drawback to that method. Joins increase query complexity (immensely so in some cases) and can increase query time if you're not careful.

Instead, the standard way to do this (i.e. simulate object inheritance when only a few attributes differ between the subclasses) is to do something called Single Table Inheritance. This method prevents database joins at the cost of a little bit of unused database space.

It works like this: You create one table that contains all the attributes, including the ones that only apply to one or the other, as well as a type attribute to specify the object type. For example, if customer has attributes:

id, name, email, password, order_date

AND staff has attributes:

id, name, email, password, hire_date

Then you create one table with columns for all the attributes and a type:

id, type, name, email, password, order_date, hire_date

The type column will always contain either "customer" or "staff". If type is "customer", then hire_date is always NULL, and is meaningless. If type is "staff" then order_date is always NULL, and is meaningless.

like image 136
Ben Lee Avatar answered Oct 10 '22 03:10

Ben Lee