Wednesday, September 19, 2012

"Converting SQL to Relational Algebra"

It's that time of the year again.  Introductory courses in relational data management (I'm a bit reluctant to call them "courses in relational theory") are starting again, all over the world, and consequently, students seeking advice and assistance from "professionals" start posing "Converting SQL to Relational Algebra" questions again on various database-related discussion fora, when they are not able to solve assignments given to them in class, or when they are uncertain their solution is correct.

I would actually like any of the teachers who give such assignments to try and explain to me what purpose they hope to be achieving by giving such assignments.  What do students learn from this ?  I recently got involved in such a "Converting SQL to Relational Algebra" question, and one remark the student made, in the discussion that ensued, confirms my feeling regarding this : they learn nothing at all, and "Converting SQL to Relational Algebra" is completely pointless, only adding to the confusion instead of resolving it.  (The remark was, literally, : "we do not either understand why we are learning this".)

Why is this so ?  Well, it's because Relational Algebra is foundational, and SQL is not.  That's because Relational Algebra is completely abstract, and SQL is not.  Not in the same sense that Relational Algebra is abstract.  SQL is abstract with respect to the procedures and algorithms that the implementing engine executes in order to carry out a given SQL command.  But that is not quite as "profound" or "foundational" a level of abstraction as the one the Relational Algebra can be said to have.

SQL is just a syntax for expressing formulae of the RA.  One possible syntax for it.  Of the plethora of distinct possible syntaxes that can be conceived to do the same.  And SQL is an awful syntax for that purpose, come to that.  That's because initially, SQL was firmly rooted in predicate calculus, not in relational algebra.  That SQL can express relational algebra, is only a "coincidental" consequence of the fact that predicate calculus and relational algebra were later proven equivalent.  That historical reason is why, for example, relational difference had to be expressed using WHERE NOT EXISTS (...), and EXCEPT was only introduced in the standard decades later.

Granted, if you teach RA first and only then SQL, you are headed for a shit load of questions, "why did they make that syntax so quirky if the algebra is so simple" ?  The answer is always the same : poor historical reasons.  BTW there's a great book forthcoming that fits this line of teaching perfectly.  But at least they could understand.

And the fact still remains that if students can first manage to understand RA, then they can understand any language that implements or supports it.  They will then understand that, as far as RA operations are concerned, the difference between SQL and, say, Tutorial D, is a mere matter of syntax.  They might understand that the Tutorial D expression 'R1 JOIN R2' is the very same thing as the SQL expressions 'SELECT * FROM R1,R2 WHERE R1.<attr> = R2.<attr>', 'SELECT * FROM R1 JOIN R2 ON ...' and 'SELECT * FROM R1 NATURAL JOIN R2'.  And the reason they would understand, is precisely that their thinking would be in RA, not in SQL or any other specific language.

We urgently need to learn our database designers to think of data in terms of sets (sets of tuples, where those sets represent the extension of a logical predicate, and each tuple represents a proposition), and to think of manipulations on that data in terms of relational algebra.  Not in terms of tables and SQL.

And it means that the teaching should no longer be about "Converting SQL to relational algebra", but instead about "Converting relational algebra to SQL".  The latter, not the former, is the sensible way of doing things.

Tuesday, September 18, 2012

"Why EAV sucks"

We've already seen this one before as an illustration of a cartesian product establishing a tuple type :

I:INT X C:CHAR = {(I:1,C:'A') , (I:1,C:'B') , ...}

and one possible relation deriving from this :

R = { (I:1,C:'A') , (I:1,C:'B') }

or, rewriting those tuples as sets of pairs mapping attribute names to values of arbitrary domains :

R = { {(I,1),(C,'A')} , {(I,1),(C,'B')}}

In tabular form (a fairly typical form for representing relation), this could become something like

IC
1A
2B

Well, tables consist of rows and columns, and with this particular view of a relation, both rows and columns turn out to have an interesting property.

Beginning with the rows.  It is obvious that one row contains precisely one tuple of the relation.  Nothing more and nothing less.  And one tuple corresponds to exactly one logical proposition that it represents.  That logical proposition being a sentence, a statement of fact.  For example, "Yesterday, the average temperature in room A was 1 degrees centigrade.".

Then the columns.  What is common for all the things mentioned in the column labeled 'I' ?  They are all numbers originating from domain INT.  Likewise for the things mentioned in the column labeled 'C'.  In our data manipulation language, this means that if we have a reference to column (/attribute) 'C', we just know that what we're referring to is a CHAR value.  We don't need to typecheck this at runtime.  It's guaranteed by the typechecks that occurred when the tuple was inserted.

Remember these two.  They're important.

A closer look at one of these two tuples themselves now.

{(I,1),(C,'A')}

That's a set of ordered pairs.  The first member of each pair coming from the domain of 'valid attribute names', the second coming from ...   Well from what exactly ?  We can't say that the second member of all pairs here comes from INT, nor from CHAR, nor in fact from any domain we used to build tuple types and relations with.  Rather, all we can say is that it's just some value from some domain, but we don't know which it is.  (We can know which one it is, by inspecting the value of the first member (the attribute name), and then linking that somehow to the original way in which we defined our cartesian product/tuple type.)

Anyway.  A "set of ordered pairs" is a relation, thus a tuple is itself also a relation.  (But do keep the distinction in mind between "relation over the domains INT and CHAR" and "relation over the domains ATTRIBUTENAME and SET_UNION_OF_ALL_DOMAINS").

Anf if a tuple is itself also a relation, we could try out what we get if we wanted to represent it tabularly using the usual technique :

????????????
I1
CA

Compare with the "interesting properties" of the (tabular representation of) the relation.  Does the interesting property of the column still survive ?  No it doesn't.  Unless we find the fact of possibly getting back just anything from any expression in our data manipulation language an "interesting" property.  Does the interesting property of the rows (tuples of a relation) still stand ?  No it doesn't.  It just tells us that there has been a temperature of 1 degrees centigrade yesterday, in some further unspecified room, for example.  (But note that in order to derive so much information, we need to inspect the value of that "first column", and iterate over a set of used attribute names : "if it's C then that value is a room identifier.  No it's not C.  If it's I then that value is an average temperature.  Ah yes that's the one.")

(Aside.  The question marks are there for a reason.  What would you put in their place ?  Can the user of a system based on this paradigm of tuples-as-relations be given the freedom to choose his own preferred replacements for the question marks, in a sense similar to how the designer of a database is at freedom to choose his attribute names, when defining cartesian products aka tuple types ?  End-of-aside.)

One step further in the predictable direction.  Take a look at

??????ATTRIBUTENAMEVALUE
GUID-WXCVBN-AXIOI1
GUID-WXCVBN-AXIOCA
GUID-WXCVBN-AX1OI2
GUID-WXCVBN-AX1OCB

This table was obtained by prepending something very akin to a "tuple id", "entity id" or "object id" to the table, and then using those values for identifying "which attribute values belong together to form a tuple".

Looks like anything you know ?  Rhetorical question.  This is EAV.  Strip the RM from its connection to predicate logic (that is, remove the connection with 'meaning') and strip the RM from the static type checking that is offered by its most foundational building brick, the tuple (that is, remove the most fundamental data integrity feature of all), and what is left is EAV.  As another commenter put it : "disassemble the tuple and amputate the predicate".

Some thought exercises.  Assume you want to design a database like this.  Assume the name in place of the question marks is 'OID'.  Write all the needed constraints on this three-column table to effect the following :

- values corresponding to the ATTRIBUTENAME 'I' must be of domain INT.
- values corresponding to the ATTRIBUTENAME 'C' must be of domain CHAR.
- only complete tuples can be inserted.  That is, if an I or a C is inserted, then so must the corresponding C or I be.
- only complete tuples can be deleted.  That is, if an I or a C is deleted, then so must the corresponding C or I be.


These four constraints all derive naturally from a relational declaration as simple as (two examples)

VAR RELATION {I:INT C:CHAR} IC ;
CREATE TABLE IC (I INT, C CHAR) ;

Which of the two approaches is the easiest and the simplest ?

Further thought exercises.

A constraint must be introduced to the effect that "the I value must be less or equal than the position of the C value in the alphabet."  Write a query to check whether this constraint is currently satisfied by your EAV database, and spell out the strategy you're going to follow to enforce this rule.  Is it simpler or easier or less work involved than the following ? (two examples)

CONSTRAINT IC_RULE1 ALL(IC, I<=INDEXOF(C,"ABCDEFG...XYZ")) ;
ALTER TABLE IC CHECK (I<=INDEXOF(C,"ABCDEFG...XYZ")) ;

A constraint must be introduced to the effect that the I values are unique identifiers for any tuple.  Write a query to check whether this constraint is currently satisfied by your EAV database, and spell out the strategy you're going to follow to enforce this rule, or write out the declarative constraint that will enforce this in your EAV database.  Is it simpler or easier or less work involved than the following ? (two examples)

VAR RELATION {I:INT C:CHAR} IC KEY {I};
ALTER TABLE IC KEY (I) ;

Further thought exercise.  Read this sentence carefully.  Now look at the following EAV structure.

??????ATTRIBUTENAMEVALUE
GUID-WXCVBN-AXIOPOS1
GUID-WXCVBN-AXIOWORDRead
GUID-WXCVBN-AXOOPOS3
GUID-WXCVBN-AXOOWORDsentence
GUID-WXCVBN-AXO0POS4
GUID-WXCVBN-AXO0WORDcarefully
GUID-WXCVBN-AX1OPOS2
GUID-WXCVBN-AX1OWORDthis

I could write that same sentence, in cryptic form, in four lines :

Word 1 in the sentence is Read.
Word 3 in the sentence is sentence.
Word 4 in the sentence is carefully.
Word 2 in the sentence is this.

And EAV even goes beyond that in turning that into 8 lines !  How much work and computation does it involve to reassemble the original sentence from this ?



All of that should be sufficient to illustrate how much veracity there is to the claim that "EAV makes database maintenance easier".  Instead :

If you do not care about the data type of (the values in) your database fields, then EAV is your thing.
If you do not care about the meaning of the contents of your database, then EAV is your thing.
If you do not care about the integrity of your data, then EAV is your thing.

(In each of these cases, "do not care" is supposed to also include the notion that "the user doesn't mind paying all those extra hours you put in solving problems that the DBMS has already solved for you".)

Tuesday, September 11, 2012

"Types, Sets, Tuples, Headings, Relations, a set mess ???"

That's a long title, and it's intended to illustrate how all of that stuff that actually underpins the Relational Model of Data, mathematically speaking, may come across as "one big tangled mess of almost-but-not-quite similar-or-equal concepts all thrown on a big pile".

And the body of this installment is about illustrating how it really is not that "perceived mess".

The following example has been used more than once already in this little corner of the internet.


I:INT X C:CHAR = {(I:1,C:'A') , (I:1,C:'B') , ...}


At this point, I need to take one more step back to basics.  The foregoing definition assumed it to be "known" or "agreed-on" what those domains INT and CHAR precisely were, respectively.  I.e. what its constituent members are.  The thing to note is that those "domains" are sets, and their members are values :


INT = {1 , 2 , ...}
CHAR = {'A' , 'B' , ...}

And that's really all it takes to be a type.  A type is a set of values.  And a value can be whatever we want it to be.  If I have a good use for the set of guitar chords, I can choose that to be a type.  If I have a good use for the set {cloud, oak, armchair} or {scissors, stone, net}, I can choose that to be a type.

(Aside : of course, in a scenario of information exchange, the parties participating in the exchange need to be in full and perfect agreement on what the types are (which values are in it and which are not).  Exchange without such a full agreement is unpleasant surprises in the air and accidents waiting to happen.)


Back to

I:INT X C:CHAR = {(I:1,C:'A') , (I:1,C:'B') , ...}


Obviously, by definition in fact, such Cartesian products are themselves a set.  Are they then also a type ?  The predictable answer is of course 'yes'.  A Cartesian Product is a set of tuples, and if we regard these tuples as being values, then any Cartesian Product of domains constitutes a tuple type.


One step further.  Relations were defined to be any subset of this cartesian product.  Any set is a subset of itself, thus any cartesian product is also a subset of itself, thus any cartesian product is a relation, and since each cartesian product constitutes a tuple type, at least this "maximal" relation ("maximal" subset of the cartesian product of the domains) can also be said to constitute a tuple type.  But all other relations derived from the same cartesian product are also "just sets of tuples".  Likewise, really just any relation can be thought of as "constituting a tuple type".  This holds true even of the empty relation, even though it's fairly counterintuitive to imagine a type that has no values ...  (What could we possibly be using that for ???)

Is all of that important ?  The view of "really just any relation" as itself being, or constituting, a tuple type ?  Not really.  Except perhaps for this.  One could "subdivide" the set of all possible subsets of our cartesian product in three distinct "classes".  The first class consisting of just the subset that is the original cartesian product itself.  The second class being those subsets that can be defined "predicatively", by stating a constraining additional predicate such as, e.g. "I equals 1".  And the third class being "the others".  Pragmatically speaking, this third class can only be defined "by enumeration".  (Formally, there is no real distinction between "by enumeration" and "by predicate", because stating the enumeration is, from the perspective of logic, the very same thing as stating a predicate.)

The third class of subsets is thus characterized by the fact that its definition "looks like", e.g. "It's the tuple type I:INT C:CHAR where either I equals 1 and C equals 'Z', or I equals 5 and C equals 'W'".  Which is a predicate, but one that looks suspiciously much like a full enumeration.

The second class of subsets is thus characterized by the fact that its definition "looks like", e.g. "It's the tuple type I:INT C:CHAR where I equals 1".  A reasonably concise way to define possibly useful subsets/types.

The first class is thus characterized by the fact that its definition is just simply, "It's the tuple type I:INT C:CHAR".  The 'I:INT X C:CHAR' portion is the heading.  The (only) tuple type in this class can thus be said to be characterized by its heading alone.  All other conceivable tuple types with the same heading need an additional constraining predicate to define which tuples are and are not member of the type.  This is the reason why in practice, this particular tuple type is often called "the" tuple type corresponding to some heading (as if there is only one such type).  Formally, this is rather incorrect.  Many tuple types have the same heading, but the one that has all possible tuples, is the most useful, in practice.

The fact that relations are themselves also tuple types, is the source of quite a bit of confusion. The "design dilemma", for example.  (That's the question of whether structures such as 'customer' and 'address' should be conveyed in their own type or not.)  It's not a dilemma at all.  Defining a Customer or Address class in an OO system constitutes defining a type.  The tuple type that corresponds to it is a type too.  Whether or not to give the type a name, is another question, and one that will mostly be moot at that.

On to relations.  If relations are themselves values, then what is their type ?  Well, a type is the set of all its contained values.  Hence, a relation type is a set of relations.  The construction of such a set of relations can be done using the mathematical concept of powersets.  A powerset is the set of all possible subsets of a given set.  So if we :
- start with a tuple type such as the one in our running example,
- enumerate all the possible subsets of that tuple type (that's equivalent to enumerating all the possible relations with that heading)
- and collect all those subsets in a new set,
then this new set is our relation type.

This relation type too is characterized by its heading (and its heading alone).  As with tuple types, this relation type is not the only relation type of this heading, though.  Any subset of the tuple type (e.g. all the tuples that have I>=1, thus ruling out negative numbers), when subjected to the same procedure, will in turn give rise to some relation type (relations with the specified heading and where all its tuples satisfy the predicate that (e.g.) I>=1).  Likewise, subsetting the relation type using some predicate (for example, retaining only "the relations that have at least three tuples") gives rise to some other new relation type.

Typically, however, relational systems do not exploit this property of relation and tuple types.  Instead they give the user the possibility to specify predicates that constrain which relations and tuples can validly appear in which places.  But a system that offered named tuple/relation types, with a constraining predicate, would fundamentally (mathematically) not really be different (in what it allows the user to achieve).

Friday, August 24, 2012

"A difference that doesn't matter"

This question was touched on lightly in an aside of a previous installment, leaving the question mostly unanswered.  The previous post mentioned this to illustrate the concept of a relation as a set :

 +------------------+-------------+--------------
I:INT X C:CHAR = {(I:1,C:'A') , (I:1,C:'B') , ... }
         +--------------+-------------+----------

And then it went on to conclude that for any of those individual tuples, e.g.  (I:1,C:'A')  ,

"We can also think of a (single) tuple as itself being a set, namely a set of ordered pairs in which the first thing is an attribute name and the second thing is "some value drawn from some domain".

And then a sidenote was made observing that other sources ("Introduction to Database Systems") "say that a tuple is a set of ordered triplets", and it was added that "The difference between the two approaches is not [so important]".

A little post to expand on that "difference" and to justify the claim that indeed this difference "doesn't matter".

Indeed, "Introduction to Database Systems" speaks of "the triple <Ai,Ti,vi> being a component of [some tuple]".  We can recognize the Ai and vi parts, that's the attribute name part and the value part, respectively, and the "additional" Ti part is the name of the corresponding domain for Ai.

Thus, the "difference" is essentially one between

 +------------------+----------------------+--------------
I:INT X C:CHAR = {(I:INT:1,C:CHAR:'A') , (I:INT:1,C:CHAR:'B') , }
         +------------------+----------------------+------

and

 +------------------+-------------+--------------
I:INT X C:CHAR = {(I:1,C:'A') , (I:1,C:'B') , ... }
         +--------------+-------------+----------

Is that "difference" of great significance ?  Not really.  In both "alternatives", the LHS of the equation is a statement of the heading that the resulting tuples conform to.  In both alternatives, there is a "mechanical" way to compute the RHS, given the LHS (and given the precise definition of the domains that are used in that LHS, of course).  That "mechanical" way consists of :
  • process all members of the "first" domain
  • for each member of the domain, process all members of the "second" domain
  • for each member of the second domain, process all members of the "third" domain
  • ...
  • for each member of the "next-to-last" domain, process all members of the "last" domain
  • for each member of the last domain, spell out the tuple consisting of those "current" domain members.
It should be obvious that the only difference between the two is in the details of the "spell out" part.  The first approach includes "spell out the domain name", the second example doesn't.

The "mechanical way" just described is, in a sense, the way to go from the LHS of the equations to the RHS.  One could also, somewhat philosophically, contemplate things that could happen if one ever wanted to "go from the RHS of those equations to the LHS", so to speak.  "Derive the heading from an enumerated cartesian product", so to speak.  In that case, there seems to be a more important difference.  The second example simply doesn't allow us to do that ... at first sight.  Indeed, no domain names are mentioned in the RHS of the second example.  So how do we obtain them ?  Rather simply : generate them.  Name them "1", "2", "3", ...  Those names don't have to be meaningful when dealing with questions that were only philosophical to begin with !

Anyway, it should be clear that both approaches are able to "cover the same ground", and that therefore whatever difference might be perceived between them is indeed only perception, superficial, and is indeed a difference that doesn't matter.

Friday, August 17, 2012

"Relations of nothing at all"

In a previous installment, it was explained how relations, in the sense of the Relational Model of Data, are a generalization of the binary relations that are typically studied in mathematics.  Obviously, that "generalization" implies that such relations consist of "pairs" that have more than two values (drawn from the domains that were used to form the cartesian product), but the possibility was also alluded at to have "pairs" with only one value for its members, and even the possibility of such "pairs" with zero values for its members.

How does that make sense ?

First, let's revisit the "trick" that the Relational Model applied in "replacing" the concept of "ordinal" pairs with that of "unordered" pairs, "decomposing" that trick and its consequences step-by-step.

Start with the cartesian product of domains INT and CHAR :

 +-------------+---------+---------------+--------
INT X CHAR = {(1,'A') , (1,'B') , ... , (2,'A') , ...}
        +---------+---------+---------------+-----

What those lines seek to express is that we "know" that the numbers in those pairs derive from domain INT, precisely because they are the first ones in the pairs, and likewise for the quoted characters.

(Aside : computer languages that support 'tuples' natively typically use this 'ordered' version.  Haskell is a case in point.  There is a "first" operator to "retrieve" the "first" value from a tuple.  I digress.)

But for reasons of practicality, we do not want "addressability" (of the values within the tuples) by ordinal position (well at least not in settings where we are dealing with "large shared databases"), we want addressibility by attribute name.  The way to do this is by prepending attribute names to each and every thingy in that equation :

 +------------------+-------------+--------------
I:INT X C:CHAR = {(I:1,C:'A') , (I:1,C:'B') , ... }
         +--------------+-------------+----------

Aside : The equation as given states the equality between (some kind of) "predicative" way of defining a set (left side of the equation) and the "enumerative" way of defining a set (right side of the equation).  An "intensional" versus an "extensional" way of defining a type if you will.  But pls don't proliferate that latter terminology as it may be grotesquely off-base with more common usage of those terms.  Anyways.  Going in detail on that would be digressing from my main point here.  Maybe something for another installment.  End-of-aside.

Do we now still need those "pairs" (n-tuples) to be ordered ?  Well obviously, no we don't.  As long as we "know of the association" of I to domain INT and of C to domain CHAR, there is no longer any meaningful difference between (writing down that first tuple as)   (I:1,C:'A')   and (writing down that first tuple as)   (C:'A',I:1).


As a consequence, under this notation, we can also think of a (single) tuple as itself being a set, namely a set of these things that are separated by the comma's in each tuple of the enumeration.  And what exactly are those "things that are separated by comma's" ?  Eurhm, well, they are ordered pairs in which the first thing is an attribute name and the second thing is "some value drawn from some domain".

Another aside : "Introduction to Database Systems" says that a tuple is a set of ordered triplets.  The difference between the two approaches is not germane to the main point being made in this post (which is tuples and relations of nothing at all).  Suffice it to say here that the difference plays on ( / is a consequence of ) that presumption that was spelled out "As long as we "know of the association" of I to domain INT and of C to domain CHAR".  Maybe something for another installment.  End-of-another-aside.

Okay let's see what happens if we explicitly re-cast that tuple as a set of ordered pairs.
That gives us   { (I,1) , (C,'A') }.   Braces in bold for emphasis.
It should be clear that if we take a cartesian product of n domains, we get tuples that are themselves a set of cardinality n.  And since set theory is not limited to cardinalities >=2, this implies that, at least theoretically, we could also consider tuples of cardinality one and tuples of cardinality zero.

(Side remark on terminology : the number of attributes in a tuple is more commonly referred to as its degree.  I use the term "cardinality" here because that term is more closely related to set theory, and I am stressing the concept of tuples-as-sets here.  It should be clear that my "cardinality" of a tuple and the literature's more common "degree" of a tuple are the very same thing.)

We'll look briefly at tuples of cardinality one, because there is little unintuitive about them, and they will show us how tuples (and relations) of nothing at all, indeed make sense, and how they even are useful.  A tuple of cardinality one could be something like   TUPLE{ (I,1) }.   They are useful whenever the information that we want to store or retrieve, is the logical counterpart of a unary predicate, i.e. a predicate in which there is exactly one "fill-in-the-gaps" place.  For example, "The average temperature tomorrow will be §I§ degrees centigrade.".  Or "the highest customer number assigned is currently §I§".  Or "A §make of car§ has passed through our street today.".  (This latter one merely to illustrate that one must beware of confusing unary predicates with "predicates of which only one single instantiation can be true.  The talk is of unary predicates.)

Okay.  One step further down the line of decreasing tuple cardinalities (and we're finally where the title suggested we'd end up).  A tuple of cardinality zero, is, then, "a set of attribute values that has zero members".  Iow, it is the empty set of attribute values.  Iow, it is the empty set.   TUPLE{ }, in our usual notation.

How many such tuples are there ?  That's pretty obvious : exactly as many as there are "empty sets" in mathematics ... exactly one, thus.  Because the zero-tuple is unique, we can give it a name.  TUPLE_DEE in what follows.  Now where can TUPLE_DEE be useful in data management ?  That should by now be obvious too : it will be useful in any place where the information we want to store or retrieve, is logically defined by a nilary predicate.  I.e. whenever we deal with information, the defining predicate of which has no fill-in-the-gaps spots at all.  These predicates are sometimes labeled "degenerate predicates", and actually they correspond to propositions.  The following examples are drawn from "Databases, Types and the Relational Model", appendix E : "The door is open", or "The alarm is set".  No §§ marks, no fill-in-the-gaps.

Suppose you'd have to design a database to record the current state of affairs for those two predicates.  In SQL.  Would you create a "type" that can represent open/closed ?  One that can represent set/not set ?  What would you be doing to prevent your tables from containing two distinct rows, one saying that the door is "open" and the other row saying that the door is "closed" ?  Or would you design a boolean attribute "true" for open and "false" for closed ?  Yet again, how would you interpret such a table if it is empty ?  How would you enforce the rule that there must always be exactly one row in your table ?  All of that involves much more complication than is needed or warranted.

All you really need for such a database, is a relvar (/table) with no attributes (columns) at all.  If I want to record the information that "the door is closed", then I just ensure the table is empty.  How does this work ?  Well, any tuple in a relvar represents a true instantiation of the relvar's predicate.  If that predicate is a niladic, "degenerate" one, then the only instantiation possible is, the predicate itself (which already is a proposition by and of itself).  If there are no tuples at all in such a relvar, then this means that there are no true instantiations (/no true instances) of the relvar's proposition, meaning the relvar's proposition is FALSE.  If there is indeed a tuple in such a relvar, then that means that there does exist a true instantiation of the relvar's predicate, and since the only possible instantiation of that predicate is the predicate (proposition) itself, it means that the relvar's proposition is true.

Observe that there are thus two distinct possible values that such a "niladic" relvar can take on : one possible value in which no tuple is present at all (that's just the empty relation), and a value in which the empty tuple is present.  The difference between these two is a bit akin to the difference (in mathematics) between   {} and {{}}.  These values (relation values) are often assigned a name too, most often "TABLE_DUM" and "TABLE_DEE", other times more briefly "DUM" and "DEE".

I coloured the "outer" braces red to illustrate that these are the braces "associated with" a relvar and its corresponding predicate (proposition in our niladic case) and the "inner" ones green to illustrate that these correspond to a tuple that makes an instantiation of a predicate (proposition in our niladic case) true.

When querying a database, it is often claimed that DUM and DEE represent "false and true, respectively", or "no and yes, respectively".  That is a little bit sloppy.  Here's why :

If a database relvar's predicate is "The door is open", and we query that relvar, then we get back either DUM or DEE.  If it is DEE, then TUPLE_DEE appears in it, but the 'meaning' that TUPLE_DEE carries in this case is "The door is open".  It is only because of human interpretation that we "know" that this means a "yes" answer to the question "is the door open".  If we ask a question "is at least one student enrolled on any course", then we could inquire an ENROLMENT relvar and project away all of its attributes.  Once again, the result we get is either DUM or DEE.  If it is DEE, then TUPLE_DEE within it carries the meaning of the projection, which is "there exists some student and there exists some course such that that student is enrolled on that course".  It is only because of human interpretation that we know we can answer the question asked with a firm "yes" ...

Tuesday, August 14, 2012

"What relations 'mean' " ...

In a previous post, it was established what relations really are (mere mathematical things, i.e. objects that play a role in some mathematical theory).  And the relational model of data uses exactly those things as a building brick for our databases.  And those databases convey meaningful information for their users.  Databases can contain information such as "An order for five screwdrivers was placed on 2012-08-01 13:45:56 by a person named John Doe for an order price of 7 local currency units, and this order was delivered on 2012-08-14.'.  That's certainly a very "meaningful" statement.  It leads many people to believe that relations must have some kind of meaning.  Alas, they are mistaken ...


Lets consider a relation that consists of the 2-tuple (DAY1:Saturday, DAY2:Sunday).   In tabular form, it could be depicted as
DAY1 DAY2
Saturday Sunday
and that's about everything that "characterizes" this relation.

But by and of itself, does this "mean" anything ?  Well no, it doesn't.  Claiming the opposite would be similar to claiming that "the number one 'means something', by and of itself".  No it doesn't.

Relations (and the tuples they consist of) do not have any meaning of themselves.  If the opposite were true, then any reader would be in the possibility of concluding from the foregoing table that some firm statement is true, say, for example, "Saturday is the week-end day that comes before Sunday, which is also considered a week-end day.".  It would also be true that all readers would come to the very same conclusion.  And there would not be any reader who would come to the conclusion that this relations means "On Saturday, He created man, and on Sunday, He took a break to admire His own works thus far." ...

None of that is the case, of course.  If relations carry any meaning, then it is because they appear in a certain given context.  Note the choice of the word 'carry', as distinct from 'have'.  It's an important distinction.  Relations and the tuples they contain are merely carriers of "meaning", and the same relation and/or tuple might carry very different meanings in different contexts.

(For more stuff on why it is a good thing that "relations don't mean a thing", see, e.g., here.)

When it comes to context, two distinct cases apply which correspond to whether a user is updating the database or whether he is querying (inquiring) it.

In the case of updating, "what a relation means" (and/or "what a tuple means") is determined by what database relvar the update is targeting.  And in particular by the external predicate that has been associated with that relvar.

If that predicate happens to be (*) "§DAY1§ is a week-end day that comes immediately before §DAY2§, which is itself also a week-end day.", then a user inserting the 2-tuple (DAY1:Saturday, DAY2:Sunday) in that relvar is in effect making the assertion that "Saturday is a week-end day that comes immediately before Sunday, which is also a week-end day.".

(*) The things enclosed in § marks are obviously intended as placeholders for some value-to-be-filled-in.  Which value that is, is, obviously, an attribute from a tuple that [in this case of updating a relvar] is being inserted into the relvar.  This process of filling in "concrete" attribute values in the places where such placeholders appear in a predicate, is commonly called " instantiating the predicate".  Instantiating a predicate (such that all placeholders are effectively replaced) yields a proposition, and inserting a tuple means asserting that that proposition is a true one.

If that predicate happens to be "On §DAY1§, He created man, and on §DAY2§, He took a break to admire His own works thus far.", then a user inserting the 2-tuple (DAY1:Saturday, DAY2:Sunday) in that relvar is in effect making the assertion that "On Saturday, He created man, and on Sunday, He took a break to admire His own works thus far. ".

Observe how the inserted tuple itself is the very same in the two cases, but how the "meaning" that the tuple carries in either case is entirely different.

Back to (a relvar with) the predicate "§DAY1§ is a week-end day that comes immediately before §DAY2§, which is itself also a week-end day.".  Now suppose some user wants to record the assertion that "Sunday is a week-end day that comes immediately before Monday.".  Would it be correct of this user to insert a tuple (DAY1:Sunday, DAY2:Monday) in that relvar ?  Obviously no, it wouldn't, as that would mean that this user would also be asserting the part that says that "Monday is itself also a week-end day" !!!

Documenting the external predicate of each relvar in a database is about the most important aspect there is to database design.  And of course as always, it is important to be precise !  Even if differences or variations seem extremely subtle, they can ultimately still give rise to major misunderstandings and mistakes !

On to the meaning of relations/tuples when inquiring a database.  When that tuple (DAY1:Saturday, DAY2:Sunday) was inserted into the relvar, that was taken to be an assertion to the effect that the corresponding proposition was a true one.  That 'meaning' is of course never altered merely by the tuple "staying where it is (in the relvar)".  Thus, if we inquire this relvar and get back that same tuple in the result, that still tells the inquiring user that "Saturday is a week-end day that comes immediately before Sunday, which is also a week-end day.".

Note once again that if we got back the very same tuple from inquiring a totally different relvar (one with a totally different external predicate), then this very same tuple would mean something entirely different.  Nothing changes to the fact that relations and the tuples within them are mere carriers of meaning.

But when we inquire a database, we typically use constructs that are much more complex than just "naming a relvar" (and getting back their full contents).  Those constructs are the possible expressions of the relational algebra.  What matters about that in the context of 'meaning', is that each possible expression of the relational algebra, also has its very own "external predicate" that "defines the meaning" carried by the tuples appearing in the result of the query.

For example, if we apply a RESTRICTion to some relvar, then that expression has for its external predicate the external predicate of that relvar, ANDed together (logically conjuncted) with a rule that expresses/defines the restriction condition applied.  For example, applying to our week-end days relvar a restriction condition 'DAY1 = Sunday', gives us the external predicate §DAY1§ is a week-end day that comes immediately before §DAY2§, which is itself also a week-end day, AND [it is the case that] §DAY1§ is Sunday.".  The empty result we'd be getting back from that query, is a manifestation of the fact that there simply are no true instantiations of this predicate.

Note that the querying too indicates why it is so extremely important to document the external predicates of our database relvars : without that, there just is no formal way for us to tell what our query results actually mean (and without such a formal way to tell that, all that's left for us to do is to make mere assumptions - but as the saying goes, assumption is the mother of all screw-ups).

Monday, August 13, 2012

"What is a relational database"

Various sources (see, for example, "An Introduction to Relational Theory") define a "database" as an
  • organized
  • machine-readable
  • collection of data.
Many alternative formulations exist with various degrees of difference in style or covered detail, but the essence is typically always the same.

From such definitions, we can derive (proceeding in random order) :
  1. A database is a collection of data.   Note in particular that a "collection of data" is nowhere near the same thing as "a software system that can be used to manage data" !!!  A mere collection of data is something notoriously passive, a collection of data does not ever actively do anything, but a software system is, contrariwise, a component that can indeed be very active.  What I'm getting at here is of course the distinction between the terms "database" and "DBMS".  A database is a collection of data, a DBMS is a software system that is used to manage that collection of data.  Not respecting that distinction can irritate some people quite heavily, so anyone reading this can now, once and for all, solemnly swear that they "shall never ever again use the word 'database' when what they actually mean is 'DBMS' ".  If the batteries of your camera have run down, then you don't say that it's the batteries of your photograph that need recharging either, do you ?
    Should you think this is unimportant or needless nitpicking, then think again.  It's important to be precise.  Why is it important to be precise ?  Because we deal with machines that do exactly as they're told.  And we programmers and software developers in general are the ones who are supposed to formulate the instructions that those machines will be following.  To be skilled at that, it is an absolute and inevitable requirement that the person doing that is, indeed, capable of being precise.  Lethally precise.  The more capable we are of achieving that "lethal degree of preciseness", the more skilled we will be at writing software that is actually correct.
  2. Back to what a database is.  It is an organized collection of data.  Meaning there must be some kind of structure to the database.  If there is no structure in a database, then what it contains is not data, but just garbage, and nothing or no one will ever be able to make any sense out of what it contains.  The term "unstructured data", "unstructured databases", "schema-less databases", "schema-less data", "schema-less data model", and what have you of that ilk, are all contradictions of terms, and nothing more than utter nonsense.  There always is some kind of structure.  It may be a very high-level kind of structure, it may be that it doesn't really express anything that comes comparatively close to the kind of facts that the end-user is actually dealing with in his world, it may rise skyhigh in its level of "abstraction", in some sense, but there always is at least some kind of structure, some kind of organization.
  3. And finally, it is machine-readable.  Some alternative formulations are about a database being an "electronic registration" of some sort, the essential point is the same.  (And comparatively unimportant, I'm tempted to add.  The sole purpose is to rule out the paper cards in a filing cabinet of elder times, as being a kind of database that should be taken into consideration when discussing database technology in computerized environments.)
That established, we can state what it means to be a relational database :
  1. First and foremost, it means of course being a database, meaning it satisfies the three criteria mentioned earlier,
  2. And two, it is a collection of data that is organized according to the relational model of data, meaning that it is an organized collection of relations.  More precisely, it is an organized collection of relation variables, variables that take on relations as values.  The "organization" takes on the form of each such relation variable (relvar for short) being assigned a unique name, owing to which it is identifiable in the database.
    Also to be noted is that each relvar in the database is accompanied by an intended interpretation.  It is precisely this "intended interpretation" that will allow us users to make any sense of what the database contains.  This intended interpretation is of no concern to the machinery (the DBMS) that manages the data, it is all the more important for us, users, who are "external" to that machinery.  That is why this intended interpretation is often called the "external predicate" associated with the relvar.
(And consequentially, at this point it can also be stated what it means to be a relational DBMS, namely in the first place to be a DBMS, i.e. a software system that can be used to manage data and/or databases, and in the second place one that has the purpose of managing a relational database in particular.)