SQL Tutorial - Null Values


Null value is an 'unknown' value in SQL Server. If a column has null value, It means that the data is either missing or unknown.

The Null Value


The 'Null" value is different from an empty value(' '). An empty value cannot be considered as a NULL. Since 'Null' is unknown, any operation with null value will also return a null value. Also Null is not equal to Null. Since the default option for a column is null, you have to explicitly state that a column is not null when creating a table. To Handle a null situation we use the following functions.
  • ISNull Function
  • Coalesce Function
INull function is covered in the next chapter and Coalesce is covered here.

The Create Table example with default null option


CREATE TABLE Employees
(
EmployeeID smallint NOT NULL,
EmployeeName nvarchar(50) NOT NULL,
DateOfBirth smalldatetime NOT NULL,
DesignationID smallint NULL,
DeptID smallint NULL,
PhoneNo nvarchar(12) NULL,
City nvarchar(50) NOT NULL,
Salary decimal(5, 2) NULL
)

In the above columns, it can be seen that DesignationID, PhoneNo and salary columns are optional columns. That means that they can contain null values. So when the query is run on the 'Employees' table, it returns the rows of records as shown below along with the null values that have not been entered.

The below query displays all the columns and data from the 'EMPLOYEES' table.

Select EmployeeID,EmployeeName,DateOfBirth,DesignationID,DeptID,PhoneNo
from Employees

EmployeeID EmployeeName DateOfBirth DesignationID DeptID PhoneNo
1 Richard Hughes 4/23/1945 12:00:00 AM 1 1 343-123-2002
2 Taryn Sinclair 3/22/1980 12:00:00 AM 2 2 232-344-8755
3 Ted Horowitz 3/31/1960 12:00:00 AM 3 4 435-657-9068
4 Jonathan Douglas 7/7/1971 12:00:00 AM 3 4 323-454-7656
5 Miranda Leigh 7/19/1983 12:00:00 AM 7 3 634-465-8046
6 Jana Rae 9/23/1976 12:00:00 AM 8 2 434-434-1254
7 Lita Rosanna 9/14/1982 12:00:00 AM 4 6 565-782-1223
8 Colin Flooks 12/29/1988 12:00:00 AM 4 2 954-652-2111
9 Anthony Frank 2/22/1988 12:00:00 AM 9 3 323-243-1249
10 Stephanie Lynn 7/30/1979 12:00:00 AM 8 2 543-765-4653
11 Jack Martin 8/25/1985 12:00:00 AM NULL NULL 443-324-6522