<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Experimental Thoughts &#187; NULL</title>
	<atom:link href="http://thoughts.j-davis.com/tag/null/feed/" rel="self" type="application/rss+xml" />
	<link>http://thoughts.j-davis.com</link>
	<description>Ideas on Databases, Logic, and Language by Jeff Davis</description>
	<lastBuildDate>Thu, 06 May 2010 19:29:24 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Flexible Schemas and PostgreSQL</title>
		<link>http://thoughts.j-davis.com/2010/05/06/flexible-schemas-and-postgresql/</link>
		<comments>http://thoughts.j-davis.com/2010/05/06/flexible-schemas-and-postgresql/#comments</comments>
		<pubDate>Thu, 06 May 2010 17:42:28 +0000</pubDate>
		<dc:creator>Jeff Davis</dc:creator>
				<category><![CDATA[Databases]]></category>
		<category><![CDATA[Language]]></category>
		<category><![CDATA[NoSQL]]></category>
		<category><![CDATA[NULL]]></category>
		<category><![CDATA[PostgreSQL]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://thoughts.j-davis.com/?p=267</guid>
		<description><![CDATA[First, what is a &#8220;flexible schema&#8221;? It&#8217;s hard to pin down an exact definition, but it&#8217;s used to mean a data model that permits changes in application data structures without needing to migrate old data or incur other administrative hassles. That&#8217;s a worthwhile goal. Applications often grow organically, especially in the early, exploratory stages of [...]]]></description>
			<content:encoded><![CDATA[<p>First, what is a &#8220;flexible schema&#8221;? It&#8217;s hard to pin down an exact definition, but it&#8217;s used to mean a data model that permits changes in application data structures without needing to migrate old data or incur other administrative hassles.</p>
<p>That&#8217;s a worthwhile goal. Applications often grow organically, especially in the early, exploratory stages of development. For example, you may decide to track when a user last did something on the website, so that you can adapt news and notices for those users (e.g. &#8220;Did you know that we added feature XYZ since you last visited?&#8221;). Developers have a need to produce a prototype quickly to work out the edge cases (do we update that timestamp for all actions, or only certain ones?), and probably a need to put it in production so that the users can benefit sooner.</p>
<p>A common worry is that <code>ALTER TABLE</code> will be a major performance problem. That&#8217;s sometimes a problem, but in PostgreSQL, you can add a column to a table in constant time (not dependent on the size of the table) in most situations. I don&#8217;t think this is a good reason to avoid <code>ALTER TABLE</code>, at least in PostgreSQL (other systems may impose a greater burden).</p>
<p>There are good reasons to avoid <code>ALTER TABLE</code>, however. We&#8217;ve only defined one use case for this new &#8220;last updated&#8221; field, and it&#8217;s a fairly loose definition. If we use <code>ALTER TABLE</code> as a first reaction for tracking any new application state, we&#8217;d end up with lots of columns with overlapping meanings (all subtly different), and it would be challenging to keep them consistent with each other. More importantly, adding new columns without thinking through the meaning and the data migration strategy will surely cause confusion and bugs. For example, if you see the following table:</p>
<pre>    CREATE TABLE users
    (
      name         TEXT,
      email        TEXT,
      ...,
      last_updated TIMESTAMPTZ
    );
</pre>
<p>you might (reasonably) assume that the following query makes sense:</p>
<pre>    SELECT * FROM users
      WHERE last_updated &lt; NOW() - '1 month'::INTERVAL;</pre>
<p>Can you spot the problem? Old user records (before the <code>ALTER TABLE</code>) will have <code>NULL</code> for <code>last_updated</code> timestamps, and will not satisfy the <code>WHERE</code> condition even though they intuitively qualify. There are two parts to the problem:</p>
<ol>
<li>The presence of the <code>last_updated</code> field fools the author of the SQL query into making assumptions about the data, because it seems so simple on the surface.</li>
<li>NULL semantics allow the query to be executed even without complete information, leading to a wrong result.</li>
</ol>
<p>Let&#8217;s try changing the table definition:</p>
<pre>    CREATE TABLE users
    (
      name       TEXT,
      email      TEXT,
      ...,
      properties HSTORE
    );
</pre>
<p><a title="HSTORE" href="http://www.postgresql.org/docs/8.4/static/hstore.html">HSTORE</a> is a set of key/value pairs. Some tuples might have the <code>last_updated</code> key in the properties attribute, and others may not. This accomplishes two things:</p>
<ol>
<li>There&#8217;s no need for ALTER TABLE or cluttering of the namespace with a lot of nullable columns.</li>
<li>The name &#8220;properties&#8221; is vague enough that query writers would (hopefully) be on their guard, understanding that not all records will share the same properties.</li>
</ol>
<p>You could still write the same (wrong) query against the second table with minor modification. Nothing has fundamentally changed. But we are using a different development strategy that&#8217;s easy on application developers during rapid development cycles, yet does not leave a series of pitfalls for users of the data. When a certain property becomes universally recorded and has a concrete meaning, you can plan a real data migration to turn it into a relation attribute instead.</p>
<p>Now, we need some guiding principles about when to use a complex type to  represent complex information, and when to use separate columns in the  table. To maximize utility and minimize confusion, I believe the best  guiding principle is the meaning of the data you&#8217;re storing across <em>all </em>tuples. When defining the attributes of a relation, if you find  yourself using vague nouns such as &#8220;properties,&#8221; or resorting to complex  qualifications (lots of &#8220;if/then&#8221; branching in your definition), consider less constrained data types like <a title="HSTORE" href="http://www.postgresql.org/docs/8.4/static/hstore.html">HSTORE</a>.  Otherwise, it&#8217;s best to nail down the meaning in terms of appropriate  nouns, which will help keep the DBMS smart and queries simple (and correct). See <a title="Choosing Data Types" href="../2009/09/30/choosing-data-types/">Choosing  Data Types</a> and further guidance in reference [1].</p>
<p>I believe there are three reasons why application developers feel that relational schemas are &#8220;inflexible&#8221;:</p>
<ol>
<li>A reliance on NULL semantics to make things &#8220;magically work,&#8221; when in reality, it just makes queries succeed that should fail. See my previous posts: <a title="None, nil, Nothing, undef, NA, and SQL NULL" href="http://thoughts.j-davis.com/2008/08/13/none-nil-nothing-undef-na-and-sql-null/">None, nil, Nothing, undef, NA, and SQL NULL</a> and <a title="What is the deal with NULLs?" href="http://thoughts.j-davis.com/2009/08/02/what-is-the-deal-with-nulls/">What is the deal with NULLs?</a>.</li>
<li>The SQL database industry has avoided interesting types, like <a title="HSTORE" href="http://www.postgresql.org/docs/8.4/static/hstore.html">HSTORE</a>, for a long time. See my previous post: <a title="Choosing Data Types" href="http://thoughts.j-davis.com/2009/09/30/choosing-data-types/">Choosing Data Types</a>.</li>
<li>ORMs make a fundamental false equivalence between an object attribute and a table column. There is a relationship between the two, of course; but they are simply not the same thing. This is a direct consequence of &#8220;The First Great Blunder&#8221;[2].</li>
</ol>
<p><strong>EDIT: </strong>I found a more concise way to express my fundamental point &#8212; During the early stages of application development, we only vaguely understand our data. The most important rule of database design is that the database should represent reality, not what we wish reality was like. Therefore, a database should be able to express that vagueness, and later be made more precise when we understand our data better. None of this should be read to imply that constraints are less important or that we need not understand our data. These ideas mostly apply only at very early stages of development, and even then, prudent use of constraints often makes that development much faster.</p>
<p>[1] Date, C.J.; Darwen, Hugh (2007). <em>Databases, Types, and the Relational Model</em>. pp. 377-380 (Appendix B, &#8220;A Design Dilemma&#8221;).</p>
<p>[2] Date, C.J. (2000). <em>An Introduction To Database Systems</em>, p.  865.</p>
]]></content:encoded>
			<wfw:commentRss>http://thoughts.j-davis.com/2010/05/06/flexible-schemas-and-postgresql/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>None, nil, Nothing, undef, NA, and SQL NULL</title>
		<link>http://thoughts.j-davis.com/2008/08/13/none-nil-nothing-undef-na-and-sql-null/</link>
		<comments>http://thoughts.j-davis.com/2008/08/13/none-nil-nothing-undef-na-and-sql-null/#comments</comments>
		<pubDate>Wed, 13 Aug 2008 18:00:02 +0000</pubDate>
		<dc:creator>Jeff Davis</dc:creator>
				<category><![CDATA[Databases]]></category>
		<category><![CDATA[NULL]]></category>
		<category><![CDATA[PostgreSQL]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://davisjeff.wordpress.com/?p=14</guid>
		<description><![CDATA[In my last post, Why DBMSs are so complex, I raised the issue of type mismatches between the application language and the DBMS. Type matching between the DBMS and the application is as important as types themselves for successful application development. If a type behaves one way in the DBMS, and a &#8220;similar&#8221; type behaves [...]]]></description>
			<content:encoded><![CDATA[<p>In my last post, <a title="Why DBMSs are so complex" href="http://thoughts.j-davis.com/2008/08/03/why-dbmss-are-so-complex/">Why DBMSs are so complex</a>, I raised the issue of type mismatches between the application language and the DBMS.</p>
<p>Type matching between the DBMS and the application is as important as types themselves for successful application development. If a type behaves one way in the DBMS, and a &#8220;similar&#8221; type behaves slightly differently in the application, that can only cause confusion. And it&#8217;s a source of unnecessary awkwardness: you already need to define the types that suit your business best in one place, why do you need to redefine them somewhere else, based on a different basic type system?</p>
<p><span id="more-14"></span></p>
<p>At least we&#8217;re using PostgreSQL, the most extensible database available, where you can define sophisticated types and make them perform like native features.</p>
<p>But there are still problems. Most notably, it&#8217;s a non-trivial challenge to find an appropriate way to model NULLs in the application language. You can&#8217;t <strong>not</strong> use them in the DBMS, because the SQL spec generates them from oblivion, e.g. from an outer join or an aggregate function, even when you have no NULLs in your database. So the only way to model the same semantics in your application is to somehow make your application language understand NULL semantics.</p>
<div>Here&#8217;s how SQL NULL behaves:</p>
<pre>
=&gt; -- aggregate with one NULL input
=&gt; select sum(column1) from (values(NULL::int)) t;
sum
-----

(1 row)

=&gt; -- aggregate with two inputs, one of them NULL
=&gt; select sum(column1) from (values(1),(NULL)) t;
sum
-----
1
(1 row)

=&gt; -- aggregate with no input
=&gt; select sum(column1) from (values(1),(NULL)) t where false;
sum
-----

(1 row)

=&gt; -- + operator
=&gt; select 1 + NULL;
?column?
----------

(1 row)
</pre>
<p>I&#8217;ll divide the &#8220;NULL-ish&#8221; values of various languages into two broad categories:</p>
<ol>
<li>Separate type, few operators defined, error early, no 3VL &#8212; Python, Ruby and Haskell fall into this category, because their &#8220;NULL-ish&#8221; types (<tt>None</tt>, <tt><strong>nil</strong></tt>, and <tt><strong>Nothing</strong></tt>, respectively) usually result in an immediate exception, unless the operator to which the NULLish value is passed handles it as a special case. Few built-in operators are defined for arguments of these types. These fail to behave like SQL NULL, because they employ no three-valued logic (3VL) at all, and thus fail in the forth portion of the SQL example.</li>
<li>Member of all types, every operator defined &#8212; Perl and R fall into this category. Perl&#8217;s <strong>undef</strong> can be passed through many built-in operators (like +), but doesn&#8217;t ever use 3VL, so fails the forth portion of the SQL example. R uses a kind of 3VL for it&#8217;s <tt><strong>NA</strong></tt> value, but it uses it everywhere, so <tt>sum(c(1,<strong>NA</strong>))</tt> results in <tt><strong>NA</strong></tt> (thus failing the second portion of the SQL example). In R, you can omit <tt>NA</tt>s from the sum explicitly (not a very good solution, by the way), but then it will fail the first portion of the SQL example.</li>
</ol>
<p>As far as I can tell (correct me if I&#8217;m mistaken), none of these languages support the third portion of the SQL example: the sum of an empty list in SQL is NULL. The languages that I tested with a built-in <tt>sum</tt> operator (Python, R, Haskell) all return <tt>0</tt> when passed an empty list.</p>
<p>Languages from the first category appear safer, because you will catch the errors earlier rather than later. However, transforming SQL NULLs in these languages to <tt>None</tt>, <tt><strong>nil</strong></tt>, or <tt><strong>Nothing</strong></tt> is actually quite dangerous, because a change in the data you store in your database (inserting NULLs or deleting records that may be aggregated) or even a change in a query (outer join, or an aggregate that may have no input) can produce NULLs, and therefore produce exceptions, that can evade even rigorous testing procedures and sneak into production.</p>
<p>Languages from the second category tend to pass the &#8220;<strong>undef</strong>&#8221; or &#8220;<strong>NA</strong>&#8221; along deeper into the application, which can cause unintuitive and difficult-to-trace problems. Perhaps worse, something will always happen, and usually the result will take the form of the correct answer even if it is wrong.</p>
<p>So where does that leave us? I think the blame here rests entirely on the SQL standard&#8217;s definition of NULL, and the inconsistency between &#8220;not a value at all&#8221; and &#8220;the third logical value&#8221; (both of which can be used to describe NULL in different contexts). Not much can be done about that, so I think the best strategy is to try to interpret and remove NULLs as early as possible. They can be removed from result sets before returning to the client by using COALESCE, and they can be removed after they reach the client with client code. Passing them along as some kind of special value is only useful if your application already must be thoroughly aware of that special value.</p>
<p>Note: Microsoft has defined some kind of &#8220;DBNull&#8221; value, and from browsing the docs, it appears a substantial amount of work went into making them behave as SQL NULLs. This includes a special set of SQL types and operators. Microsoft appears to be making a lot of progress matching DBMS and application types more closely, but I think the definition of SQL NULLs is a lost cause.</p></div>
]]></content:encoded>
			<wfw:commentRss>http://thoughts.j-davis.com/2008/08/13/none-nil-nothing-undef-na-and-sql-null/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
	</channel>
</rss>
