<p>Example</p>

<p>I have <code>Person</code>, <code>SpecialPerson</code>, and <code>User</code>. <code>Person</code> and <code>SpecialPerson</code> are just people - they don't have a user name or password on a site, but they are stored in a database for record keeping. User has all of the same data as <code>Person</code> and potentially <code>SpecialPerson</code>, along with a user name and password as they are registered with the site.</p>

<hr>

<p>How would you address this problem? Would you have a <code>Person</code> table which stores all data common to a person and use a key to look up their data in <code>SpecialPerson</code> (if they are a special person) and User (if they are a user) and vice-versa?</p>

[{'answer_id': 45631, 'author': 'Chris Roberts', 'author_id': 475, 'author_profile': 'https://Stackoverflow.com/users/475', 'pm_score': -1, 'selected': False, 'text': "<p>Personally, I would store all of these different user classes in a single table.  You can then either have a field which stores a 'Type' value, or you can imply what type of person you're dealing with by what fields are filled in.  For example, if UserID is NULL, then this record isn't a User.</p>\n\n<p>You could link out to other tables using a one to one-or-none type of join, but then in every query you'll be adding extra joins.</p>\n\n<p>The first method is also supported by LINQ-to-SQL if you decide to go down that route (they call it 'Table Per Hierarchy' or 'TPH').</p>\n"}, {'answer_id': 45632, 'author': 'Danimal', 'author_id': 2757, 'author_profile': 'https://Stackoverflow.com/users/2757', 'pm_score': 0, 'selected': False, 'text': "<p>In the past I've done it exactly as you suggest -- have a Person table for common stuff, then SpecialPerson linked for the derived class. However, I'm re-thinking that, as Linq2Sql wants to have a field in the same table indicate the difference. I haven't looked at the entity model too much, though -- pretty sure that allows the other method. </p>\n"}, {'answer_id': 45638, 'author': 'Sara Chipps', 'author_id': 4140, 'author_profile': 'https://Stackoverflow.com/users/4140', 'pm_score': 1, 'selected': False, 'text': "<p>yes, I would also consider a TypeID along with a PersonType table if it is possible there will be more types. However, if there is only 3 that shouldn't be nec. </p>\n"}, {'answer_id': 45643, 'author': 'Mat Roberts', 'author_id': 4401, 'author_profile': 'https://Stackoverflow.com/users/4401', 'pm_score': 3, 'selected': False, 'text': "<p>If the User, Person and Special person all have the same foreign keys, then I would have a single table.  Add a column called Type which is constrained to be User, Person or Special Person.  Then based on the value of Type have constraints on the other optional columns.</p>\n\n<p>For the object code it doesn't make much difference if you have the separate tables or multiple tables to represent polymorphism.  However if you have to do SQL against the database, its much easier if the polymorphism is captured in single table...provided the foreign keys for the sub types are the same.  </p>\n"}, {'answer_id': 45646, 'author': 'Lars Mæhlum', 'author_id': 960, 'author_profile': 'https://Stackoverflow.com/users/960', 'pm_score': 2, 'selected': False, 'text': "<p>I'd say that, depending on what differentiates Person and Special Person, you probably don't want polymorphism for this task.  </p>\n\n<p>I'd create a User table, a Person table that has a nullable foreign key field to User (i.e, the Person can be a User, but does not have to).<br>\nThen I would make a SpecialPerson table which relates to the Person table with any extra fields in it. If a record is present in SpecialPerson for a given Person.ID, he/she/it is a special person.</p>\n"}, {'answer_id': 45647, 'author': 'Mendelt', 'author_id': 3320, 'author_profile': 'https://Stackoverflow.com/users/3320', 'pm_score': 7, 'selected': True, 'text': "<p>There are generally three ways of mapping object inheritance to database tables. </p>\n\n<p>You can make one big table with all the fields from all the objects with a special field for the type. This is fast but wastes space, although modern databases save space by not storing empty fields. And if you're only looking for all users in the table, with every type of person in it things can get slow. Not all or-mappers support this.</p>\n\n<p>You can make different tables for all the different child classes with all of the tables containing the base-class fields. This is ok from a performance perspective. But not from a maintenance perspective. Every time your base-class changes all the tables change.</p>\n\n<p>You can also make a table per class like you suggested. This way you need joins to get all the data. So it's less performant. I think it's the cleanest solution.</p>\n\n<p>What you want to use depends of course on your situation. None of the solutions is perfect so you have to weigh the pros and cons.</p>\n"}, {'answer_id': 45656, 'author': 'HS.', 'author_id': 618, 'author_profile': 'https://Stackoverflow.com/users/618', 'pm_score': 3, 'selected': False, 'text': "<p>What I'm going to say here is going to send database architects into conniptions but here goes:</p>\n\n<p>Consider a database <em>view</em> as the equivalent of an interface definition.\nAnd a table is the equivalent of a class.</p>\n\n<p>So in your example, all 3 person classes will implement the IPerson interface.\nSo you have 3 tables - one for each of 'User', 'Person' and 'SpecialPerson'.</p>\n\n<p>Then have a view 'PersonView' or whatever that selects the common properties (as defined by your 'interface') from all 3 tables into the single view.\nUse a 'PersonType' column in this view to store the actual type of the person being stored.</p>\n\n<p>So when you're running a query that can be operated on any type of person, just query the PersonView view. </p>\n"}, {'answer_id': 45683, 'author': 'Ubiguchi', 'author_id': 2562, 'author_profile': 'https://Stackoverflow.com/users/2562', 'pm_score': 3, 'selected': False, 'text': "<p>There's three basic strategies for handling inheritance in a relational database, and a number of more complex/bespoke alternatives depending on your exact needs.</p>\n\n<ul>\n<li>Table per class hierarchy. One table for the whole hierarchy.</li>\n<li>Table per subclass. A separate table is created for every sub class with a 0-1 association between the subclassed tables.</li>\n<li>Table per concrete class. A single table is created for every concrete class.</li>\n</ul>\n\n<p>Each of these appoaches raises its own issues about normalization, data access code, and data storage, although my personal preferance is to use <em>table per subclass</em> unless there's a specific performance or structural reason to go with one of the the alternatives.</p>\n"}, {'answer_id': 45690, 'author': 'kaybenleroll', 'author_id': 277, 'author_profile': 'https://Stackoverflow.com/users/277', 'pm_score': 3, 'selected': False, 'text': "<p>At the risk of being an 'architecture astronaut' here, I would be more inclined to go with separate tables for the subclasses. Have the primary key of the subclass tables also be a foreign key linking back to the supertype.</p>\n\n<p>The main reason for doing it this way is that it then becomes much more logically consistent and you do not end up with a lot of fields that are NULL and nonsensical for that particular record. This method also makes it much more easy to add extra fields to the subtypes as you iterate your design process.</p>\n\n<p>This does add the downside of adding JOINs to your queries, which can impact performance, but I almost always go with an ideal design first, and then look to optimise later if it proves to be necessary. The few times I have gone the 'optimal' way first I have almost always regretted it later.</p>\n\n<p>So my design would be something like</p>\n\n<p>PERSON (personid, name, address, phone, ...)</p>\n\n<p>SPECIALPERSON (personid REFERENCES PERSON(personid), extra fields...)</p>\n\n<p>USER (personid REFERENCES PERSON(personid), username, encryptedpassword, extra fields...)</p>\n\n<p>You could also create VIEWs later on that aggregates the supertype and the subtype, if that is necessary.</p>\n\n<p>The one flaw in this approach is if you find yourself heavily searching for the subtypes associated with a particulare supertype. There is no easy answer to this off the top of my head, you could track it programmatically if necessary, or else run soem global queries and cache the results. It will really depend on the application.</p>\n"}, {'answer_id': 45770, 'author': 'Radu094', 'author_id': 3263, 'author_profile': 'https://Stackoverflow.com/users/3263', 'pm_score': 3, 'selected': False, 'text': '<p>This might not be what the OP meant to ask, but I thought I might throw this in here.</p>\n\n<p>I recently had a unique case of db polymorphism in a project. We had between 60 to 120 possible classes, each with its own set of 30 to 40 unique attributes, and about 10 - 12 common attributes on all the classes . We decided to go the SQL-XML route and ended up with a single table. Something like :</p>\n\n<pre><code>PERSON (personid,persontype, name,address, phone, XMLOtherProperties)\n</code></pre>\n\n<p>containing all common properties as columns and then a big XML property bag. The ORM layer was then responsible for reading/writing the respective properties from the XMLOtherProperties. A bit like :</p>\n\n<pre><code> public string StrangeProperty\n{\nget { return XMLPropertyBag["StrangeProperty"];}\nset { XMLPropertyBag["StrangeProperty"]= value;}\n}\n</code></pre>\n\n<p>(we ended up mapping the xml column as a Hastable rather than a XML doc, but you can use whatever suits your DAL best)</p>\n\n<p>It\'s not going to win any design awards, but it will work if you have a large (or unknown) number of possible classes. And in SQL2005 you can still use XPATH in your SQL queries to select rows based on some property that is stored as XML.. it\'s just a small performance penalty to take in.</p>\n'}, {'answer_id': 45784, 'author': 'Vitor Silva', 'author_id': 1842864, 'author_profile': 'https://Stackoverflow.com/users/1842864', 'pm_score': 6, 'selected': False, 'text': '<p>Take a look at Martin Fowler\'s <em><a href="http://www.martinfowler.com/eaaCatalog/" rel="noreferrer">Patterns of Enterprise Application Architecture</a></em>:</p>\n\n<ul>\n<li><p><a href="http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html" rel="noreferrer">Single Table Inheritance</a>:</p>\n\n<blockquote>\n  <p>When mapping to a relational database, we try to minimize the joins that can quickly mount up when processing an inheritance structure in multiple tables. Single Table Inheritance maps all fields of all classes of an inheritance structure into a single table.</p>\n</blockquote></li>\n<li><p><a href="http://www.martinfowler.com/eaaCatalog/classTableInheritance.html" rel="noreferrer">Class Table Inheritance</a>:</p>\n\n<blockquote>\n  <p>You want database structures that map clearly to the objects and allow links anywhere in the inheritance structure. Class Table Inheritance supports this by using one database table per class in the inheritance structure.</p>\n</blockquote></li>\n<li><p><a href="http://www.martinfowler.com/eaaCatalog/concreteTableInheritance.html" rel="noreferrer">Concrete Table Inheritance</a>:</p>\n\n<blockquote>\n  <p>Thinking of tables from an object instance point of view, a sensible route is to take each object in memory and map it to a single database row. This implies Concrete Table Inheritance, where there\'s a table for each concrete class in the inheritance hierarchy.</p>\n</blockquote></li>\n</ul>\n'}, {'answer_id': 11532085, 'author': 'Kashyap Shah', 'author_id': 1357544, 'author_profile': 'https://Stackoverflow.com/users/1357544', 'pm_score': 2, 'selected': False, 'text': "<p>In our company we deal with polymorphism by combining all the fields in one table and its worst and no referential integrity can be enforced and very difficult to understand model. I would recommend against that approach for sure.</p>\n\n<p>I would go with Table per subclass and also avoid performance hit but using ORM where we can avoid joining with all subclass tables by building query on the fly by basing on type. The aforementioned strategy works for single record level pull but for bulk update or select you can't avoid it.</p>\n"}, {'answer_id': 28781045, 'author': 'Oliver Williams', 'author_id': 4127646, 'author_profile': 'https://Stackoverflow.com/users/4127646', 'pm_score': 2, 'selected': False, 'text': '<p>This is an older post but I thought I\'ll weigh in from a conceptual, procedural and performance standpoint.</p>\n\n<p>The first question I would ask is the relationship between person, specialperson, and user, and whether it\'s possible for someone to be <em>both</em> a specialperson and a user simultaneously.  Or, any other of 4 possible combinations (class a + b, class b + c, class a + c, or a + b + c).  If this class is stored as a value in a <code>type</code> field and would therefore collapse these combinations, and that collapse is unacceptable, then I would think a secondary table would be required allowing for a one-to-many relationship.  I\'ve learned you don\'t judge that until you evaluate the usage and the cost of losing your combination information.</p>\n\n<p>The other factor that makes me lean toward a single table is your description of the scenario.  <code>User</code> is the only entity with a username (say varchar(30)) and password (say varchar(32)).  If the common fields\' possible length is an average 20 characters per 20 fields, then your column size increase is 62 over 400, or about 15% - 10 years ago this would have been more costly than it is with modern RDBMS systems, especially with a field type like varchar (e.g. for MySQL) available.</p>\n\n<p>And, if security is of concern to you, it might be advantageous to have a secondary one-to-one table called <code>credentials ( user_id, username, password)</code>.  This table would be invoked in a JOIN contextually at say time of login, but structurally separate from just "anyone" in the main table.  And, a <code>LEFT JOIN</code> is available for queries that might want to consider "registered users".</p>\n\n<p>My main consideration for years is still to consider the object\'s significance (and therefore possible evolution) outside the DB and in the real world.  In this case, all types of persons have beating hearts (I hope), and may also have hierarchical relationships to one another; so, in the back of my mind, even if not now, we may need to store such relationships by another method.  That\'s not explicitly related to your question here, but it is another example of the expression of an object\'s relationship.  And by now (7 years later) you should have good insight into how your decision worked anyway :)</p>\n'}]
['https://Stackoverflow.com/questions/45621', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/572/']