10

I have three basic types of entities: People, Businesses, and Assets. Each Asset can be owned by one and only one Person or Business. Each Person and Business can own from 0 to many Assets. What would be the best practice for storing this type of conditional relationship in Microsoft SQL Server?

My initial plan is to have two nullable foreign keys in the Assets table, one for People and one for Businesses. One of these values will be null, while the other will point to the owner. The problem I see with this setup is that it requires application logic in order to be interpreted and enforced. Is this really the best possible solution or are there other options?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
sglantz
  • 2,063
  • 4
  • 20
  • 30

7 Answers7

13

Introducing SuperTypes and SubTypes

I suggest that you use supertypes and subtypes. First, create PartyType and Party tables:

CREATE TABLE dbo.PartyType (
   PartyTypeID int NOT NULL identity(1,1) CONSTRAINT PK_PartyType PRIMARY KEY CLUSTERED
   Name varchar(32) CONSTRAINT UQ_PartyType_Name UNIQUE
);

INSERT dbo.PartyType VALUES ('Person'), ('Business');

SuperType

CREATE TABLE dbo.Party (
   PartyID int identity(1,1) NOT NULL CONSTRAINT PK_Party PRIMARY KEY CLUSTERED,
   FullName varchar(64) NOT NULL,
   BeginDate smalldatetime, -- DOB for people or creation date for business
   PartyTypeID int NOT NULL
      CONSTRAINT FK_Party_PartyTypeID FOREIGN KEY REFERENCES dbo.PartyType (PartyTypeID)
);

SubTypes

Then, if there are columns that are unique to a Person, create a Person table with just those:

CREATE TABLE dbo.Person (
   PersonPartyID int NOT NULL
      CONSTRAINT PK_Person PRIMARY KEY CLUSTERED
      CONSTRAINT FK_Person_PersonPartyID FOREIGN KEY REFERENCES dbo.Party (PartyID)
         ON DELETE CASCADE,
   -- add columns unique to people
);

And if there are columns that are unique to Businesses, create a Business table with just those:

CREATE TABLE dbo.Business (
   BusinessPartyID int NOT NULL
      CONSTRAINT PK_Business PRIMARY KEY CLUSTERED
      CONSTRAINT FK_Business_BusinessPartyID FOREIGN KEY REFERENCES dbo.Party (PartyID)
         ON DELETE CASCADE,
   -- add columns unique to businesses
);

Usage and Notes

Finally, your Asset table will look something like this:

CREATE TABLE dbo.Asset (
   AssetID int NOT NULL identity(1,1) CONSTRAINT PK_Asset PRIMARY KEY CLUSTERED,
   PartyID int NOT NULL
      CONSTRAINT FK_Asset_PartyID FOREIGN KEY REFERENCES dbo.Party (PartyID),
   AssetTag varchar(64) CONSTRAINT UQ_Asset_AssetTag UNIQUE
);

The relationship the supertype Party table shares with the subtype tables Business and Person is "one to zero-or-one". Now, while the subtypes generally have no corresponding row in the other table, there is the possibility in this design of having a Party that ends up in both tables. However, you may actually like this: sometimes a person and a business are nearly interchangeable. If not useful, while a trigger to enforce this will be fairly easily done, the best solution is probably to add the PartyTypeID column to the subtype tables, making it part of the PK & FK, and put a CHECK constraint on the PartyTypeID.

The beauty of this model is that when you want to create a column that has a constraint to a business or a person, then you make the constraint to the appropriate table instead of the party table.

Also, if desired, turning on cascade delete on the constraints can be useful, as well as an INSTEAD OF DELETE trigger on the subtype tables that instead delete the corresponding IDs from the supertype table (this guarantees no supertype rows that have no subtype rows present). These queries are very simple and work at the entire-row-exists-or-doesn't-exist level, which in my opinion is a gigantic improvement over any design that requires checking column value consistency.

Also, please notice that in many cases columns that you would think should go in one of the subtype tables really can be combined in the supertype table, such as social security number. Call it TIN (taxpayer identification number) and it works for both businesses and people.

ID Column Naming

The question of whether or not to call the column in the Person table PartyID, PersonID, or PersonPartyID is your own preference, but I think it's best to call these PersonPartyID or BusinessPartyID—tolerating the cost of the longer name, this avoids two types of confusion. E.g., someone unfamiliar with the database sees BusinessID and doesn't know this is a PartyID, or sees PartyID and doesn't know it is restricted by foreign key to just those in the Business table.

If you want to create views for the Party and Business tables, they can even be materialized views since it's a simple inner join, and there you could rename the PersonPartyID column to PersonID if you were truly so inclined (though I wouldn't). If it's of great value to you, you can even make INSTEAD OF INSERT and INSTEAD OF UPDATE triggers on these views to handle the inserts to the two tables for you, making the views appear completely like their own tables to many application programs.

Making Your Proposed Design Work As-Is

Also, I hate to mention it, but if you want to have a constraint in your proposed design that enforces only one column being filled in, here is code for that:

ALTER TABLE dbo.Assets
ADD CONSTRAINT CK_Asset_PersonOrBusiness CHECK (
   CASE WHEN PersonID IS NULL THEN 0 ELSE 1 END
   + CASE WHEN BusinessID IS NULL THEN 0 ELSE 1 END = 1
);

However, I don't recommend this solution.

Final Thoughts

A natural third subtype to add is organization, in the sense of something that people and businesses can have membership in. Supertype and subtype also elegantly solve customer/employee, customer/vendor, and other problems similar to the one you presented.

Be careful not to confuse "Is-A" with "Acts-As-A". You can tell a party is a customer by looking in your order table or viewing the order count, and may not need a Customer table at all. Also don't confuse identity with life cycle: a rental car may eventually be sold, but this is a progression in life cycle and should be handled with column data, not table presence--the car doesn't start out as a RentalCar and get turned into a ForSaleCar later, it's a Car the whole time. Or perhaps a RentalItem, maybe the business will rent other things too. You get the idea.

It may not even be necessary to have a PartyType table. The party type can be determined by the presence of a row in the corresponding subtype table. This would also avoid the potential problem of the PartyTypeID not matching the subtype table presence. One possible implementation is to keep the PartyType table, but remove PartyTypeID from the Party table, then in a view on the Party table return the correct PartyTypeID based on which subtype table has the corresponding row. This won't work if you choose to allow parties to be both subtypes. Then you would just stick with the subtype views and know that the same value of BusinessID and PersonID refer to the same party.

Further Reading On This Pattern

Please see A Universal Person and Organization Data Model for a more complete and theoretical treatment.

I recently found the following articles to be useful for describing some alternate approaches for modeling inheritance in a database. Though specific to Microsoft's Entity Framework ORM tool, there's no reason you couldn't implement these yourself in any DB development:

P.S. I have switched, more than once, my opinion on column naming of IDs in subtype tables, due to having more experience under my belt.

ErikE
  • 48,881
  • 23
  • 151
  • 196
  • I need to type faster... when I started my response only HLGEM had posted. Sigh. – ErikE Jan 21 '10 at 21:39
  • You typed a lot. I'm deleting my post out of respect for how well you explained database schema design. – Travis Gockel Jan 21 '10 at 21:44
  • That was very considerate of you! – ErikE Jan 21 '10 at 21:56
  • @ErikE I really appreciate seeing that it is possible to solve that requirement, however, I'd like to know: is it really a good idea to implement it, or it would've been better to just create PersonAsset and BusinessAsset tables? – oScarDiAnno Oct 13 '21 at 22:18
  • @oScarDiAnno How will you enforce referential integrity to an `Asset` if you don't have an `Assets` table? How will you work with Assets in parts of your system, in a way that doesn't care what *kind* of asset it is? How will you add new asset types without having to touch *every single piece of code in your database that works with assets* if you don't have an `Asset` table? – ErikE Oct 13 '21 at 23:09
  • @ErikE I can see the importance there, I guess I was just thinking of a different use case. I mean, for example, if `Asset` doesn't and won't have more relationships (other than with the 'parent' table which would be either `Person` or `Business` and maybe `Organization`), is this approach still desirable? Or would it be better to just have `PersonAsset`, `BusinessAsset` tables (and so on), which would contain the Asset properties + the foreign key of the owning table? – oScarDiAnno Oct 14 '21 at 14:44
  • I can't possibly imagine a system that wouldn't have some areas that want to work with an `Asset` without caring which kind it was. SOLID and other good software principles say we should confine the knowledge about specific parts of our system to as few areas as possible, and should limit the number of types of knowledge each area of our system works with. The SRP says, each function/module/class should have only 1 reason to change. I'd need to know more about your use case to really get any more concrete. – ErikE Oct 15 '21 at 17:25
  • @oScarDiAnno Did you get value from the last link in my answer about "how to choose an inheritance strategy"? – ErikE Oct 15 '21 at 17:30
2

You don't need application logic to enforce this. The easiest way is with a check constraint:

(PeopleID is null and BusinessID is not null) or (PeopleID is not null and BusinessID is null)
D'Arcy Rittich
  • 167,292
  • 40
  • 290
  • 283
  • I actually like your check constraint better than mine for just two columns. Mine lends itself much better to expansion to any number of columns--just add one more sub-expression. With your version, adding another column would require changing each sub-expression. Imagine going from 5 columns to 6... – ErikE Jan 21 '10 at 22:13
1

You can have another entity from which Person and Business "extend". We call this entity Party in our current project. Both Person and Business have a FK to Party (is-a relationship). And Asset may have also a FK to Party (belongs to relationship).

With that said, if in the future an Asset can be shared by multiple instances, is better to create m:n relationships, it gives flexibility but complicates the application logic and the queries a bit more.

Lluis Martinez
  • 1,963
  • 8
  • 28
  • 42
1

ErikE's answer gives a good explanation on how to go about the supertype / subtype relationship in tables and is likely what I'd go for in your situation, however, it doesn't really address the question(s) you've posed which are also interesting, namely:

  1. What would be the best practice for storing this type of conditional relationship in Microsoft SQL Server?
  2. ...are there other options?

For those I recommend this blog entry on TechTarget which has an excerpt from excerpt from "A Developer's Guide to Data Modeling for SQL Server, Covering SQL Server 2005 and 2008" by Eric Johnson and Joshua Jones which addresses 3 possible options.

In summary they are:

  1. Supertype Table - Almost matches what you've proposed, have a table with some fields that will always be null when others are filled. Good when only a couple of fields aren't shared. So depending on how different Business and People are you could possibly combine them into one table, Owners perhaps, and then just have OwnerID in your Asset table.
  2. Subtype Tables - Basically the opposite of what Supertype tables are and is what you have just now. Here we have lots of unique fields and maybe one or two the same so we just have the repeated fields appear in each table. As you are finding this isn't really suitable for your situation.
  3. Supertype and Subtype Tables - A combination of both of the above where the matching fields are placed in a single table and the unique ones in separate tables and matching IDs are used to join the record from one table to the other. This matches ErikE's proposed solution and, as mentioned, is the one I would favour as well.

Sadly it doesn't go on to explain which, if any, are best practice but it is certainly a good read to get an idea of the options that are out there.

Community
  • 1
  • 1
RyanfaeScotland
  • 1,216
  • 11
  • 30
  • I noticed your answer just now. I'm a little puzzled about the description of #3, where you mention "another table is used to join them all". In the scheme I laid out, there is no "other table". There is one supertype table, and then the many subtype tables. I did present a `PartyType` table, but this table doesn't join them all, it merely provides meaning to the `PartyTypeID` column (and isn't actually required, for example if the code enforces the meaning of each `PartyTypeID` in an enum instead of using a table to record the details). (continued...) – ErikE Aug 25 '16 at 15:45
  • The way the tables link together is the special one-to-zero-or-one relationship, where `PartyID`, `BusinessID`, and `PersonId` are interchangeable—no join is required to figure out their meaning, as they are merely different names for the same thing (explicitly, a `BusinessID` of 42 IS the `PartyID` 42). – ErikE Aug 25 '16 at 15:45
  • Hi ErikE, you are right, a third table isn't a requirement, it is something I have in my schema to create instances of an item from the PartyID (so InstanceID 1, 2 and 3 might all map to PartyID 42). I'll clear up my answer to remove this confusion. – RyanfaeScotland Aug 25 '16 at 16:14
  • I've updated my answer to go into a little more detail (links) about some of the alternatives, which I think you are laying out here, but without much detail explaining exactly what they mean and how to implement them. – ErikE Aug 25 '16 at 16:25
  • Good effort, I prefer giving answers that give a basic guidance / pointers as to the solution, helping people find the info that is already out there written by greater authorities on the topic than myself. I'm sure people will appreciate it being added to your answer as well though. – RyanfaeScotland Aug 25 '16 at 16:38
0

YOu can enforce the logic with a trigger instead. Then no matter how the record is changed, only one of the fileds will be filled in.

You could also have a PeopleAsset table and a BusinessAsset table, but stillwould have the problem of enforcing that only one of them has a record.

HLGEM
  • 94,695
  • 15
  • 113
  • 186
0

An asset would have a foreign key to the owning person, and you should setup an association table to link assets and businesses. As said in other comments, you can use triggers and/or constraints to ensure that the data stays in a consistent state. ie. when you delete a business, delete the lines in your association table.

Marty Neal
  • 8,741
  • 3
  • 33
  • 38
0

Table People, Businesses both can use UUID as primary key, and union both to a view for sql join purpose.

so you can simply use one foreign key column in Assets relation to both People and Businesses, because UUID is nearly unique. And you can simply query like:

select * from Assets
join view_People_Businesses as v on v.id = Assets.fk
Steven Chou
  • 1,504
  • 2
  • 21
  • 43