HistoryNull was introduced by E. F. Codd as a method of representing missing data in the relational model. Codd later reinforced his requirement that all RDBMS' support Null to indicate missing data in a two-part series published in ComputerWorld magazine.12 Codd also introduced a ternary (three-valued) logic, consisting of the truth values True, False, and Unknown, which is closely tied to the concept of Null. The Unknown truth value is generated whenever Null is compared with any data value, or with another Null. Codd indicated in his 1990 book The Relational Model for Database Management, Version 2 that the single Null mandated by the SQL standard was inadequate, and should be replaced by two separate Null-type markers to indicate the reason why data is missing. These two Null-type markers are commonly referred to as 'A-Values' and 'I-Values', representing 'Missing But Applicable' and 'Missing But Inapplicable', respectively.3 Codd's recommendation would have required SQL's logic system be expanded to accommodate a four-valued logic system. Because of this additional complexity, the idea of multiple Null-type values has not gained widespread acceptance. Three-valued logic (3VL)Since Null is not a member of any data domain, it is not considered a "value", but rather a marker (or placeholder) indicating the absence of value. Because of this, comparisons with Null can never result in either True or False, but always in a third logical result, Unknown.4 The logical result of the expression below, which compares the value 10 to Null, is Unknown: 10 = NULL -- Results in Unknown However, certain operations on Null can return values if the value of Null is not relevant to the outcome of the operation. Consider the following example in which the OR statement is evaluated in short-circuited form: TRUE OR NULL -- Results in True In this case, the fact that the value on the right of OR is unknowable is irrelevant, because the outcome of the OR operation would be True regardless of the value on the right. SQL implements three logical results, so SQL implementations must provide for a specialized three-valued logic (3VL). The rules governing SQL three-valued logic are shown in the tables below (p and q represent logical states)"5
Basic SQL comparison operators always return Unknown when comparing anything with Null, so the SQL standard provides for two special Null-specific comparison predicates. The Data typingNull is untyped in SQL, meaning that it is not designated as an integer, character, or any other specific data type.4 Because of this, it is sometimes mandatory (or desirable) to explicitly convert Nulls to a specific data type. For example, if overloaded functions are supported by the RDBMS, SQL might not be able to automatically resolve to the correct function without knowing the data types of all parameters, including those for which Null is passed. Data Manipulation LanguageSQL three-valued logic is encountered in Data Manipulation Language (DML) in comparison predicates of DML statements and queries. The SELECT * FROM t WHERE i = NULL; The example query above logically always returns zero rows because the comparison of the i column with Null always returns Unknown, even for those rows where i is Null. The Unknown result causes the CASE expressionsSQL SELECT CASE i WHEN NULL THEN 'Is Null' -- This will never be returned WHEN 0 THEN 'Is Zero' -- This will be returned when i = 0 WHEN 1 THEN 'Is One' -- This will be returned when i = 1 END FROM t; Because the expression A searched SELECT CASE WHEN i IS NULL THEN 'Null Result' -- This will be returned when i is NULL WHEN i = 0 THEN 'Zero' -- This will be returned when i = 0 WHEN i = 1 THEN 'One' -- This will be returned when i = 1 END FROM t; In the searched Check constraintsThe primary place in which SQL three-valued logic intersects with SQL Data Definition Language (DDL) is in the form of check constraints. A check constraint placed on a column operates under a slightly different set of rules than those for the DML CREATE TABLE t ( i INTEGER, CONSTRAINT ck_i CHECK ( i < 0 AND i = 0 AND i > 0 ) ); In order to constrain a column to reject Nulls, the CREATE TABLE t ( i INTEGER NOT NULL ); Procedural extensionsSQL/PSM (SQL Persistent Stored Modules) defines procedural extensions for SQL, such as the IF i = NULL THEN SELECT 'Result is True' ELSEIF NOT(i = NULL) THEN SELECT 'Result is False' ELSE SELECT 'Result is Unknown'; The Joins
Example SQL outer join query with Null placeholders in the result set. The Null markers are represented by the word
NULL in place of data in the results. Results are from Microsoft SQL Server, as shown in SQL Server Management Studio.SQL outer joins, including left outer joins, right outer joins, and full outer joins, automatically produce Nulls as placeholders for missing values in related tables. For left outer joins, for instance, Nulls are produced in place of rows missing from the table appearing on the right-hand side of the The first table (Employee) contains employee ID numbers and names, while the second table (PhoneNumber) contains related employee ID numbers and phone numbers, as shown below.
The following sample SQL query performs a left outer join on these two tables. SELECT e.ID, e.LastName, e.FirstName, pn.Number FROM Employee e LEFT OUTER JOIN PhoneNumber pn ON e.ID = pn.ID; The result set generated by this query demonstrates how SQL uses Null as a placeholder for values missing from the right-hand (PhoneNumber) table, as shown below.
Inner joins and cross joins, also available in standard SQL, do not generate Null placeholders for missing values in related tables. Care must be taken when using nullable columns in SQL join criteria. Because a Null is not equal to any other Null, Nulls in a column of one table will not join to Nulls in the related column of another table using the standard equality comparison operators. The SQL ( A = B ) OR ( A IS NULL AND B IS NULL ) Mathematical and string concatenationBecause Null is not a data value, but a marker for an unknown value, using mathematical operators on Null results in an unknown value, which is represented by Null.8 In the following example, multiplying 10 by Null results in Null: 10 * NULL -- Result is NULL This can lead to unanticipated results. For instance, when an attempt is made to divide Null by zero, platforms may return Null instead of throwing an expected "data exception - division by zero".8 Though this behavior is not defined by the ISO SQL standard many DBMS vendors treat this operation similarly. For instance, the Oracle, PostgreSQL, MySQL Server, and Microsoft SQL Server platforms all return a Null result for the following: NULL / 0 String concatenation operations, which are common in SQL, also result in Null when one of the operands is Null.9 The following example demonstrates the Null result returned by using Null with the SQL 'Fish ' || NULL || 'Chips' -- Result is NULL Aggregate functionsSQL defines aggregate functions to simplify server-side aggregate calculations on data. Almost all aggregate functions perform a Null-elimination step, so that Null values are not included in the final result of the calculation.10 This implicit Null elimination, however, can have an impact on aggregate function results. The following example table results in different results being returned for each column when the SQL
The SQL Grouping and sortingBecause SQL:2003 defines all Null markers as being unequal to one another, a special definition was required in order to group Nulls together when performing certain operations. SQL defines "any two values that are equal to one another, or any two Nulls", as "not distinct".11 This definition of not distinct allows SQL to group and sort Nulls when the Other SQL operations, clauses, and keywords use "not distinct" in their treatment of Nulls. These include the following:
The SQL standard does not explicitly define a default sort order for Nulls. Instead, on conforming systems, Nulls can be sorted before or after all data values by using the Effect of NULL on index operationSome SQL products do not index keys containing NULL values. For instance, the PostgreSQL documentation for a B-Tree index states that
In cases where the index enforces uniqueness, NULL values are excluded from the index and uniqueness is not enforced between NULL values. Again, quoting from the PostgreSQL documentation:
This is consistent with the SQL:2003-defined behavior of scalar Null comparisons. Another method of indexing Nulls involves handling them as not distinct in accordance with the SQL:2003-defined behavior. For example, Microsoft SQL Server documentation states the following:
Both of these indexing strategies are consistent with the SQL:2003-defined behavior of Nulls. Because indexing methodologies are not explicitly defined by the SQL:2003 standard, indexing strategies for Nulls are left entirely to the vendors to design and implement. Null-handling functionsSQL defines two functions to explicitly handle Nulls: COALESCEThe COALESCE(value1, value2, value3, ...)
CASE WHEN value1 IS NOT NULL THEN value1 WHEN value2 IS NOT NULL THEN value2 WHEN value3 IS NOT NULL THEN value3 ... END Some SQL DBMSs implement vendor-specific functions similar to NULLIFThe NULLIF(value1, value2) Thus,
CASE WHEN value1 = value2 THEN NULL ELSE value1 END
ControversyCommon mistakesMisunderstanding of how Null works is the cause of a great number of errors in SQL code, both in ISO standard SQL statements and in the specific SQL dialects supported by real-world database management systems. These mistakes are usually the result of confusion between Null and either 0 (zero) or an empty string (a string value with a length of zero, represented in SQL as For example, a SELECT * FROM sometable WHERE num <> 1; -- Rows where num is NULL will not be returned, -- contrary to many users' expectations. Similarly, Null values are often confused with empty strings. Consider the SELECT * FROM sometable WHERE LENGTH(string) < 20; -- Rows where string is NULL will not be returned. This is complicated by the fact that in some databases such as Oracle, the empty string is incorrectly considered to be NULL. CriticismsThe ISO SQL implementation of Null is the subject of criticism, debate and calls for change. In The Relational Model for Database Management: Version 2, Codd suggested that the SQL implementation of Null was flawed and should be replaced by two distinct Null-type markers. The markers he proposed were to stand for "Missing but Applicable" and "Missing but Inapplicable", known as A-values and I-values, respectively. Codd's recommendation, if accepted, would have required the implementation of a four-valued logic in SQL.3 Others have suggested adding additional Null-type markers to Codd's recommendation to indicate even more reasons that a data value might be "Missing", increasing the complexity of SQL's logic system. At various times, proposals have also been put forth to implement multiple user-defined Null markers in SQL. Because of the complexity of the Null-handling and logic systems required to support multiple Null markers, none of these proposals have gained widespread acceptance. Still other Relational Management (RM) experts, like the authors of The Third Manifesto, Chris Date and Hugh Darwen, have suggested that the SQL Null implementation is inherently flawed and should be eliminated altogether.16 These experts often point to inconsistencies and flaws in the implementation of SQL Null-handling (particularly in aggregate functions) as proof that the entire concept of Null is flawed and should be removed from the Relational Model.17 Others, like author Fabian Pascal, have stated a belief that "how the function calculation should treat missing values is not governed by the relational model." Closed world assumptionAnother point of conflict concerning Nulls is that they violate the closed world assumption model of relational databases by introducing an open world assumption into it.18 The Closed World Assumption, as it pertains to databases, states that "Everything stated by the database, either explicitly or implicitly, is true; everything else is false."19 This view assumes that the knowledge of the world stored within a database is complete. Nulls, however, operate under the Open World Assumption, in which some items stored in the database are considered unknown, making the databases's stored knowledge of the world incomplete. Relational Management experts see this as an inconsistency within SQL. Law of the Excluded MiddleSQL allows three logical choices, true, false, and unknown, which means that SQL necessarily ignores the law of the excluded middle. Put simply the Law of the Excluded Middle essentially states that when given any Boolean result, the opposite of the result can be obtained by applying the logical "not" operator. This does not apply to SQL nulls, however. Under the precepts of the law of the excluded middle, a Boolean expression like the following can be simplified: SELECT * FROM stuff WHERE ( x = 10 ) OR NOT ( x = 10 ); The law of the excluded middle allows for simplification of the WHERE clause predicate, which would result in a statement like the following: SELECT * FROM stuff; This will not work in SQL, since the x column could contain nulls which would result in some rows not being returned. To correctly simplify the first statement in SQL requires that we return all rows in which x is not null. SELECT * FROM stuff WHERE x IS NOT NULL; While ignoring the law of the excluded middle does introduce additional complexity to SQL logic, attempts to apply this rule to SQL's 3VL results in a false dichotomy. Boolean datatype inconsistencyThe ISO SQL:1999 standard introduced the Boolean datatype to SQL.20 The Boolean datatype, as defined by the standard, can hold the truth values TRUE, FALSE, and UNKNOWN. Null is defined in this one instance as equivalent to the truth value UNKNOWN. This "null equals UNKNOWN truth value" proposition introduces an inconsistency into SQL 3VL. One major problem is that it contradicts a basic property of nulls, the property of propagation. Nulls, by definition, propagate through all SQL expressions. The Boolean truth values do not have this property. Consider the following scenarios in SQL:1999, in which two Boolean truth values are combined into a compound predicate. According to the rules of SQL 3VL, and as shown in the 3VL truth table shown earlier in this article, the following statements hold:
However, because nulls propagate, treating null as UNKNOWN results in the following logical inconsistencies in SQL 3VL:
The SQL:1999 standard does not define how to deal with this inconsistency, and results could vary between implementations. Because of these inconsistencies and lack of support from vendors the SQL Boolean datatype did not gain widespread acceptance. Most SQL DBMS platforms now offer their own platform-specific recommendations for storing Boolean-type data. See also
References
Further reading
External links
| | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||