Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blank values in Date column returning as 1900/01/01 on running SELECT statement

The column [PAYOFF DATE] has some blank values and some values in mm/dd/yy format.

I have to replace '/' with '-' and return the date as yyyy-mm-dd. The below query is doing it. The problem is that for all blank values, I am getting results as 1900-01-01.

Is it possible to replace 1900-01-01 with null and return other valid date values as is in yyyy-mm-dd format?

I am using SQL Server.

SELECT
cast(replace(a.[PAYOFF DATE],'/','-') as date) 
FROM MTG a
like image 730
Reeya Oberoi Avatar asked Apr 09 '14 20:04

Reeya Oberoi


People also ask

How do I create a blank date field in SQL?

How to blank out a date field using SQL? "NULL" can be specified as a value in the Date field to get an empty/blank by using INSERT statement.

How do you handle NULL values in a date column?

If you have a STRING column where its format is like TIMESTAMP , you can simply apply it. Then, DATE will extract just the date and it takes care of the NULL values. Show activity on this post. You can try substr[1] from 1 to 10 to get the date, and then you can use the safe.


Video Answer


1 Answers

You dont need to do the string manipulation as you have shown in your question. If you have dates stored in mm/dd/yyyy format just cast it as DATE.

SELECT cast(a.[PAYOFF DATE] AS DATE) 
FROM MTG a 

For 1900-01-01 values, since you are converting from a string data type to Date, String datatype can have Empty strings but Date datatype cannot have empty date values, It can have either a date value or NULL value.

Therefore you need to convert the empty string to nulls before you convert it to date. 1900-01-01 is just a default value sql server puts in for you because Date datatype cannot have an empty value.

You can avoid having this sql server default value by doing something like this.

SELECT cast(NULLIF(a.[PAYOFF DATE],'') AS DATE) 
FROM MTG a 
like image 196
M.Ali Avatar answered Oct 01 '22 21:10

M.Ali