<?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; SQL</title>
	<atom:link href="http://thoughts.j-davis.com/tag/sql/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</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>6</slash:comments>
		</item>
		<item>
		<title>Temporal PostgreSQL Roadmap</title>
		<link>http://thoughts.j-davis.com/2010/03/09/temporal-postgresql-roadmap/</link>
		<comments>http://thoughts.j-davis.com/2010/03/09/temporal-postgresql-roadmap/#comments</comments>
		<pubDate>Wed, 10 Mar 2010 04:49:06 +0000</pubDate>
		<dc:creator>Jeff Davis</dc:creator>
				<category><![CDATA[Databases]]></category>
		<category><![CDATA[Language]]></category>
		<category><![CDATA[Logic]]></category>
		<category><![CDATA[PostgreSQL]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[Temporal]]></category>

		<guid isPermaLink="false">http://thoughts.j-davis.com/?p=254</guid>
		<description><![CDATA[Why are temporal extensions in PostgreSQL important? Quite simply, managing time data is one of the most common requirements, and current general-purpose database systems don&#8217;t provide us with the basic tools to do it. Every general-purpose DBMS falls short both in terms of usability and performance when trying to manage temporal data. What is already [...]]]></description>
			<content:encoded><![CDATA[<p>Why are temporal extensions in PostgreSQL important? Quite simply, managing time data is one of the most common requirements, and current general-purpose database systems don&#8217;t provide us with the basic tools to do it. Every general-purpose DBMS falls short both in terms of usability and performance when trying to manage temporal data.</p>
<p>What is already done?</p>
<p><span id="more-254"></span></p>
<ul>
<li><a href="http://pgfoundry.org/projects/temporal">PERIOD data type</a>, which can represent anchored intervals of time; that is, a chunk of time with a definite beginning and a definite end (in contrast to a SQL INTERVAL, which is not anchored to any specific beginning or end time).
<ul>
<li>Critical for usability because it acts as a <em>set</em> of time, so you can easily test for containment and other operations without using awkward constructs like BETWEEN or lots of comparisons (and keeping track of inclusivity/exclusivity of boundary points).</li>
<li>Critical for performance because you can index the values for efficient &#8220;contains&#8221; and &#8220;overlaps&#8221; queries (among others).</li>
</ul>
</li>
</ul>
<ul>
<li>Temporal Keys (called Exclusion Constraints, and will be available in the next release of PostgreSQL, 9.0), which can enforce the constraint that no two periods of time (usually for a given resource, like a person) overlap. See the <a href="http://developer.postgresql.org/pgdocs/postgres/sql-createtable.html">documentation</a> (look for the word &#8220;EXCLUDE&#8221;), and see my previous articles (<a href="../2009/11/01/temporal-keys-part-1/">part 1</a> and <a href="../2009/11/08/temporal-keys-part-2/">part 2</a>) on the subject.
<ul>
<li>Critical for usability to avoid procedural, error-prone hacks to enforce the constraint with triggers or by splitting time into big chunks.</li>
<li>Critical for performance because it performs comparably to a UNIQUE index, unlike the other procedural hacks which are generally too slow to use for most real systems.</li>
</ul>
</li>
</ul>
<p>What needs to be done?</p>
<ul>
<li>Range Types &#8212; Aside from PERIOD, which is based on TIMESTAMPTZ, it would also be useful to have very similar types based on, for example, DATE. It doesn&#8217;t stop there, so the natural conclusion is to generalize PERIOD into &#8220;range types&#8221; which could be based on almost any subtype.</li>
<li>Range Keys, Foreign Range Keys &#8212; If Range Types are known to the Postgres engine, that means that we can have syntactic sugar for range keys (like temporal keys, except for any range type), etc., that would internally use Exclusion Constraints.</li>
<li>Range Join &#8212; If Range Types are known to the Postgres engine, there could be syntactic sugar for a &#8220;range join,&#8221; that is, a join based on &#8220;overlaps&#8221; rather than &#8220;equals&#8221;. More importantly, there could be a new join type, a Range Merge Join, that could perform this join efficiently (without a Range Merge Join, a range join would always be a nested loop join).</li>
<li>Simple table logs &#8212; The ability to easily create an effective &#8220;audit log&#8221; or similar trigger-based table log, that can record changes and be efficiently queried for historical state or state changes.</li>
</ul>
<p>I&#8217;ll be speaking on this subject (specifically, the new Exclusion Constraints feature) in the upcoming <a href="http://postgresqlconference.org">PostgreSQL Conference EAST 2010</a> (my <a href="http://postgresqlconference.org/2010/east/talks/not_just_unique_exclusion_constraints">talk description</a>) in Philadelphia later this month and <a href="http://pgcon.org">PGCon 2010</a> (my <a href="http://www.pgcon.org/2010/schedule/events/201.en.html">talk description</a>) in Ottawa this May. In the past, these conferences and others have been a great place to get ideas and help me move the temporal features forward.</p>
<p>The existing features have been picking up a little steam lately. The <a href="http://lists.pgfoundry.org/pipermail/temporal-general/">temporal-general mailing list</a> has some traffic now &#8212; fairly low, but enough that others contribute to the discussions, which is a great start. I&#8217;ve also received some great feedback from a number of people, including the folks at <a href="http://pgexperts.com">PGX</a>. There&#8217;s still a ways to go before we have all the features we want, but progress is being made.</p>
]]></content:encoded>
			<wfw:commentRss>http://thoughts.j-davis.com/2010/03/09/temporal-postgresql-roadmap/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Scalability and the Relational Model</title>
		<link>http://thoughts.j-davis.com/2010/03/07/scalability-and-the-relational-model/</link>
		<comments>http://thoughts.j-davis.com/2010/03/07/scalability-and-the-relational-model/#comments</comments>
		<pubDate>Sun, 07 Mar 2010 21:37:24 +0000</pubDate>
		<dc:creator>Jeff Davis</dc:creator>
				<category><![CDATA[Databases]]></category>
		<category><![CDATA[Language]]></category>
		<category><![CDATA[Logic]]></category>
		<category><![CDATA[NoSQL]]></category>
		<category><![CDATA[PostgreSQL]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://thoughts.j-davis.com/?p=242</guid>
		<description><![CDATA[The relational model is just a way to represent reality. It happens to have some very useful properties, such as closure over many useful operations &#8212; but it&#8217;s a purely logical model of reality. You can implement relational operations using hash joins, MapReduce, or pen and paper. So, right away, it&#8217;s meaningless to talk about [...]]]></description>
			<content:encoded><![CDATA[<p>The relational model is just a way to represent reality. It happens to have some very useful properties, such as closure over many useful operations &#8212; but it&#8217;s a purely logical model of reality. You can implement relational operations using hash joins, MapReduce, or pen and paper.</p>
<p>So, right away, it&#8217;s meaningless to talk about the scalability of the relational model. Given a particular question, it might be difficult to break it down into bite-sized pieces and distribute it to N worker nodes. But going with MapReduce doesn&#8217;t solve that scalability problem &#8212; it just means that you will have a hard time defining a useful map or reduce operation, or you will have to change the question into something easier to answer.</p>
<p><span id="more-242"></span>There may exist scalability problems in:</p>
<ul>
<li>SQL, which defines requirements outside the scope of the relational model, such as ACID properties and transactional semantics.</li>
<li>Traditional architectures and implementations of SQL, such as the &#8220;table is a file&#8221; equivalence, lack of sophisticated types, etc.</li>
<li>Particular implementations of SQL &#8212; e.g. &#8220;MySQL can&#8217;t do it, so the relational model doesn&#8217;t scale&#8221;.</li>
</ul>
<p>Why are these distinctions important? As with many debates, <a title="Terminology Confusion" href="http://thoughts.j-davis.com/2007/12/11/terminology-confusion/">terminology confusion</a> is at the core, and prevents us from dealing with the problems directly. If SQL is defined in a way that causes scalability problems, we need to identify precisely those requirements that cause a problem, so that we can proceed forward without losing all that has been gained. If the traditional architectures are not suitable for some important use-cases, they need to be adapted. If some particular implementations are not suitable, developers need to switch or demand that it be made competitive.</p>
<p>The NoSQL movement (or at least the hype surrounding it) is far too disorganized to make real progress. Usually, incremental progress is best; and sometimes a fresh start is best, after drawing on years of lessons learned. But it&#8217;s never a good idea to start over with complete disregard for the past. For instance, an <a href="http://about.digg.com/blog/looking-future-cassandra">article from Digg</a> starts off great:</p>
<blockquote><p>The fundamental problem is endemic to the relational database mindset, which places the burden of computation on reads rather than writes.</p></blockquote>
<p>That&#8217;s good because he blames it on the <em>mindset</em> not the <em>model</em>,<em> </em>and then identifies a specific problem. But then the article completely falls flat:</p>
<blockquote><p>Computing the intersection with a JOIN is much too slow in MySQL, so we have to do it in PHP.</p></blockquote>
<p>A join is faster in PHP than MySQL? Why bother even discussing SQL versus NoSQL if your particular implementation of SQL &#8212; MySQL &#8212; can&#8217;t even do a hash join, the exact operation that you need? Particularly when almost every other implementation can (including PostgreSQL)? That kind of reasoning won&#8217;t lead to solutions.</p>
<p>So, where do we go from here?</p>
<ol>
<li>Separate the SQL model from the other requirements (some of which may limit scalability) when discussing improvements.</li>
<li>Improve the SQL model (my readers know that I&#8217;ve criticized SQL&#8217;s logical problems many times in the past).</li>
<li>Improve the implementations of SQL, particularly how tables are physically stored.</li>
<li>If you&#8217;re particularly ambitious, come up with a relational alternative to SQL that takes into account what&#8217;s been learned after decades of SQL and can become the next general-purpose DBMS language.</li>
</ol>
<p>EDIT 2010-03-09: I should have cited Josh Berkus&#8217;s talk on <a href="http://www.pgexperts.com/document.html?id=40">Relational vs. Non-Relational</a> (complete list of <a href="http://www.pgexperts.com/presentations.html">PGX talks</a>), which was part of the inspiration for this post.<a href="http://www.pgexperts.com/document.html?id=40"><br />
</a></p>
]]></content:encoded>
			<wfw:commentRss>http://thoughts.j-davis.com/2010/03/07/scalability-and-the-relational-model/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Good Error Recovery is Hard, So Use PostgreSQL</title>
		<link>http://thoughts.j-davis.com/2009/12/23/good-error-recovery-is-hard-so-use-postgresql/</link>
		<comments>http://thoughts.j-davis.com/2009/12/23/good-error-recovery-is-hard-so-use-postgresql/#comments</comments>
		<pubDate>Thu, 24 Dec 2009 04:29:04 +0000</pubDate>
		<dc:creator>Jeff Davis</dc:creator>
				<category><![CDATA[Databases]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[PostgreSQL]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://thoughts.j-davis.com/?p=221</guid>
		<description><![CDATA[My last post about the Linux OOM Killer got a lot of attention, and I don&#8217;t intend to re-open the whole discussion. However, a couple themes developed that I think warrant some further discussion. One of those themes is that &#8220;error recovery is hard,&#8221; and that&#8217;s absolutely true. It&#8217;s so true that many of the [...]]]></description>
			<content:encoded><![CDATA[<p>My <a href="http://thoughts.j-davis.com/2009/11/29/linux-oom-killer/">last post about the Linux OOM Killer</a> got a lot of attention, and I don&#8217;t intend to re-open the whole discussion. However, a couple themes developed that I think warrant some further discussion. One of those themes is that &#8220;error recovery is hard,&#8221; and that&#8217;s absolutely true. It&#8217;s so true that many of the kernel developers seemed to develop a more extreme version: &#8220;error recovery is infeasible&#8221; (see this <a href="http://article.gmane.org/gmane.comp.audio.jackit/19998">post</a>) &#8212; but that is <strong>not</strong> true.</p>
<p><a href="http://postgresql.org">PostgreSQL</a> is a great example: it gets error recovery <em>right</em>. I didn&#8217;t say it&#8217;s perfect, but graceful degradation is designed into postgres from the start, and if it doesn&#8217;t degrade gracefully, that&#8217;s probably a bug. I am saying this as a person who experienced a not-so-graceful PostgreSQL problem first-hand back in 2006 that was due to an OOM condition on FreeBSD (and yes, <code>malloc()</code> returned <code>NULL</code>). But:</p>
<ul>
<li>The bug occurred under fairly strange circumstances where very small allocations ate the memory very completely, leaving no room (not even a few dozen bytes), during a transaction that included extensive DDL (note that most database systems can&#8217;t even do transactional DDL at all).</li>
<li>The bug was <a href="http://git.postgresql.org/gitweb?p=postgresql.git;a=commit;h=56fb6b53d215d88a581588450a997d31959df9e8">fixed</a>!</li>
</ul>
<p>A database system getting error recovery right is no accident, fluke, or statistical outlier. Database systems are meant to get this right <em>so that applications do not have to do it</em>. In other words, write applications against PostgreSQL (or another robust relational database system), and you get error recovery for free.</p>
<p>The application may be performing a complex series of updates or state changes, and trying to ensure graceful error recovery without a database system to help may be nearly impossible. But by simply wrapping those operations in a single transaction, the application only needs to know how to handle a few classes of errors, and will always see consistent data afterward.</p>
<p>Moral of the story: if you&#8217;re not building on top of a robust DBMS, and you have any significant amount of state to manage, then you are not getting error recovery right (unless you put in the serious analysis required). Similar problems apply to those using a DBMS like a filesystem, with no constraints (to prevent corruption) and related operations split across transactional boundaries. So: use PostgreSQL, use transactions, and use constraints.</p>
]]></content:encoded>
			<wfw:commentRss>http://thoughts.j-davis.com/2009/12/23/good-error-recovery-is-hard-so-use-postgresql/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Temporal Keys, Part 2</title>
		<link>http://thoughts.j-davis.com/2009/11/08/temporal-keys-part-2/</link>
		<comments>http://thoughts.j-davis.com/2009/11/08/temporal-keys-part-2/#comments</comments>
		<pubDate>Mon, 09 Nov 2009 05:48:37 +0000</pubDate>
		<dc:creator>Jeff Davis</dc:creator>
				<category><![CDATA[Databases]]></category>
		<category><![CDATA[Language]]></category>
		<category><![CDATA[PostgreSQL]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[Temporal]]></category>

		<guid isPermaLink="false">http://thoughts.j-davis.com/?p=180</guid>
		<description><![CDATA[In the last article, I argued that: A schedule conflict is a typical business problem. The later you try to resolve a schedule conflict, the more costly it is to resolve. In particular, there is a big jump in the cost the moment after conflicting data is recorded. Therefore, it&#8217;s best for the DBMS itself [...]]]></description>
			<content:encoded><![CDATA[<p>In the <a title="Temporal Keys, Part 1" href="http://thoughts.j-davis.com/2009/11/01/temporal-keys-part-1/">last article</a>, I argued that:</p>
<ul>
<li>A schedule conflict is a typical business problem.</li>
<li>The later you try to resolve a schedule conflict, the more costly it is to resolve.</li>
<li>In particular, there is a big jump in the cost the moment after conflicting data is recorded.</li>
<li>Therefore, it&#8217;s best for the DBMS itself to enforce the constraint, because only the DBMS can avoid the conflict effectively before the conflict is recorded.</li>
</ul>
<p>Then, I opened up a discussion to see how people are dealing with these schedule conflicts. In the comments I received at the end of the article, as well as other anecdotes from conferences, user groups, mailing lists, and my own experience, the solutions fall into a few categories:</p>
<p><span id="more-180"></span></p>
<ul>
<li>The rate of conflicts is so low that the costs are not important. For instance, you may make 0.1% of your customers unhappy, and need to refund them, but perhaps that&#8217;s a cost you&#8217;re willing to pay.</li>
<li>The application receives so few requests that performance is not an object, and serialization of all requests is a viable option. The serialization is done using big locks and a read-check-write cycle. Even if performance is not an object, these applications sometimes run into maintenance problems or unexpected outages because of the big locks required.</li>
<li>You can break the time slices into manageable chunks, e.g. one day chunks aligned at midnight. This kind of solution is highly specific to the business, reduces the flexibility of the business, and often requires a substantial amount of custom, error-prone procedural code.</li>
<li>Complex procedural code: usually a mix of application code, functions in the DBMS, row-level locking, static data in tables that only exists for the purposes of row-level locks, etc. This kind of solution is generally very specific to the application and the business, requires lots of very error-prone custom procedural code, is difficult to adequately test, and it&#8217;s hard to understand what&#8217;s going on in the system at any given time. Hunting down sporadic performance problems would be a nightmare.</li>
</ul>
<p>Those solutions just aren&#8217;t good enough. We use relational database systems because they are smart, declarative, generally useful for many problems, and maintainable (Note: these principles contrast with <a href="http://en.wikipedia.org/wiki/NoSQL">NoSQL</a>, which is moving in the opposite direction &#8212; more on that in another article).</p>
<p><em>[UPDATE: The following project has been committed for the next release of PostgreSQL; the feature is now called "Exclusion Constraints"; and the new version of PostgreSQL will be called 9.0 (not 8.5). See the <a href="http://developer.postgresql.org/pgdocs/postgres/sql-createtable.html">documentation</a> under the heading "EXCLUDE".]</em></p>
<p>The project that I&#8217;ve been working on for PostgreSQL 8.5 is called &#8220;<a href="https://commitfest.postgresql.org/action/patch_view?id=199">Operator Exclusion Constraints</a>&#8220;. These are a new type of constraint that most closely resembles the <code>UNIQUE</code> constraint, because one tuple can preclude the existence of other tuples. With a <code>UNIQUE</code> constraint on attribute <code>A</code> of a table with attributes <code>(A, B, C)</code>, the existence of the tuple <code>(5, 6, 7)</code> precludes the existence of any tuple <code>(5, _, _)</code> in that table at the same time. This is different from a foreign key, which <em>requires</em> the existence of a tuple in another table; and different from a <code>CHECK</code> constraint which rejects tuples independently from any other tuple in any table (and the same goes for NOT NULL).</p>
<p>The same semantics as a <code>UNIQUE</code> constraint can be easily specified as an Operator Exclusion Constraint, with a minor performance penalty at insert time (one additional index search, usually only touching pages that are already in cache). Exclusion constraints are more general than <code>UNIQUE</code>, however. For instance, with a complex type such as <a href="http://www.postgresql.org/docs/8.4/static/datatype-geometric.html#AEN6211">CIRCLE</a>, you can specify that no two circles in a table overlap &#8212; which is a constraint that is impossible to specify otherwise (without resorting to the poor solutions mentioned above<a title="Temporal Keys, Part 1" href="../2009/11/01/temporal-keys-part-1/"></a>).</p>
<p>This applies to temporal keys very nicely. First, get the <a href="http://pgfoundry.org/projects/temporal">PERIOD data type</a>, which allows you a better way to work with periods of time (sets of time, really), rather than points in time. Second, you need to install the <a href="http://www.postgresql.org/docs/8.4/static/btree-gist.html">btree_gist</a> contrib module. Then, use an exclusion constraint like so:</p>
<p><em>[UPDATE 2010-03-09: Syntax updated to reflect the version of this project committed for PostgreSQL 9.0. ]</em></p>
<pre>CREATE TABLE room_reservation
(
  name   TEXT,
  room   TEXT,
  during PERIOD,
  EXCLUDE USING gist (room WITH =, during WITH &amp;&amp;)
);</pre>
<p>That will prevent two reservations on the same room from overlapping. There are a few pieces to this that require explanation:</p>
<ul>
<li><code>&amp;&amp;</code> is the &#8220;overlaps&#8221; operator for the <code>PERIOD</code> data type.</li>
<li><code>USING gist</code> tells PostgreSQL what kind of index to create to enforce this constraint. The operators must map to search strategies for this index method, and searching for overlapping periods requires a GiST index.</li>
<li>Because we are using GiST, we need GiST support for equality searches for the <code>TEXT</code> data type, which is the reason we need the btree_gist contrib module.</li>
<li>Conflicts will only occur if two tuples have equal room numbers, <em>and</em> overlapping periods of time for the reservation.</li>
</ul>
<p>This solution:</p>
<ul>
<li>Performs well under light and heavy contention. Not quite as well as a UNIQUE constraint, but much better than the alternatives, and without the surprises you might get from using big locks. Note that the constraint <em>will </em>be enforced at some point, so ignoring the problem is not a high-performance alternative (interpersonal communication has higher latency than a computer).</li>
<li>Is declarative. The implementation shows through a little bit &#8212; the user will know that an index is being used, for instance &#8212; but it&#8217;s a relatively simple declaration. As a consequence, it&#8217;s not very error-prone from the schema designer&#8217;s standpoint.</li>
<li>Is not specific to the business. You don&#8217;t have to decide on an appropriate time slice (e.g. one hour, one day, etc.); you don&#8217;t have to try to partition locks in creative ways; you don&#8217;t have to write procedural code (in the database system or application); and you don&#8217;t have to come up with interesting ways to detect a conflict or notify the user.</li>
</ul>
<p>Temporal keys are just one part of the support required for effective temporal data management inside the DBMS. However, it&#8217;s one of the most important pieces that requires support from the core engine, and cannot be implemented as a module.</p>
]]></content:encoded>
			<wfw:commentRss>http://thoughts.j-davis.com/2009/11/08/temporal-keys-part-2/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Temporal Keys, Part 1</title>
		<link>http://thoughts.j-davis.com/2009/11/01/temporal-keys-part-1/</link>
		<comments>http://thoughts.j-davis.com/2009/11/01/temporal-keys-part-1/#comments</comments>
		<pubDate>Mon, 02 Nov 2009 00:55:34 +0000</pubDate>
		<dc:creator>Jeff Davis</dc:creator>
				<category><![CDATA[Databases]]></category>
		<category><![CDATA[Logic]]></category>
		<category><![CDATA[PostgreSQL]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[Temporal]]></category>

		<guid isPermaLink="false">http://thoughts.j-davis.com/?p=171</guid>
		<description><![CDATA[&#8220;Schedule conflict&#8221; &#8212; it&#8217;s one of the simplest and most common constraints for business or any other organization. One person cannot be in two places at the same time; and in many cases a only a single person can use a given resource at any time. Does your database system know anything about a schedule [...]]]></description>
			<content:encoded><![CDATA[<p>&#8220;Schedule conflict&#8221; &#8212; it&#8217;s one of the simplest and most common constraints for business or any other organization. One person cannot be in two places at the same time; and in many cases a only a single person can use a given resource at any time.</p>
<p>Does your database system know anything about a schedule conflict? Should it?</p>
<p>Constraints are always enforced at some point, it&#8217;s just a matter of when, how, and the cost of correcting the situation.</p>
<p><span id="more-171"></span>Consider two professors who try to reserve the same lecture hall at overlapping times (let&#8217;s say 1-2pm, and 1:30-2:30pm). Now imagine two possible resolutions:</p>
<ol>
<li>They are blissfully unaware of the schedule conflict until they have already promoted their lecture, attracted an audience, and arrived at the building. The professor scheduled for 1:30-2:30pm will be disappointed to find it already in use, and the students will be confused. The second lecture may have to be canceled due to the confusion, or lose a substantial number of attendees.</li>
<li>At the time of scheduling, one professor is given an error message to the effect of &#8220;this room is already reserved, please choose a different time&#8221;.</li>
</ol>
<p>Observe that neither one really solves the problem: the second resolution still forces one professor to choose a less-desirable time. However, it is a <em>much</em> cheaper resolution. As with many problems, early detection is simplest and cheapest to resolve.</p>
<p>Of course, there are many resolutions that fall between the first and the second. For instance, you might run a program every hour that checks for conflicts and alerts the parties involved. That may work, but there are still problems:</p>
<ul>
<li>You&#8217;ve now introduced uncertainty into the system: do I have a reservation or not? If there is a conflict later, will I be kicked out or will they?</li>
<li>You have to come up with rules for resolution: does the first one win? How do you define &#8220;first&#8221; if transactions are running for a while? What if someone makes a reservation &#8220;first&#8221; but then makes all kinds of changes later; were they really first or did they just game the system?</li>
<li>If someone&#8217;s reservation gets bumped, you have to now have a new strange state for a reservation, in which it is disabled, the organizer has (hopefully) been notified, and it needs to change.</li>
<li>Notice that everything is very procedural and specific to the business. You have to have a notification mechanism, and rules for how to resolve it.</li>
<li>Let&#8217;s go back to the definition of &#8220;first&#8221;: say you have made a reservation, and you get bumped by the conflict detector. In between the time you made the reservation and the time you were notified of a conflict, someone else reserved your second choice. Are you now first in line for that time slot? If so, that has a cascading effect such that it&#8217;s almost impossible for the person that took the second-choice slot to know that they are at risk of being bumped.</li>
</ul>
<p>These thought experiments might seem like edge cases, but reservation systems have two common traits that make these problems very real:</p>
<ol>
<li>They tend to start allowing reservations of a specific resource at a specific time, published in advance.</li>
<li>There tend to be some resources and time slots that have a much higher value than the others.</li>
</ol>
<p>These two traits lead to heavy contention.</p>
<p>Now, how would you go about enforcing such a constraint (non-overlapping time periods) in the database? While considering possible solutions, think about:</p>
<ul>
<li>Does the solution work for a wide variety of use cases, or only in special cases?</li>
<li>How well would it perform, under low contention and high contention, and under varied workloads?</li>
<li>Can it be implemented in a general purpose RDBMS, like PostgreSQL?</li>
<li>Is it procedural in nature, or declarative?</li>
</ul>
<p>I think it&#8217;s worthwhile to consider the problem, so I will end this article now, and provide some approaches, as well as my real answer, in the next article. In the meantime, feel free to post ideas as comments.</p>
]]></content:encoded>
			<wfw:commentRss>http://thoughts.j-davis.com/2009/11/01/temporal-keys-part-1/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>PostgreSQL WEST and Temporal Databases</title>
		<link>http://thoughts.j-davis.com/2009/10/12/postgresql-west-and-temporal-databases/</link>
		<comments>http://thoughts.j-davis.com/2009/10/12/postgresql-west-and-temporal-databases/#comments</comments>
		<pubDate>Tue, 13 Oct 2009 05:09:57 +0000</pubDate>
		<dc:creator>Jeff Davis</dc:creator>
				<category><![CDATA[Databases]]></category>
		<category><![CDATA[Language]]></category>
		<category><![CDATA[PostgreSQL]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[Temporal]]></category>

		<guid isPermaLink="false">http://thoughts.j-davis.com/?p=152</guid>
		<description><![CDATA[I&#8217;ve been interested in temporal data and relational databases for quite some time. There are going to be at least two people talking about temporal data at PostgreSQL WEST in Seattle: Scott Bailey and me. See the talk descriptions. In the past, I&#8217;ve worked on a temporal extension to PostgreSQL that implements the PERIOD data [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been interested in temporal data and relational databases for quite some time. There are going to be at least two people talking about temporal data at <a title="PG WEST" href="http://postgresqlconference.org">PostgreSQL WEST</a> in Seattle: <a href="http://scottrbailey.wordpress.com/">Scott Bailey</a> and me. See the <a href="http://postgresqlconference.org/2009/west/talks">talk descriptions</a>.</p>
<p>In the past, I&#8217;ve worked on a <a title="Temporal PostgreSQL" href="http://pgfoundry.org/projects/temporal">temporal extension</a> to PostgreSQL that implements the <code>PERIOD</code> data type. This is a data type that offers both a definite beginning and a definite end time, which is important for describing things that happen over a period of time, rather than instantaneously. Trying to use separate attributes for &#8220;start&#8221; and &#8220;end&#8221; is bad for a number of reasons, and will certainly be addressed in a subsequent blog entry. For now, I&#8217;ll just say that I believe the <code>PERIOD</code> data type is fundamentally important for handling all kinds of time data, which I believe is a common problem.</p>
<p>At WEST, I&#8217;ll be presenting my progress on <em>temporal keys</em>. Temporal keys are used to prevent overlapping periods of time &#8212; a schedule conflict &#8212; by using an index and following the same concurrent behavior as <code>UNIQUE</code> with minimal performance cost (one extra index search, to be precise).</p>
<p>Temporal keys cannot be expressed in PostgreSQL 8.4, unless you resort to triggers and a full table lock (ouch!). So, additional backend support is required. This is accomplished in my patch for <a title="Operator Exclusion Constraints GIT repo" href="http://git.postgresql.org/gitweb?p=users/jdavis/postgres.git;a=shortlog;h=refs/heads/operator-exclusion-constraints">operator exclusion constraints</a>, which are a more general way of using arbitrary operators and index searches to enforce a constraint. I plan to do what&#8217;s required for the patch to be accepted in PostgreSQL 8.5.</p>
<p>Temporal modeling is a common problem. It seems like almost every PostgreSQL conference has had at least one talk on the matter, so we know there is some demand for improvement. If you&#8217;re interested, I hope you come to WEST and chat with Scott or I, and let&#8217;s see if we can come up with some real solutions.</p>
]]></content:encoded>
			<wfw:commentRss>http://thoughts.j-davis.com/2009/10/12/postgresql-west-and-temporal-databases/feed/</wfw:commentRss>
		<slash:comments>4</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>
