Knowing the DifferenceHow well do you know your SQL and set theory?by Joe Celko I have not done a theoretical database column in a long time, so let me share this problem from Steve Kass. It's a good measure of how well you know your SQL and set theory. The setup is simple: Create a 1x1 table, and then execute these two queries:
(Key this into your query tool and see what happens before you read any further.) Technically, the Why COUNT(*) CountsOnly By definition, One line of reasoning for this result is that you have a A second line of reasoning is that you can parse the
which returns an empty set, and
which returns zero. If SQL were a procedural language, a good compiler would prune out the dead code at compile time, and these results would always occur. But I asked people to test these queries on various SQL products, and the consensus was to return 99 and 0 for Q1 and Q2, respectively. These results mean that I can get anything I want out of an empty set. All I have to do is put in
a dummy Wanted: Precise SyntaxThe line of reasoning I favor until SQL establishes firm rules is that you have an ambiguous
syntax and you just blow up. Perhaps what SQL should have is two very distinct key words, such as
This situation isn't the result of NULLs, as in some of the other unexpected logical results in
SQL. With the CASE expression, these two queries jump between the "set as a whole" level
(cardinality) and the "values within the set" level ( Gregor Cantor invented set theory to explain infinite sets by handling them as completed units of work, instead of a sequence of elements that approach infinity. At last! We're at the foundations of set theory, and I can finally use my Masters degree in Math. Suddenly, there's a huge difference between set functions and aggregate functions! Joe Celko [71062.1056@compuserve.com] is an independent consultant in Austin, Texas and the author of Joe Celko's SQL for Smarties: Advanced SQL Programming (Morgan Kaufmann Publishers, 1999).
|
Most Popular This Week
IE Weekly Newsletter
Subscribe to the newsletter
|
|
|




