Saturday, July 30, 2011

NULL or IS NULL or IS NOT NULL


Null is a special marker used in Structured Query Language (SQL) to indicate that a data value does not exist in the database. Introduced by the creator of the relational database model, E. F. Codd, SQL Null serves to fulfill the requirement that all true relational database management systems (RDBMS) support a representation of "missing information and inapplicable information".

When you perform operations on null in SQL Server, by default the result is NULL. NULL values can not really be evaluated.

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)

Joins

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 LEFT OUTER JOIN operator. The following simple example uses two tables to demonstrate Null placeholder production in a left outer join.
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.

Employee
ID
LastName
FirstName
1
Johnson
Joe
2
Lewis
Larry
3
Thompson
Thomas
4
Patterson
Patricia
PhoneNumber
ID
Number
1
555-2323
3
555-9876
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 null able 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 COALESCE function or CASE expressions can be used to "simulate" Null equality in join criteria, and the IS NULL and IS NOT NULL predicates can be used in the join criteria as well.

Another Example:-


 Source:-
1.        http://en.wikipedia.org
2.        http://blogs.msdn.com

No comments: