Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert NaN values to NULL, or NaN to 0 in SQL

Tags:

sql-server

I have values in registries that contain NaN values (they come from MATLAB). How would I convert them to NULL, or preferably, 0, in SQL?

like image 953
edgarmtze Avatar asked Mar 08 '11 20:03

edgarmtze


3 Answers

If you have imported them into a SQL Server table

update tbl
set theColumn = NULL
WHERE theColumn = 'NaN'

This converts the column values to NULL if they are the string 'NaN' For the column to contain 'NaN', it must be varchar, so if you prefer 0, that would be the string '0'

update tbl
set theColumn = '0'
WHERE theColumn = 'NaN'

In a select statement, you can use either of

SELECT NULLIF(theColumn, 'NaN') as NullifiedTheColumn, ...
SELECT CASE theColumn when 'NaN' then '0' else theColumn end as ZeroedTheColumn, ...
like image 81
RichardTheKiwi Avatar answered Oct 23 '22 02:10

RichardTheKiwi


SELECT NULLIF('NaN', ColumnName)

example

DECLARE @d VARCHAR(3) ='NaN'

SELECT NULLIF('NaN', @d)

for 0

DECLARE @d VARCHAR(7) ='NaN'

SELECT CASE WHEN @d = 'NaN' THEN '0' ELSE @d END
like image 36
SQLMenace Avatar answered Oct 23 '22 02:10

SQLMenace


How about CASE WHEN IsNumeric(column)=0 THEN 0 ELSE column?

like image 39
Mark Sowul Avatar answered Oct 23 '22 02:10

Mark Sowul