SQL Server query returns a date when I select WHERE column = ''

SQL Server query returns a date when I select WHERE column = ''
typescript
Ethan Jackson

I am running a query to check if any records contain a blank DateOfBirth, but data returned is not what I expected.

I ran the following:

SELECT TOP 5 DateOfBirth, * FROM [MyDataBase].[dbo].[CustomerRecord] WHERE DateOfBirth = ''

When I run this, my results show rows like this:

IDDateOfBirthSurname
11900-01-01Jones
21900-01-01Deacon
61900-01-01Bacon
101900-01-01James
121900-01-01Burns

The Information_SCHEMA.Columns shows that the column is defined as date and the COLUMN_DEFAULT is NULL and IS_NULLABLE is set to YES.

So why does it not return rows that are blank?

Answer

You say that DateOfBirth is a DATE. So why are you comparing it to a string at all? You shouldn't. Compare dates with dates, strings with strings etc. Don't mix the types. A date is never equal to an empty string (''), because these are two different things. The results you are getting are hence somewhat arbitrary. Obviously, SQL Server takes the liberty to interprete the empty string as equal to the date 1900-01-01, which it shouldn't in my opinion.

A "blank" DateOfBirth would be a date that is NULL. Hence:

SELECT TOP 5 DateOfBirth, * FROM [MyDataBase].[dbo].[CustomerRecord] WHERE DateOfBirth IS NULL;

Related Articles