Atlanta Custom Software Development 

 
   Search        Code/Page
 

User Login
Email

Password

 

Forgot the Password?
Services
» Web Development
» Maintenance
» Data Integration/BI
» Information Management
Programming
  Database
Automation
OS/Networking
Graphics
Links
Tools
» Regular Expr Tester
» Free Tools

Null values in WHERE clauses

Total Hit ( 3229)

Rate this article:     Poor     Excellent 

 Submit Your Question/Comment about this article

Rating


 


A SELECT query returns all the rows for which the WHERE clause returns True. However, many developer - especially those accustomed to other programming languages, such as VB - get confused on this point, and assume that the query returns the rows for which the WHERE clause returns any non-False value, and this is a major source for bugs.

To explain the reason, consider that the SQL language uses a three-value logic: True, False, and Null. Any Null value in an expression makes the entire expression Null (with some exception, noted below). For example, your common sense would suggest that the following SELECT returns all the rows in the table:

Click here to copy the following block
SELECT * FROM Orders WHERE (total < 1000 Or total >= 1000)

What happens, however, is that the SELECT won't include records for which the Total field is Null, because this value makes the entire WHERE expression evaluate to Null. Here's another example:

Click here to copy the following block
SELECT * FROM Orders WHERE total = 0

The above query returns all orders for which Total is zero, but not those for which Total is Null. If you want to include the latter ones, you must explicitly look for Null values:

Click here to copy the following block
SELECT * FROM Orders WHERE total = 0 OR total IS NULL

ISNULL is T-SQL a function that is often useful to get rid of Null values. Simply stated, it always returns its first argument, except when it is Null (in which case it returns the second argument). See how you can rewrite the above query to avoid Null values:

Click here to copy the following block
-- convert Null values to zero before comparing them
SELECT * FROM Orders WHERE ISNULL(total, 0) = 0

Moreover, T-SQL extends the ANSI 92 standard and supports Null also in IN clauses, so you can rewrite the above query as follows:

Click here to copy the following block
SELECT * FROM Orders WHERE total IN (0, NULL)



Submitted By : Nayan Patel  (Member Since : 5/26/2004 12:23:06 PM)

Job Description : He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting.
View all (893) submissions by this author  (Birth Date : 7/14/1981 )


Home   |  Comment   |  Contact Us   |  Privacy Policy   |  Terms & Conditions   |  BlogsZappySys

© 2008 BinaryWorld LLC. All rights reserved.