When statment to replace Null data - sql-server-2008

money
20.00
17.87
5.00
NULL
3.00
I want the null entries turned into zeroes. The money column is for money spent. Ive tried the following and it didnt like changing NUll to a dollar value.
select case money when 'NULL' then 0 end
from mytable

select coalesce(money, 0) from mytable
Coalesce will take the first non-null value in the list.

Try:
SELECT IsNull(money, 0)
FROM mytable
EDIT
If you want to replace the values in the table:
UPDATE mytable
SET money = 0
WHERE money Is Null

While I agree with the other two answers, I wasnted to explain why what you did was not right.
select case money when 'NULL' then 0 end
from mytable
Here you are treating NULL as a string value. But NULL is a condition not a value. It means there is no known value. If you inserted the actual word 'null' into the table in that field, then your code would have worked.
When you want to test for a NULL condition you use:
WHERE field1 IS NULL
or you change the value using coalesce or ISNULL. If you need to test for NULL as part of a case statement, then you would do it like this:
CASE WHEN field1 IS NULL THEN 0 ELSE T1 END
For simple cases like yours, COALESCE or ISNULL is best. But at times you may need to do a very complicated CASE and then it is handy to know how to do it.

Related

Why does <> 'null' works in MySQL?

Hope the question is not too generic. Couldn't find anything on the site or in SQL documentation:
While coding, i tested this, and to my surprise it worked:
SELECT * FROM cal_entry WHERE cal_entry.parent_id <> 'null'
It actually shows the rows without the ones with NULL values (these are real NULL values in database, not strings with 'null' inside).
According to the docs, I should have used NOT NULL, of course. By the way, it doesn't work with = 'null', like it is correctly stated in the docs.
Can someone explain that?
You are selecting all rows where <> 'null' is true.
Comparing(equals or not-equals) to null is null, so if a row where cal_entry.parent_id is null, your condition will be false/null.
So your query gets all rows that are not null, nor contain the string 'null'.
(Note, you could just as well have written <>'something_else')
Assuming parent_id in an int column the query will return all non-null, non-zero rows:
SELECT *
FROM (
SELECT NULL AS parent_id UNION ALL
SELECT 0 UNION ALL
SELECT 1 UNION ALL
SELECT 2
) AS cal_entry
WHERE cal_entry.parent_id <> 'null'
-- returns 1 and 2 but not 0!
When comparing a number to string MySQL will convert the string to number. Some examples:
'null' becomes 0
'asdf' becomes 0
'1asdf' becomes 123
'1' becomes 1
Your query will behave like:
WHERE cal_entry.parent_id <> 0
this operator give you result of not equal to. ex. $var != null.
we write in mysql as <>. this is kind of validation that the value shoud never be equal to null.
When working with null following two statements should always be taken note of -
An expression can be null, but it can never be equal to null.
Two nulls are never equal to each other.
So, in your query wherever there is a comparison null<>null it returns true by second statement.
Also, always account the possibility that some rows might contain null -
Select * from cal_entry where cal_entry.parent_id!=10
This query would leave out the rows with null entries. Instead use -
Select * from cal_entry where cal_entry.parent_id!=10 or cal_entry.parent_id is null

Select field conditionally from mysql

Is it possible to use Select with Case to select from one of several fields depending on which of them is null or not?
I basically want to return a value for all records with logic that says
Return $Value from FIeldA if not null
else from FieldB if not NULL
else from FieldC if not Null
else '0'
I've used Case/When/Then to compare values from a specific field but not as a way of comparing values between fields and not sure if this is possible.
Short answer, use COALESCE:
SELECT COALESCE(FieldA, FieldB, FieldC, 0) AS FieldName
FROM tableName;
It will give you the first non nullable value from the three fields FieldA, FieldB, FieldC. If all are null, then it will return 0. Which what you are trying to do.
Long answer, use CASE expression.
if you want to check multiple filed and if null then return same result 0 then use COALESCE function . this is simple code
SELECT COALESCE(filed1, filed2, filed3, 0) as output from table;
for more information
https://www.w3schools.com/sql/func_sqlserver_coalesce.asp
extra option if you want to select filed using condition then use case. this is demo code
SELECT CASE 1 WHEN 1 THEN 'this is case one'
WHEN 2 THEN 'this is case two'
ELSE 'this is not in the case'
END as 'how to execute case statement';
for more information
https://dev.mysql.com/doc/refman/5.7/en/case.html
http://www.mysqltutorial.org/mysql-case-function/

MySql confusion between empty value (i.e. '') comparision against NULL [duplicate]

Could someone please explain the following behavior in SQL?
SELECT * FROM MyTable WHERE MyColumn != NULL (0 Results)
SELECT * FROM MyTable WHERE MyColumn <> NULL (0 Results)
SELECT * FROM MyTable WHERE MyColumn IS NOT NULL (568 Results)
<> is Standard SQL-92; != is its equivalent. Both evaluate for values, which NULL is not -- NULL is a placeholder to say there is the absence of a value.
Which is why you can only use IS NULL/IS NOT NULL as predicates for such situations.
This behavior is not specific to SQL Server. All standards-compliant SQL dialects work the same way.
Note: To compare if your value is not null, you use IS NOT NULL, while to compare with not null value, you use <> 'YOUR_VALUE'. I can't say if my value equals or not equals to NULL, but I can say if my value is NULL or NOT NULL. I can compare if my value is something other than NULL.
NULL has no value, and so cannot be compared using the scalar value operators.
In other words, no value can ever be equal to (or not equal to) NULL because NULL has no value.
Hence, SQL has special IS NULL and IS NOT NULL predicates for dealing with NULL.
Note that this behavior is the default (ANSI) behavior.
If you:
SET ANSI_NULLS OFF
http://msdn.microsoft.com/en-us/library/ms188048.aspx
You'll get different results.
SET ANSI_NULLS OFF will apparently be going away in the future...
We use
SELECT * FROM MyTable WHERE ISNULL(MyColumn, ' ') = ' ';
to return all rows where MyColumn is NULL or all rows where MyColumn is an empty string. To many an "end user", the NULL vs. empty string issue is a distinction without a need and point of confusion.
In SQL, anything you evaluate / compute with NULL results into UNKNOWN
This is why SELECT * FROM MyTable WHERE MyColumn != NULL or SELECT * FROM MyTable WHERE MyColumn <> NULL gives you 0 results.
To provide a check for NULL values, isNull function is provided.
Moreover, you can use the IS operator as you used in the third query.
The only test for NULL is IS NULL or IS NOT NULL. Testing for equality is nonsensical because by definition one doesn't know what the value is.
Here is a wikipedia article to read:
https://en.wikipedia.org/wiki/Null_(SQL)
NULL Cannot be compared to any value using the comparison operators. NULL = NULL is false. Null is not a value. The IS operator is specially designed to handle NULL comparisons.
null represents no value or an unknown value. It doesn’t specify why there is no value, which can lead to some ambiguity.
Suppose you run a query like this:
SELECT *
FROM orders
WHERE delivered=ordered;
that is, you are looking for rows where the ordered and delivered dates are the same.
What is to be expected when one or both columns are null?
Because at least one of the dates is unknown, you cannot expect to say that the 2 dates are the same. This is also the case when both dates are unknown: how can they be the same if we don’t even know what they are?
For this reason, any expression treating null as a value must fail. In this case, it will not match. This is also the case if you try the following:
SELECT *
FROM orders
WHERE delivered<>ordered;
Again, how can we say that two values are not the same if we don’t know what they are.
SQL has a specific test for missing values:
IS NULL
Specifically it is not comparing values, but rather it seeks out missing values.
Finally, as regards the != operator, as far as I am aware, it is not actually in any of the standards, but it is very widely supported. It was added to make programmers from some languages feel more at home. Frankly, if a programmer has difficulty remembering what language they’re using, they’re off to a bad start.
I would like to suggest this code I made to find if there is a change in a value,
i being the new value and d being the old (although the order does not matter). For that matter, a change from value to null or vice versa is a change but from null to null is not (of course, from value to another value is a change but from value to the same it is not).
CREATE FUNCTION [dbo].[ufn_equal_with_nulls]
(
#i sql_variant,
#d sql_variant
)
RETURNS bit
AS
BEGIN
DECLARE #in bit = 0, #dn bit = 0
if #i is null set #in = 1
if #d is null set #dn = 1
if #in <> #dn
return 0
if #in = 1 and #dn = 1
return 1
if #in = 0 and #dn = 0 and #i = #d
return 1
return 0
END
To use this function, you can
declare #tmp table (a int, b int)
insert into #tmp values
(1,1),
(1,2),
(1,null),
(null,1),
(null,null)
---- in select ----
select *, [dbo].[ufn_equal_with_nulls](a,b) as [=] from #tmp
---- where equal ----
select *,'equal' as [Predicate] from #tmp where [dbo].[ufn_equal_with_nulls](a,b) = 1
---- where not equal ----
select *,'not equal' as [Predicate] from #tmp where [dbo].[ufn_equal_with_nulls](a,b) = 0
The results are:
---- in select ----
a b =
1 1 1
1 2 0
1 NULL 0
NULL 1 0
NULL NULL 1
---- where equal ----
1 1 equal
NULL NULL equal
---- where not equal ----
1 2 not equal
1 NULL not equal
NULL 1 not equal
The usage of sql_variant makes it compatible for variety of types
NULL is not anything...it is unknown. NULL does not equal anything. That is why you have to use the magic phrase IS NULL instead of = NULL in your SQL queries
You can refer this: http://weblogs.sqlteam.com/markc/archive/2009/06/08/60929.aspx

Mysql SUM inside a CASE

Say I have a query that is something like this:
select
table1.column1,
table1.column2,
...,
case when foo.id is null then 'N/A' else sum(foo.points) end as score -- same result using ifnull()
from
table1 inner join table2 on ...
left join foo on ...
group by ...
Since I do a LEFT JOIN on foo, there is a chance that there is no match. In that case, I want the score to show as 'N/A' instead of NULL or 0. But when I do the above query, I get blob for the score column for all rows.
When you have different data types in the results in the case it will return a value with the data type blob if it can't find a common type.
Try casting the sum to a char:
case when foo.id is null then 'N/A' else cast(sum(foo.points) as char) end as score
If you are grouping, you should really put your sum around the case, like:
sum(case when foo.id is null then 0 else foo.points)
..as otherwise you are summing just the row value (meaning only one value).
Also, a column should only have one data type, so either number or text, which is why you might be seeing this issue since you are trying to display either a number or text in the same column.
If you really want N/A, you can try converting the number to text, and then using the coalesce function to handle nulls, however I would need to see your data to say the best way to write your above query. If you can create an SQL fiddle, I would be more than happy to take a look :)
SUM up the the results of the CASE..WHEN.
SUM(CASE WHEN foo.id IS NULL THEN NULL ELSE foo.points) END AS score
You can display the default value in the frontend application (n/a) when the score field is null (or equals to 0).
The score will be NULL when there all rows has null in foo.id.

MySQL GROUP BY NULL and EMPTY

In a MySQL query I am doing a GROUP BY with a text field. Due to the nature of the original data, some rows are contain empty strings for this field, and others are true null.
When grouping, how can I group empty string and null together, treating both as null?
This can be accomplished by SELECT CASE. There may be a simpler way I do not know of.
The format of SELECT CASE is
SELECT
CASE
WHEN table_name.text_field IS NULL OR table_name.text_field = ''
THEN null
ELSE table.text_field
END as new_field_name,
other_field, another_field, ...rest of query...
So you see, you can CASE together values with WHEN/THEN and default to the real value by ELSE.