Show 'Unknown' for Null Ids in SQL - sql

when the numeric field is Null how to show a string value? Tried the syntax below but getting an error
'Error converting data type varchar to numeric':
Syntax:
select
case
when bill_area_id IS null then 'Unknown'
else bill_area_id end from Table_name

Use coalesce to return first non-null value :
select coalesce(bill_area_id, 'Unknown') from Table_name
Note that compatible data types is required. I.e. you may have to do :
select coalesce(cast(bill_area_id as varchar(15)), 'Unknown') from Table_name

If you are using sql server, you can also use this :
select isnull(cast(bill_area_id as varchar(15)), 'Unknown') from Table_name

The error is because you are mixing varchar with numeric output in the same column. For SQL Server for example:
select
case
when bill_area_id IS null then 'Unknown'
else CAST(bill_area_id as varchar) end from Table_name
Ensures that the output is uniformly varchar since I am casting bill_area_id as varchar, or selecting 'Unknown' (also a varchar).
There are other answers here using COALESCE/isnull that are just as valid, since those functions provide an alternative to NULL values.

Related

Snowflake: Insert null value in a numeric type column

I have a case statement to rectify one business logic in snowflake:
INSERT INTO DB.table_b
SELECT
CASE
WHEN UPPER(emp) <> LOWER(emp) THEN NULL
WHEN emp IS NULL THEN nullif(emp, 'NULL')
ELSE emp
END AS emp_no
FROM
DB.table_a;
The 'table_a' content as below :
emp
-------
ABCD
NULL
''
23
It contains character string, null, empty and numbers. So, the requirement is to take only numbers and empty values from the case statement since the column emp_no in 'table_b' is numeric type. In source table if the column value is string then we have to insert NULL value. But as the 'table_b' column is of type 'numeric' the null value is not getting inserted and getting following error
Numeric value '' is not recognized
Using TRY_TO_NUMBER:
A special version of TO_DECIMAL , TO_NUMBER , TO_NUMERIC that performs the same operation (i.e. converts an input expression to a fixed-point number), but with error-handling support (i.e. if the conversion cannot be performed, it returns a NULL value instead of raising an error).
INSERT INTO DB.table_b
SELECT TRY_TO_NUMBER(emp) AS emp
FROM DB.table_a;
you can not use IS_INTEGER but for VARCHAR(16777216) it isn't supported
So a regular expression would be better
INSERT INTO DB.table_b
SELECT
CASE
WHEN regexp_like(emp,'^[0-9]+$') THEN emp
ELSE NULL
END AS emp_no
FROM
DB.table_a;
As Lukasz mentions you should use the TRY_TO_x functions (TRY_TO_NUMERIC, TRY_TO_DOUBLE) as these safely handle parsing the types, and return NULL if the parse fails. The extra note I will add is that both NUMBER/NUMERICs and DOUBLEs will parse 0.1234 but get different results, which you didn't mention as caring about, but I think is worth noting, so I am adding an extra answer to point the difference out.
The CTE is just to get the values into the SQL:
WITH data(emp) as (
select * from values
('ABCD'),
(NULL),
(''),
('0.123'),
('23')
)
SELECT emp
,try_to_numeric(emp) as emp_as_num
,try_to_double(emp) as emp_as_float
FROM data
EMP
EMP_AS_NUM
EMP_AS_FLOAT
'ABCD'
null
null
null
null
null
''
null
null
'0.123'
0
0.123
'23'
23
23
You can test for amp being string and set the string to NULL. Only numeric values will go into the second case statement.
SELECT
CASE
WHEN IS_VARCHAR(emp) then NULL else
case WHEN UPPER(emp) <> LOWER(emp) THEN NULL ELSE emp end
end AS emp_no

SQL case statement then convert to int

I have a field that I want to convert to int so I can to a count, however some of the field's values are 'null' so I'm getting an exception when it comes across these
Conversion failed when converting the nvarchar value '_____' to data type int.
I thought id be able to do something like the below but I get the same result.
CAST( CASE [value] WHEN 'is null' THEN 1 ELSE [value] END AS INT)
I want to change all null values in [value] to 1 and then change all [value] to int so I can calculate this field.
You should have no issue converting a NULL value to an int, so I assume the issue is a string 'NULL'.
SQL Server offers TRY_CONVERT(). I recommend that you use that;
select try_convert(int, [value])
In other databases, you can use a regular expression to validate the data.
it will be is null that is not string
CAST( (CASE WHEN [value] is null THEN 1 ELSE [value] END) AS INT)
but its better to use try_convert what actually #Gordon recommend
Since you aren't actually looking for the NULL--which is the absence of data. You have bad data, i.e. the actual text 'NULL' in a column.
I would actually recommend you updating all the values to NULL so you can avoid doing try casting data to fix your problem. That would be something like:
UPDATE yourtable
SET [value] = NULL
WHERE [value] = 'NULL'
Then I would also change the column to a true INT type to avoid this in the future. But that's a bit outside the scope of your question.
Of course, you can't always change the data types. If you can, then this will be a more permanent solution.

Convert 'NULL' to Date in SQL

I have a column in my table called startdate. It is in string format. Most of the fields are 'NULL'. I am copying this column to another table which data type is 'Date'.
How can I convert all the values from string to Date in SQL.
I have tried this code:
INSERT INTO Destination_Table [new_date]
SELECT CONVERT(DATE,[startdate],103)
FROM Source_Table
nullif([startdate],'NULL') returns [startdate] unless it equals to 'NULL' and then it returns NULL (a real NULL, not the string 'NULL')
INSERT INTO Destination_Table [new_date]
SELECT CONVERT(DATE,nullif([startdate],'NULL'),103)
from Source_Table
For learning purposes, here are some expressions with the same results:
nullif(x,y)
case when x=y then null else x end
case x when y then null else x end
It looks like you are using MSSQL. If you are using MSSQL 2012, the following code should work :
INSERT INTO Destination_Table [new_date]
SELECT IIF([startdate] = "NULL", null, CONVERT(DATE,[startdate],103))
FROM Source_Table
What this does, is use the IIF() method to check the value of [startdate] and if the value is the text "NULL", then return the actual null value which can be allowed in most fields unless you have null disabled on the Destination_Table.[new_date] field.
Since the Date field can only accept and store Date/Time/Date&Time/(actual null) information, the text "NULL" is not valid.
Following is the equivalent for MySQL
INSERT INTO Destination_Table [new_date]
SELECT IF([startdate] == 'NULL', null, CONVERT(DATE,[startdate],103))
FROM Source_Table
(although I am unsure MySQL allows a conversion code as a param to CONVERT() )

How to safely convert a varchar(255) to an int?

I was using a column in a case expression and it was working fine on server1. When I ran it on server2 it was failing because the column had the value 'false' in it.
The column is a varchar(255), but in my case expression I was using it as if it was an INT type. It worked fine but now it is failing because of the 'false' value in server2.
How can I safely convert to an INT, and if the conversion fails, default to 0.
Is this possible?
My query looks like:
UPDATE t1
set
c1 = ISNULL(
(
SELECT CASE c2
WHEN 123 then 'hello'
WHEN 234 then 'bye'
ELSE ''
END
)
, '')
FROM table1 as t1
There are quite a few ways to convert from numeric to varchar, but none of them are available to you (really, SQLServer2008 is disappointing because it's lacking just a few cool features that are nearly required).
In your case, the best way to do is it simply to convert your numeric expression to varchar like this :
UPDATE t1
set c1 = CASE c2
WHEN '123' then 'hello'
WHEN '234' then 'bye'
ELSE ''
END
FROM #t1 t1
It doesn't answer the question, but it solves your problem.
Use TRY_PARSE (SQL Server 2012+):
SELECT ISNULL(TRY_PARSE(column_name AS INT),0)
FROM your_table;
LiveDemo

Select a column if other column is null

I need to select a field called ProgramID from a table and if the ProgramID is NULL then I need to select the value in the InterimProgramID from the same table and alias it as ProgramID.
How can I make a conditional SELECT statement to do this?
You need the ISNULL function.
SELECT ISNULL(a, b)
b gets selected if a is null.
Also, you can use the WHEN/THEN select option, lookup in BOL. Essentially: its c switch/case block meets SQL.
select COALESCE ( ProgramID , InterimProgramID ) as 'ProgramID'
You can use either the ISNULL function or the COALESCE function. They both do pretty much the same thing, however ISNULL only takes two parameters and COALESCE takes multiple parameters (returning the first non-null it encounters). Both try the first param, then the second, (and COALESCE continues on)
DECLARE #IAMNULL VARCHAR
DECLARE #IAMNOTNULL VARCHAR
SET #IAMNOTNULL = 'NOT NULL'
SELECT ISNULL(#IAMNULL, #IAMNOTNULL)
--Output: 'NOT NULL'
DECLARE #IAMNULLALSO VARCHAR
SELECT COALESCE(#IAMNULL, #IAMNULLALSO, #IAMNOTNULL)
--Output: 'NOT NULL'
SELECT ProgramID
FROM a_table
WHERE ProgramID IS NOT NULL
UNION
SELECT InterimProgramID AS ProgramID
FROM a_table
WHERE ProgramID IS NULL;
Coalesce('zzz-' + ProgramID, InterimID) as programID will still ignore ProgramID even if you have a pretext value. It's a cool little function
There is also:
Select NVL(Column_A, Column_B) From 'schema'.'table_name'
The NVL( ) function is available in Oracle, and not in MySQL or SQL Server. This function is used to replace NULL value with another value. It is similar to the IFNULL Function in MySQL and the ISNULL Function in SQL Server.
https://www.1keydata.com/sql/sql-nvl.html
You can also use IFNULL function
select IFNULL(ProgramId,interimId) as ProgramId