Search results matching tags 'Database Design' and 'EAV'http://sqlblog.com/search/SearchResults.aspx?o=DateDescending&tag=Database+Design,EAV&orTags=0Search results matching tags 'Database Design' and 'EAV'en-USCommunityServer 2.1 SP2 (Build: 61129.1)What is so bad about EAV, anyway?http://sqlblog.com/blogs/aaron_bertrand/archive/2009/11/19/what-is-so-bad-about-eav-anyway.aspxThu, 19 Nov 2009 23:41:00 GMT21093a07-8b3d-42db-8cbf-3350fcbf5496:18973AaronBertrand<p>I see a lot of people trash-talking the EAV (entity-attribute-value) model.&nbsp; If you want the full story on EAV, I recommend you read the <a href="http://en.wikipedia.org/wiki/Entity-attribute-value_model" title="http://en.wikipedia.org/wiki/Entity-attribute-value_model" target="_blank">Wikipedia entry</a>.&nbsp; Basically this is the situation where instead of storing the properties of an entity in a single row, you store it as a set of name-value pairs in multiple rows.</p><p><br><font size="4"><b>The Problem<br></b></font> </p><p>I understand the general objections to using the EAV model:</p>
<ul><li>it is difficult to control the attribute names, and to make them consistent;</li><li>it is difficult to enforce data type integrity and referential integrity;</li><li>it is difficult (and slow) to pivot and/or self-join the values to make a single row;</li><li>it is difficult to make certain attributes mandatory; and,</li><li>we've been trained to view this as the "wrong" way to solve the problem.<br></li></ul><p>But what do you do when you have customers that demand real-time, on-demand
addition of attributes that they want to store?&nbsp; In one of the systems I manage, our customers wanted to do exactly this.&nbsp; Since we run a SaaS (software as a service) application, we have many customers across several different industries, who in turn want to use our system to store different types of information about *their* customers.&nbsp; A salon chain might want to record facts such as 'hair color,' 'hair type,' and 'haircut frequency'; while an investment company might want to record facts such as 'portfolio name,' 'last portfolio adjustment date,' and 'current portfolio balance.'&nbsp; </p><p>Luckily for us, returning that data in a single row wasn't all that important.&nbsp; Our customers wanted to find all the people with red or auburn hair, to sell them some new redhead-only shampoo; or, target all customers with a portfolio balance of $1 million or more, to try to get them to invest in some new pyramid scheme.&nbsp; </p><p><br><font size="4"><b>The Non-EAV Solution<br></b></font> </p><p>Without EAV, what would this design look like?&nbsp; Well, we'd have to add a column to the customers table for each of these attributes.&nbsp; So assuming we are opposed to EAV, and that we segment our data by our customers (which we call clients), then by their customers, we would have something like this: <br>
</p><blockquote>
<table bgcolor="#eeeeee" cellpadding="0" cellspacing="0">
<tr>
<td>
<pre style="padding:10px 20px;font-size:12px;font-family:consolas,lucida console,courier new,courier;-moz-background-inline-policy:continuous;"><font color="blue">CREATE&nbsp;TABLE&nbsp;</font><font color="black">dbo.Customers<br></font><font color="gray">(<br>&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="black">CustomerID&nbsp; </font><font color="blue"> INT&nbsp;PRIMARY&nbsp;KEY</font><font color="gray">,<br>&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="black">ClientID&nbsp;</font><font color="blue"> INT&nbsp;</font><font color="gray">NOT&nbsp;NULL<br> </font><font color="blue">REFERENCES&nbsp;</font><font color="black">dbo.Clients</font><font color="gray">(</font><font color="black">ClientID</font><font color="gray">),<br>&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="black">HairColor&nbsp; </font><font color="blue"> VARCHAR</font><font color="gray">(</font><font color="black">10</font><font color="gray">),<br>&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="black">HairType&nbsp;</font><font color="blue"> VARCHAR</font><font color="gray">(</font><font color="black">10</font><font color="gray">),<br>&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="black">HaircutFrequency&nbsp;</font><font color="blue"> VARCHAR</font><font color="gray">(</font><font color="black">32</font><font color="gray">),<br>&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="black">PortfolioName&nbsp;</font><font color="blue"> NVARCHAR</font><font color="gray">(</font><font color="black">32</font><font color="gray">),<br>&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="black">PortfolioBalance&nbsp; </font><font><font color="blue">BIGINT</font></font><font color="black"></font><font color="gray">,<br>&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="black">LastPortfolioAdjustmentDate </font><font><font color="blue">SMALLDATETIME</font></font><font color="black"><br></font><font color="gray">);<br></font></pre>
</td>
</tr>
</table>
</blockquote>
<p>Then if we wanted to satisfy those two queries, it could be:</p>
<blockquote>
<table bgcolor="#eeeeee" cellpadding="0" cellspacing="0">
<tr>
<td>
<pre style="padding:10px 20px;font-size:12px;font-family:consolas,lucida console,courier new,courier;-moz-background-inline-policy:continuous;"><font color="blue">SELECT&nbsp;</font><font color="black">CustomerID</font><font color="gray">,&nbsp;</font><font color="black">HairColor<br></font><font color="blue"> FROM&nbsp;</font><font color="black">dbo.Customers<br></font><font color="blue"> WHERE&nbsp;</font><font color="black">ClientID&nbsp;</font><font><font color="gray">=</font></font><font color="blue"> </font><font color="black">1<br></font><font color="gray"> AND&nbsp;</font><font color="black">HairColor&nbsp;</font><font color="blue">IN&nbsp;</font><font color="gray">(</font><font color="red">'Red'</font><font color="gray">, </font><font color="red">'Auburn'</font><font color="gray">);<br><br></font><font color="blue">SELECT&nbsp;</font><font color="black">CustomerID</font><font color="gray">,&nbsp;</font><font color="black">PortfolioBalance<br></font><font color="blue"> FROM&nbsp;</font><font color="black">dbo.Customers<br></font><font color="blue"> WHERE&nbsp;</font><font color="black">ClientID&nbsp;</font><font><font color="gray">=</font></font><font color="blue"> </font><font color="black">2<br></font><font color="gray"> AND&nbsp;</font><font color="black">PortfolioBalance&nbsp;</font><font color="gray">&gt;=&nbsp;</font><font color="black">1000000</font><font color="gray">;</font></pre></td>
</tr>
</table>
</blockquote>
<p>Simple enough.&nbsp; But now what if the salon decides they also want to record their customers' head size?&nbsp; The table gets wider and wider as more attributes are required, and you have to build code that will do this (or, *shudder*, add the column manually):</p>
<blockquote>
<table bgcolor="#eeeeee" cellpadding="0" cellspacing="0">
<tr>
<td>
<pre style="padding:10px 20px;font-size:12px;font-family:consolas,lucida console,courier new,courier;-moz-background-inline-policy:continuous;"><font color="blue">ALTER&nbsp;TABLE&nbsp;</font><font color="black">dbo.Customers&nbsp;</font><font color="blue">ADD&nbsp;</font><font color="black">HeadSize </font><font><font color="blue">TINYINT</font></font><font color="black"></font><font color="gray">;</font></pre>
</td>
</tr>
</table>
</blockquote>
<p>(And then any code that needs to be used to retrieve head size for the customer needs to be modified to understand the existence of that column.)<br></p>
<p>So while this reduces the complexity of self-joining to get multiple attributes as you would need to do in the EAV model, it creates its own performance problem by requiring more and more space for any single row, and potentially page splits and fragmentation as that data gets updated.&nbsp; Never mind that HairColor, for example, is probably of very little interest to anyone outside of our salon customer (though maybe we should aim for some of the dating site business).&nbsp; Personally, I don't think dynamic ALTER TABLE ADD new_attribute_name is the way to go here, as you can see that with many customers requiring their own custom attributes, we will soon be up against the one-row-per-page problem.&nbsp; Can you say "maintenance nightmare"?<br></p>
<p><br><font size="4"><b>The EAV solution </b></font><br></p><p>My solution: EAV, baby!&nbsp; We talked to our customers who were driving these requirements, and we came up with a good compromise.&nbsp; We didn't need to support every single data type; just three basic ones: strings, numbers, and dates.&nbsp; To simplify things (and based on a LOT of discussion about use cases) we settled on NVARCHAR(1024), DECIMAL(16, 4), and SMALLDATETIME.&nbsp; These covered just about every scenario we were presented with on what our customers would want to store for each of their customers.&nbsp; Actually, the biggest string they wanted was 255, but I am a forward-thinker - tomorrow they would want 512, and I didn't want to be constantly incrementing this columns, so I stretched it out - if they want to increase them we can simply adjust the parameters and artificial constraints outside of the schema.&nbsp; Similarly, the date column only needed precision to one day, but I left it open to minutes (kind of by choice, since there is nothing between SMALLDATETIME and DATETIME in 2000/2005; in 2008 I would have used DATE most likely), and the decimal requirement was only two decimal places.&nbsp; You might think that such a big decimal is wasteful, but we are using VARDECIMAL storage, which means that only the big decimals will use that space (<a href="http://sqlblog.com/blogs/aaron_bertrand/archive/2008/04/27/performance-storage-comparisons-money-vs-decimal.aspx" title="http://sqlblog.com/blogs/aaron_bertrand/archive/2008/04/27/performance-storage-comparisons-money-vs-decimal.aspx" target="_blank">last year, I ran some tests</a> that show some favorable results).&nbsp; </p><p>[And going back to the NVARCHAR column, with SQL Server 2008 R2, we plan to implement Unicode compression
so that we can squeeze a lot more out of our space -- we are I/O-bound,
not CPU-bound: see <a href="http://sqlblog.com/blogs/aaron_bertrand/archive/2009/08/11/sql-server-2008-r2-a-quick-experiment-in-unicode-compression.aspx" title="http://sqlblog.com/blogs/aaron_bertrand/archive/2009/08/11/sql-server-2008-r2-a-quick-experiment-in-unicode-compression.aspx" target="_blank">post 1</a>, <a href="http://sqlblog.com/blogs/aaron_bertrand/archive/2009/08/23/sql-server-2008-r2-digging-deeper-into-unicode-compression.aspx" title="http://sqlblog.com/blogs/aaron_bertrand/archive/2009/08/23/sql-server-2008-r2-digging-deeper-into-unicode-compression.aspx" target="_blank">post 2</a> and <a href="http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/04/more-testing-of-unicode-compression-in-sql-server-2008-r2.aspx" title="http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/04/more-testing-of-unicode-compression-in-sql-server-2008-r2.aspx" target="_blank">post 3</a> of my tests of this feature earlier this year.]</p>
<p>So the core table looked like this:<br></p>
<blockquote>
<table bgcolor="#eeeeee" cellpadding="0" cellspacing="0">
<tr>
<td>
<pre style="padding:10px 20px;font-size:12px;font-family:consolas,lucida console,courier new,courier;-moz-background-inline-policy:continuous;"><font color="blue">CREATE&nbsp;TABLE&nbsp;</font><font color="black">dbo.Attributes<br></font><font color="gray">(<br>&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="black">AttributeID&nbsp;</font><font color="blue">INT&nbsp;PRIMARY&nbsp;KEY</font><font color="gray">,<br>&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="black">ClientID&nbsp;<font color="blue"> </font></font><font color="blue">INT&nbsp;</font><font color="gray">NOT&nbsp;NULL <br> </font><font color="blue">REFERENCES&nbsp;</font><font color="black">dbo.Clients</font><font color="gray">(</font><font color="black">ClientID</font><font color="gray">),<br>&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="black">[Name]&nbsp;</font><font color="blue"> NVARCHAR</font><font color="gray">(</font><font color="black">32</font><font color="gray">)&nbsp;NOT&nbsp;NULL&nbsp;</font><font color="blue">UNIQUE</font><font color="gray">,<br>&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="black">DataTypeID&nbsp; </font><font><font color="blue">TINYINT</font></font><font color="black"> </font><font color="gray">NOT&nbsp;NULL&nbsp;</font><font color="green"><br> --&nbsp;1&nbsp;=&nbsp;string,&nbsp;2&nbsp;=&nbsp;numeric,&nbsp;3&nbsp;=&nbsp;date<br></font><font color="gray">);<br></font></pre>
</td>
</tr>
</table>
</blockquote>
<p>Then the actual data table looked like this:</p>
<blockquote>
<table bgcolor="#eeeeee" cellpadding="0" cellspacing="0">
<tr>
<td>
<pre style="padding:10px 20px;font-size:12px;font-family:consolas,lucida console,courier new,courier;-moz-background-inline-policy:continuous;"><font color="blue">CREATE&nbsp;TABLE&nbsp;</font><font color="black">dbo.CustomerAttributes<br></font><font color="gray">(<br>&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="black">CustomerID&nbsp; </font><font color="blue">INT&nbsp;</font><font color="blue">NOT&nbsp;NULL<br> REFERENCES&nbsp;</font><font color="black">dbo.Customers</font><font color="gray">(</font><font color="black">CustomerID</font><font color="gray">),<br>&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="black">AttributeID&nbsp;</font><font color="blue"> INT&nbsp;</font><font color="gray">NOT&nbsp;NULL<br> </font><font color="blue">REFERENCES&nbsp;</font><font color="black">dbo.Attributes</font><font color="gray">(</font><font color="black">AttributeID</font><font color="gray">),<br>&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="black">StringValue&nbsp;</font><font color="blue"> NVARCHAR</font><font color="gray">(</font><font color="black">1024</font><font color="gray">),<br>&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="black">NumericValue </font><font><font color="blue">DECIMAL</font></font><font color="black"></font><font color="gray">(</font><font color="black">16</font><font color="gray">,</font><font color="black">4</font><font color="gray">),<br>&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="black">DateValue&nbsp; </font><font><font color="blue">SMALLDATETIME</font></font><font color="black"></font><font color="gray">,<br>&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="black">ModifiedDate </font><font><font color="blue">SMALLDATETIME</font></font><font color="black"> </font><font color="gray">NOT&nbsp;NULL<br> </font><font color="blue">DEFAULT&nbsp;</font><font color="magenta">CURRENT_TIMESTAMP</font><font color="gray">,<br>&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="blue">PRIMARY&nbsp;KEY&nbsp;</font><font color="gray">(</font><font color="black">CustomerID</font><font color="gray">,&nbsp;</font><font color="black">AttributeID</font><font color="gray">)<br>);</font></pre>
</td>
</tr>
</table>
</blockquote>
<p>The eventual goal of this was to provide better self-service reporting without having to make custom modifications to the system every time a client has a new requirement.&nbsp; This self-service reporting can now be driven by a very simple drop-down that lists all of the IDs/names from the Attributes table, and offers different choices based on the data type.&nbsp; (For example, if it is a string, they can use =, contains, starts with, ends with, etc.; if it is a date, they can use &gt;=, &gt;, BETWEEN, &lt;, &lt;=, etc.)&nbsp; When they add an attribute, nobody has to go change any of this code because it is already written using this flexibility; the list of attribute choices just gets longer or shorter as attributes are added or removed.&nbsp; (Sorry, I'm not at liberty to share the C# source for the code that builds the self-service reporting queries.&nbsp; It is complicated, but not rocket surgery.&nbsp; Yes, I am mixing metaphors.)</p>
<p>So, for the above queries, we might end up with something like this instead:</p>
<blockquote>
<table bgcolor="#eeeeee" cellpadding="0" cellspacing="0">
<tr>
<td>
<pre style="padding:10px 20px;font-size:12px;font-family:consolas,lucida console,courier new,courier;-moz-background-inline-policy:continuous;"><font color="blue">SELECT&nbsp;</font><font color="black">c.CustomerID</font><font color="gray">,&nbsp;</font><font color="black">HairColor </font><font><font color="gray">=</font></font><font color="blue"> </font><font color="black">a.StringValue<br></font><font color="blue"> FROM&nbsp;</font><font color="black">dbo.CustomerAttributes&nbsp;</font><font color="blue">AS&nbsp;</font><font color="black">a<br></font><font color="blue"> INNER&nbsp;JOIN&nbsp;</font><font color="black">dbo.Customers&nbsp;</font><font color="blue">AS&nbsp;</font><font color="black">c<br></font><font color="blue"> ON&nbsp;</font><font color="black">a.CustomerID </font><font><font color="gray">=</font></font><font color="blue"> </font><font color="black">c.CustomerID<br></font><font color="blue"> WHERE&nbsp;</font><font color="black">c.ClientID&nbsp;</font><font><font color="gray">=</font></font><font color="blue"> </font><font color="black">1<br></font><font color="gray"> AND&nbsp;</font><font color="black">a.AttributeID = 1<br> </font><font><font color="gray">AND </font></font><font><font color="black">a.StringValue </font></font><font color="black"></font><font color="blue">IN&nbsp;</font><font color="gray">(</font><font color="red">N'Red'</font><font color="gray">,<font color="red"> </font></font><font color="red">N'Auburn'</font><font color="gray">);<br><br></font><font color="blue">SELECT&nbsp;</font><font color="black">c.CustomerID</font><font color="gray">,&nbsp;</font><font color="black">PortfolioBalance&nbsp;</font><font><font color="gray">=</font></font><font color="blue"> </font><font color="black">a.NumericValue<br></font><font color="blue"> FROM&nbsp;</font><font color="black">dbo.CustomerAttributes&nbsp;</font><font color="blue">AS&nbsp;</font><font color="black">a<br></font><font color="blue"> INNER&nbsp;JOIN&nbsp;</font><font color="black">dbo.Customers&nbsp;</font><font color="blue">AS&nbsp;</font><font color="black">c<br></font><font color="blue"> ON&nbsp;</font><font color="black">a.CustomerID&nbsp;</font><font><font color="gray">=</font></font><font color="blue"> </font><font color="black">c.CustomerID<br></font><font color="blue"> WHERE&nbsp;</font><font color="black">c.ClientID&nbsp;</font><font><font color="gray">=</font></font><font color="blue"> </font><font color="black">2<br></font><font><font color="gray"> AND </font></font><font color="gray"><font color="black">a.AttributeID = 2</font><br> AND&nbsp;</font><font color="black">a.NumericValue </font><font color="gray">&gt;=&nbsp;</font><font color="black">1000000</font><font color="gray">;</font></pre>
</td>
</tr>
</table>
</blockquote>
<p>Yes, these queries are a little more verbose, but they are fairly trivial to generate programmatically, when you have a well-defined underlying structure instead of an endless stream of column names on a wide, ever-growing table.<br></p>
<p><br><font size="4"><b>The grass is always greener... </b></font><br></p><p>Does this approach have its downsides?&nbsp; Sure:<br></p>
<ul>
<li><b>Indexes on the value columns are only marginally useful, and only in some cases.</b><br><br>By logging the actual queries that customers run, and how long they take, it is easy to periodically review the heavy hitters, and consider index or statistics changes that would benefit them.&nbsp; So far this hasn't been necessary; maybe we've just been lucky.&nbsp; We have customers with 100s of millions of rows in this table, and while the queries are not sub-second, since they are running behind the scenes and not in real-time, they are certainly well within our SLAs.&nbsp; Anyway for the ones that take longer, these are not queries that would have been any faster in a wide table either (e.g. WHERE PortfolioName LIKE '%small cap%').<br><br></li>
<li><b>It is not trivial to return all of the values for a customer's set of attributes in a single row.</b><br><br>This is true, but then again, these are easy enough to transpose at the presentation layer (and that is what we do).&nbsp; There is no reason for us to need to present the data for a customer as single-row structure (YMMV).<br><br></li>
<li><b>Pulling multiple rows for a customer is more expensive than pulling a single row.</b><br><br>This is also true.&nbsp; Though, you could argue that getting to a wide row to access just one skinny attribute is just as wasteful, especially if you are typically after certain and a small number of attributes with much higher frequency than larger numbers.&nbsp; This really depends on the table, its index structure, the I/O subsystem, access patterns, buffer pool, etc.&nbsp; But more importantly, since we can't define what a "row" looks like for all customers right now, never mind permanently, this trade-off is worth it to us.&nbsp; Again, YMMV.<br><br></li>
<li><b>As outlined above, we can't control the consistency or even the presence of certain attributes across customers.</b><br><br>Well, we could, with a lot of cumbersome code.&nbsp; But since attribute names are in complete and utter control of each customer, they can live and die by their own control over them.&nbsp; I didn't want to get into the business of determining which attributes customers wanted to make mandatory; if one customer wanted HairColor to be mandatory, and another didn't, then that is an interesting issue to solve declaratively.&nbsp; The most complicated problem has been when a customer has added two similar attributes, e.g. HairColor and Hair_Color, then applied both attributes to a single customer.&nbsp; The resolution is tedious but logically simple: <br><br>
<ol>
<li>pick one to keep (let's say we keep AttributeID = 1, and throw away AttributeID = 2);</li>
<li>for any Customers where only AttributeID = 2 exists, update to AttributeID = 1;<br></li>
<li>for any Customers where both 1 and 2 exist, keep whichever one has a greater ModifiedDate, delete the older one, and if the one remaining is 2, update to 1;<br>3a. in the case of a tie, keep 1 and throw away 2;<br></li>
<li>finally, delete Attribute 2 from the Attributes table.<br></li>
</ol>
</li>
</ul>
<p><br><b><font size="4">Conclusion</font></b></p><p>I just wanted to shine some light on a case where the EAV model might make sense (other than it being written off as a "rookie or object-oriented mistake").&nbsp; The viability of this approach will depend heavily on how much of the requirements you can gather up front (and whether they are likely to change over time, as in our case), as well as how you want to balance your maintenance time down the road: writing code during every "enhancement" request vs. occasionally troubleshooting performance.&nbsp; At least this is how my experience has panned out thus far.&nbsp; And if I were to design this system from scratch tomorrow, the design would be quite similar, though I might have a better opportunity in that case to see if sparse columns and filtered indexes might make the non-EAV approaches more attractive.&nbsp; In the meantime, I am donning my flame-resistant suit, as I am sure some purists and/or EAV opponents will come out blazing...<br></p>