Using COALESCE to handle NULL values in PostgreSQL - sql

I have the following query
SELECT DISTINCT
pt.incentive_marketing,
pt.incentive_channel,
pt.incentive_advertising
FROM test.pricing pt
WHERE pt.contract_id = 90000
group by 1,2,3
order by pt.incentive_marketing;
The above query returns the o/p as shown in the attached image
However I want to replace all null values by 0 using COALESCE
Please let me know how this can be achieved in above SELECT query
Now I further modified the query using coalesce as below
SELECT
COALESCE( pt.incentive_marketing, '0' ),
COALESCE(pt.incentive_channel,'0'),
COALESCE( pt.incentive_advertising,'0')
FROM test.pricing pt
WHERE pt.contract_id = 90000
group by 1,2,3
the result of which is as attached in image 2.
I still receive one row with blank values

You can use COALESCE in conjunction with NULLIF for a short, efficient solution:
COALESCE( NULLIF(yourField,'') , '0' )
The NULLIF function will return null if yourField is equal to the second value ('' in the example), making the COALESCE function fully working on all cases:
QUERY | RESULT
---------------------------------------------------------------------------------
SELECT COALESCE(NULLIF(null ,''),'0') | '0'
SELECT COALESCE(NULLIF('' ,''),'0') | '0'
SELECT COALESCE(NULLIF('foo' ,''),'0') | 'foo'

If you're using 0 and an empty string '' and null to designate undefined you've got a data problem. Just update the columns and fix your schema.
UPDATE pt.incentive_channel
SET pt.incentive_marketing = NULL
WHERE pt.incentive_marketing = '';
UPDATE pt.incentive_channel
SET pt.incentive_advertising = NULL
WHERE pt.incentive_marketing = '';
UPDATE pt.incentive_channel
SET pt.incentive_channel = NULL
WHERE pt.incentive_marketing = '';
This will make joining and selecting substantially easier moving forward.

Related

How to use Decode Function in the case where column has string values

I have a view xxabc_v (shown below), I need to update the "Code" column to Null wherever it is N/A when "Value" column sum (900+(-900)=0) becomes zero for the "field_name" values (Demand A+Demand B) for the "Date" 01-Apr-21.
How can I put the decode logic to code column in the above case?
Table structure and expected output:
You don't want decode() because a much simpler method works:
select nullif(code, 'N/A')
This returns NULL when code takes on the specified value.
If you actually want to change the data, then you want update:
update t
set code = NULL
where code = 'N/A';
EDIT:
I see, you have an extra condition. So, use case:
(case when code = 'N/A' and
sum(value) over (partition by id, date) = 0
then NULL
else code
end)
I assumed that you need date wise id wise sum when to sum(). Please check this out:
select date,id,(case when sum(value)over(partition by date,id)=0 and code='N/A' then NULL
else Code end)code, field_name,value
from tablename

SQL SUM to ignore NULL value

I have a table TEST_TABLE as follows:
Name x_col y_col
=======================
Jay NULL 2
This is a simplistic representation of a much larger issue but will suffice.
When I do the following query I get NULL returned
SELECT SUM(x_col + y_col) FROM TEST_TABLE WHERE Name='Jay'
I want it to be 2. I thought the SUM() method ignores NULL values. How can I ignore values that are null in this query? Or actually in general, as this is a problem for a lot of my algorithms.
You get NULL because NULL + 2 returns NULL. The SUM() has only one row, and if the + expression is NULL, then the SUM() returns NULL.
If you want NULL to be treated as 0, the use COALESCE():
SELECT SUM(COALESCE(x_col, 0) + COALESCE(y_col, 0))
FROM TEST_TABLE
WHERE Name = 'Jay';
One final note. If you start with your data and filtered out all rows, then the result will still be NULL. To get 0, you need an additional COALESCE():
SELECT COALESCE(SUM(COALESCE(x_col, 0) + COALESCE(y_col, 0)), 0)
FROM TEST_TABLE
WHERE Name = 'Jayden';
Use COALESCE to replace NULL with 0.
SELECT sum(coalesce(x_col, 0) + coalesce(y_col, 0)) FROM TEST_TABLE WHERE Name='Jay'

Postgres incrementing null value in a column

In Postgres 9.3 when a field in a table has a null value the following expression doesn't work:
update table_statatistic set members = members + 1 WHERE user_id = $1;
However when the field has an integer value then this query increments it by 1 without a problem.
The questions are:
Why is this happening.
How to fix it.
you need to use coalesce for checking null values
update table_statatistic set members = coalesce(members, 0) + 1 WHERE user_id = $1
Use COALESCE() instead:
The COALESCE function returns the first of its arguments that is not null. Null is returned only if all arguments are null. It is often used to substitute a default value for null values when data is retrieved for display
UPDATE table_statatistic SET members = COALESCE(members,0) + 1 WHERE user_id = $1;

Oracle no results, small query

I am having trouble with some sql. When I run the following query:
Select * from teleapp;
I get TONS of results. Resulst which include a column (called cashwithappyn) that has TONS of empty or null data cells. (They look empty and don't say null)
The column info is:
ColumnName ID Null? Data Type Histogram Num Distinct Num Nulls Density
CASHWITHAPPYN 54 Y VARCHAR2(1 Byte) Frequency 2 56895 0
When I try to run the following query:
Select * from teleapp where cashwithappyn = null;
or
Select * from teleapp where cashwithappyn = '';
or
Select * from teleapp where cashwithappyn not like '';
or
Select * from teleapp where cashwithappyn not in ('Y','N');
or ANY type of combination, I cannot seem to get all of the rows with nothing in cashwithappyn.
Any ideas? Please help, this is the last part of a project that I was assigned to do and I just need to figure this out.
Thanks.
Maybe the column contains blanks. In that case you can do
WHERE TRIM(CASHWITHAPYYN) IS NULL
TRIM removes all blanks before and after and if nothing is left anymore the value becomes NULL
e.g.
TRIM(' ') IS NULL -- one blank removed = true
TRIM(NULL) IS NULL -- true
Also NULL cannot be compared with = NULL but must be phrased IS NULL. NULL is not a value as such and that is why the comparison never works.
You need to use IS NULL
Select * from teleapp where cashwithappyn is null;
Logical test expressions (=, Not In, Like etc) with null result in a false so all of the following result in false
1 = NULL
1 <> NULL
NULL = NULL
NULL <> NULL
NULL NOT IN ('a','b')
NULL Not Like NULL
Additionally in oracle the zero length string is null so NOT LIKE '' will never return any rows
You'll need to use either is null, is not null or Coalesce
A co-worker and I did a bunch of research, here's what we came up with that will work. Any ideas why this works but not the others?
Select * from teleapp where nvl(cashwithappyn,'U') = 'U';

Testing for whitespace in SQL Server

I've got some blank values in my table, and I can't seem to catch them in an IF statement.
I've tried
IF #value = '' and if #value = NULL and neither one catches the blank values. Is there any way to test whether or not a varchar is entirely whitespace?
AHA! Turns out I was testing for null wrong. Thanks.
ltrim(rtrim(isNull(#value,''))) = ''
To compare with NULL, use the IS NULL keyword.
--Generic example:
SELECT *
FROM MY_TABLE
WHERE SOME_FIELD IS NULL;
--Instead of
SELECT *
FROM MY_TABLE
WHERE SOME_FIELD = NULL;
if length(#value) = 0 or #value is null
(LTRIM(RTRIM(#Value))=''
should do the trick.
where length(rtrim(ltrim(yourcolumnname))) = 0 OR yourcolumnname is null
I just did some testing, and found out something interesting.
I used to write my queries like so:
SELECT *
FROM TableA
WHERE Val IS NOT NULL
AND LEN(RTRIM(LTRIM(Val))) > 0
But, you don't actually need to check for null, all you need to do is check the length after trimming the value.
SELECT *
FROM TableA
WHERE LEN(RTRIM(LTRIM(Val))) > 0
This select weeds out nulls as well as any columns with just white space.
As it turns out, you don't need to trim the value because SQL Server ignores trailing whitespace, so all you actually need it this:
SELECT *
FROM TableA
WHERE LEN(Val) > 0
Rather then performing excessive string manipulation with LTRIM AND RTRIM, just search the expression for the first "non-space".
SELECT
*
FROM
[Table]
WHERE
COALESCE(PATINDEX('%[^ ]%', [Value]), 0) > 0
You may have fields with multiple spaces (' ') so you'll get better results if you trim that:
where ltrim(yourcolumnname) = ''