SQL CASE statement with NULL - mysql

I have the following query. According to http://dev.mysql.com/doc/refman/5.0/en/case.html, null=null is false, thus the first case row will never occur. What would be an alternative query to accomplish this?
SELECT CASE c1
WHEN NULL THEN CONCAT("Hi",name," Your value is NULL")
WHEN "v1" THEN CONCAT("Hello ",name," The value is ",
CASE c2
WHEN "v11" THEN "bla"
WHEN "v12" THEN "bla bla"
END
,")")
WHEN "v2" THEN CONCAT("Howdy there ",name," Yep, the value is ",
CASE c3
WHEN "v21" THEN "beebop"
WHEN "v22" THEN "bopbee"
END
,")")
END
AS myLabel
FROM mytable
WHERE bla="bla";

So use the where <condition> form of case:
SELECT CASE WHEN c1 is NULL THEN CONCAT('Hi', name, ' Your value is NULL')
WHEN c1 = 'v1'
THEN CONCAT('Hello ', name, ' The value is ',
(CASE WHEN c2 = 'v11' THEN 'bla'
WHEN c2 = 'v12' THEN 'bla bla'
END), ')'
)
WHEN c1 = 'v21
THEN CONCAT('Howdy there ', name, ' Yep, the value is ',
(CASE WHEN c3 = 'v21' THEN 'beebop'
WHEN c3 = 'v22' THEN 'bopbee'
END), ')'
)
END
FROM mytable
WHERE bla = 'bla';
Also, use single quotes for string (and date) constants. Don't use them for anything else, like quoting delimiters.

An alternative would be to use COALESCE to get a default value in case the field is NULL, and then use that default for comparison where you are comparing with NULL in your present your query, like so:
SELECT CASE COALESCE(c1,'')
WHEN '' THEN CONCAT("Hi",name," Your value is NULL")
Of course, '' may be a legitimate value on it's own, in which case you need to use another value as default. Owing to this, I would personally recommend Gordon's solution as the way to go.

Related

SQL delete unnecessary characters from a row and parse a table into a new table

I have created the below code:
with t as (select *,
case
when `2kids`= '1' then '2kids' else'' end as new_2kids,
case
when `3kids`= '1' then '3kids' else'' end as new_3kids,
case
when kids= '1' then 'kids' else'' end as kids
from test.family)
select concat_ws('/',new_2kids, new_3kids, new_kids) as 'nc_kids'
from t;
If I run this query my output will be:
nc_kids
2kids/new_3kids/
2kids//
/new_3kids/new_kids
2kids/new_3kids/new_kids
How can I remove all the unnecessary '/' which not followed by character.
For example:
nc_kids
2kids/new_3kids
2kids
new_3kids/new_kids
2kids/new_3kids/new_kids
concat_ws() ignore nulls, so you can just turn the empty strings to null values at concatenation time:
select concat_ws('/',
nullif(new_2kids, ''),
nullif(new_3kids, ''),
nullif(new_kids, '')
) as nc_kids
from t;
Better yet, fix the case expressions so they produce null values instead of empty stings in the first place:
with t as (
select f.*,
case when `2kids`= 1 then '2kids' end as new_2kids,
case when `3kids`= 1 then '3kids' end as new_3kids,
case when kids = 1 then 'kids' end as kids
from test.family f
)
select concat_ws('/',new_2kids, new_3kids, new_kids) as nc_kids
from t;

how to send "" instead of null in select * statement SQL

SELECT * FROM specifications
I want to send "" or "0" instead of null[if any column having null value],
can't use column-wise, more than 80 columns
As mentioned in the comments, the only way is to use COALESCE() OR ISNULL() as many times as the count (80) of your columns.
Just to make it easier, you can use the below query to generate that 80 statements for you.
SELECT CONCAT('ISNULL(',COLUMN_NAME ,',' ,
(CASE WHEN DATA_TYPE ='int' THEN '0'
WHEN DATA_TYPE ='varchar' THEN '' ELSE '' END) , ')' )
AS DERIVED_COLUMN
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'specifications'
CHECK SAMPLE DEMO HERE
Note : This is under the assumption that all your column are of int or varchar datatype. If you have other datatypes, modify the CASE accordingly.

Can Sybase CASE expressions have a default column name for their result?

I have a sybase query that is structured like this:
SELECT
case
when isnull(a,'') <> '' then a
else convert(varchar(20), b)
end
FROM table_name
WHERE b=123
It used to return the results of the 'case' in a column named 'converted'. It now returns the results of the 'case' in a column with an empty string name ''.
How could this be? Could there be some database configuration that defaults the results of a 'case' with no name?
(I've fixed the broken query by adding " as computed" after 'end' but now I'd like to know how it used to return as 'computed' before I added the fix?)
Is this what you want?
SELECT (case when isnull(a, '') <> '' then a
else convert(varchar(20), b)
end) as converted
-------------^
FROM table_name
WHERE b = 123;
By the way, you could write the select more succinctly as:
SELECT coalesce(nullif(a, ''), b) as converted

How to check if field is null or empty in MySQL?

I am trying to figure out how to check if a field is NULL or empty. I have this:
SELECT IFNULL(field1, 'empty') as field1 from tablename
I need to add an additional check field1 != "" something like:
SELECT IFNULL(field1, 'empty') OR field1 != "" as field1 from tablename
Any idea how to accomplish this?
Either use
SELECT IF(field1 IS NULL or field1 = '', 'empty', field1) as field1
from tablename
or
SELECT case when field1 IS NULL or field1 = ''
then 'empty'
else field1
end as field1
from tablename
If you only want to check for null and not for empty strings then you can also use ifnull() or coalesce(field1, 'empty'). But that is not suitable for empty strings.
Using nullif does the trick:
SELECT ifnull(nullif(field1,''),'empty') AS field1
FROM tablename;
How it works: nullif is returning NULL if field is an empty string, otherwise returns the field itself. This has both the cases covered (the case when field is NULL and the case when it's an empty string).
Alternatively you can also use CASE for the same:
SELECT CASE WHEN field1 IS NULL OR field1 = ''
THEN 'empty'
ELSE field1 END AS field1
FROM tablename.
You can use the IFNULL function inside the IF. This will be a little shorter, and there will be fewer repetitions of the field name.
SELECT IF(IFNULL(field1, '') = '', 'empty', field1) AS field1
FROM tablename
You can create a function to make this easy.
create function IFEMPTY(s text, defaultValue text)
returns text deterministic
return if(s is null or s = '', defaultValue, s);
Using:
SELECT IFEMPTY(field1, 'empty') as field1
from tablename
By trimming and comparing, we ensure we also take care of empty or tab or space character content in the field.
SELECT
CASE
WHEN LTRIM(RTRIM(col_1))='' or col_1 IS NULL THEN 'Not available'
ELSE col_1
END AS col_alias
FROM
my_table
SELECT * FROM (
SELECT 2 AS RTYPE,V.ID AS VTYPE, DATE_FORMAT(ENTDT, ''%d-%m-%Y'') AS ENTDT,V.NAME AS VOUCHERTYPE,VOUCHERNO,ROUND(IF((DR_CR)>0,(DR_CR),0),0) AS DR ,ROUND(IF((DR_CR)<0,(DR_CR)*-1,0),2) AS CR ,ROUND((dr_cr),2) AS BALAMT, IF(d.narr IS NULL OR d.narr='''',t.narration,d.narr) AS NARRATION
FROM trans_m AS t JOIN trans_dtl AS d ON(t.ID=d.TRANSID)
JOIN acc_head L ON(D.ACC_ID=L.ID)
JOIN VOUCHERTYPE_M AS V ON(T.VOUCHERTYPE=V.ID)
WHERE T.CMPID=',COMPANYID,' AND d.ACC_ID=',LEDGERID ,' AND t.entdt>=''',FROMDATE ,''' AND t.entdt<=''',TODATE ,''' ',VTYPE,'
ORDER BY CAST(ENTDT AS DATE)) AS ta
If you would like to check in PHP , then you should do something like :
$query_s =mysql_query("SELECT YOURROWNAME from `YOURTABLENAME` where name = $name");
$ertom=mysql_fetch_array($query_s);
if ('' !== $ertom['YOURROWNAME']) {
//do your action
echo "It was filled";
} else {
echo "it was empty!";
}

JPQL / SQL query: where like '%' include null values

I have a simple JPQL query. (But this applies also to an sql query..)
FROM DomainObj d where d.field1 like 'TEST%' and d.field2 like '%';
If the DB contains the following row:
1) field1 -> 'TEST'; field2 -> null
the query return nothing!
If the DB contains the following values:
2) filed1 -> 'TEST'; field2 -> ''
the query return the row!
How can I include also null values while searching for like '%' keeping the query as simple as possible (avoiding and/or clause?)
I'm implementing searching funcionality of an entity in the db.. and I also search by many fields at the same time..
Thank you
Marco
You can't directly use nulls in equality tests, because null is un-equal to everything, including itself. That's why there's the is null test, e.g:
select null = null -> null
select null <> null -> null
select 1 = null -> null
select 1 <> null -> null
select 1 + null -> null
essentially null is contagious, and will nullify anything it's compared to, or added in to.
So yes, you'll have to do
SELECT ... WHERE somefield LIKE '%...%' or somefield IS NULL
Try this:
...
and IFNULL(d.field2, '') like '%'
...
where ...
and (field2 = '' or field2 is null)
Note that the condition field2 like '%' is nonsensical because it matches any text except null. If you added or field2 is mull to it you would match everything, so logically you should just remove the condition on field2
Use IS NULL:
where d.field1 like 'TEST%' OR d.field2 IS NULL;
FROM DomainObj d where (d.field1 like 'TEST%' or d.field1 IS NULL) and (d.field2 like '%' or d.field2 IS NULL)