I have a query that I'm trying to use to update only cells with empty strings to NULL. But instead, when I run this command ALL of the cells end up being NULL:
UPDATE table_name
SET InvoiceId=NULL,
LinkedAccountId=NULL,
RecordId=NULL,
ProductName=NULL,
RateId=NULL,
SubscriptionId=NULL,
PricingPlanId=NULL,
UsageType=NULL,
Operation=NULL,
AvailabilityZone=NULL,
ReservedInstance=NULL,
UsageStartDate=NULL,
UsageEndDate=NULL,
UsageQuantity=NULL,
BlendedRate=NULL,
UnBlendedRate=NULL,
ResourceId=NULL,
Engagement=NULL,
Name=NULL,
Owner=NULL,
Parent=NULL
WHERE InvoiceId=''
OR LinkedAccountId=''
OR RecordId=''
OR ProductName=''
OR RateId=''
OR SubscriptionId=''
OR PricingPlanId=''
OR UsageType=''
OR UsageEndDate=''
OR Operation=''
OR AvailabilityZone=''
OR ReservedInstance=''
OR UsageStartDate=''
OR UsageEndDate=''
OR UsageQuantity=''
OR BlendedRate=''
OR UnBlendedRate=''
OR ResourceId=''
OR Engagement=''
OR Name=''
OR Owner=''
OR Parent='';
What am I doing wrong?
You are setting ALL fields to NULL where any field = ''
You might need to write as many queries as fields you want to update.
I might be wrong, but I don't think this is possible to do in a single query
UPDATE table_name
SET InvoiceId = NULL
WHERE InvoiceId = ''
And this for every fields
The way to interpret your SQL query is kind of like this:
UPDATE table_name
SET
(all these fields to null)
WHERE
(if ANY Of these conditions is true)
I agree with Cid that it might be the safest to do 1 field per query at a time, but this is how you could write this in a single query:
UPDATE table_name SET
field1 = IF(field1='',NULL,field1),
field2 = IF(field2='',NULL,field2),
/* etc */
I think you're assuming that the terms in your WHERE clause have an implicit correlation with the assignments in your SET clause, so only some columns will be set, depending on which ones satisfy individual terms in the WHERE clause. This is not how SQL works.
What really happens is that the whole condition of the WHERE clause is evaluated to select which rows are affected. Then all the SET assignments are applied, so all columns will be changed on the rows that satisfy the whole WHERE clause condition.
To do what you want in one pass, you could do it this way:
UPDATE table_name
SET InvoiceId=NULLIF(InvoiceId, ''),
LinkedAccountId=NULLIF(LinkedAccountId, ''),
RecordId=NULLIF(RecordId, ''),
ProductName=NULLIF(ProductName, ''),
RateId=NULLIF(RateId, ''),
SubscriptionId=NULLIF(SubscriptionId, ''),
PricingPlanId=NULLIF(PricingPlanId, ''),
UsageType=NULLIF(UsageTYpe, ''),
Operation=NULLIF(Operation, ''),
AvailabilityZone=NULLIF(AvailabilityZone, ''),
ReservedInstance=NULLIF(ReservedInstance, ''),
UsageStartDate=NULLIF(UsageStartDate, ''),
UsageEndDate=NULLIF(UsageEndDate, ''),
UsageQuantity=NULLIF(UsageQuantity, ''),
BlendedRate=NULLIF(BlendedRate, ''),
UnBlendedRate=NULLIF(UnBlendedRate, ''),
ResourceId=NULLIF(ResourceId, ''),
Engagement=NULLIF(Engagement, ''),
Name=NULLIF(Name, ''),
Owner=NULLIF(Owner, ''),
Parent=NULLIF(Parent, '')
The NULLIF() function returns NULL if its two arguments are equal, otherwise it returns the first argument. So in the case that each column is not '' then it is a no-op, setting the column to its own original value.
Related
I am using UPDATE to insert simple text into a table where the field is MEDIUMTEXT (nullable field).
It is strange that it does not work when the field is null initially. If I manually enter at least a one character/space, then it's working.
I want to append the new text into existing text in the field.
UPDATE pen SET
PEN_STATUS = #PenStat,
PEN_STATUS_CHANGE_REASON = CONCAT(PEN_STATUS_CHANGE_REASON,'\n',ChangeDate,':',EmployeeID,':',ChangeReason)
WHERE PEN_ID = PenID;
Why is this?
CONCAT does not handle NULL values. As explained in the MySQL manual:
CONCAT() returns NULL if any argument is NULL.
You want to use COALESCE to handle that use case, like :
UPDATE pen SET
PEN_STATUS = #PenStat,
PEN_STATUS_CHANGE_REASON = CONCAT(
COALESCE(PEN_STATUS_CHANGE_REASON, ''),
'\n',
ChangeDate,
':',
EmployeeID,
':',
ChangeReason
)
WHERE PEN_ID = PenID;
Presumably, because something is NULL. Try using CONCAT_WS() instead:
UPDATE pen
SET PEN_STATUS = #PenStat,
PEN_STATUS_CHANGE_REASON = CONCAT_WS('\n',
PEN_STATUS_CHANGE_REASON,
CONCAT_WS(':', ChangeDate, EmployeeID, ChangeReason
)
)
WHERE PEN_ID = PenID;
CONCAT_WS() ignores NULL arguments. Plus, the separator only needs to be listed once.
I have a table with Boolean values (0 and 1 only) that needs to be CSV-ed to a client. I know I can do 1 replace like this:
SELECT REPLACE(email, '%40', '#'),
REPLACE(name,'%20', ' '),
REPLACE(icon_clicked, 1, 'Yes')
FROM myTable
WHERE id > 1000;
This will convert all the values of 1 to 'Yes', but how to do this in a single query for both 1 => Yes and 0 => No so Boolean result is stored in a single column? I tried to do this:
SELECT REPLACE(email, '%40', '#'),
REPLACE(name,'%20', ' '),
REPLACE(icon_clicked, 1, 'Yes'),
REPLACE(icon_clicked, 0, 'No')
FROM myTable
WHERE id > 1000;
But this query created an additional column for the 'No' string replace (so final result had 4 columns, email, name, icon_clicked->yes, icon_clicked->no)
One way is to nest REPLACE:
SELECT REPLACE(REPLACE(icon_clicked, 0, 'No'), 1, 'Yes')), ...
FROM myTable
...
or use CASE WHEN (this will work for most RDBMS comparing to IF function which is MySQL related):
SELECT CASE WHEN icon_clicked THEN 'Yes' ELSE 'No' END, ...
FROM myTable
...
SqlFiddleDemo
EDIT:
There is also one nice way utilizing ELT:
SELECT icon_clicked,
ELT(FIELD(icon_clicked,0,1),'No','Yes'),
ELT(icon_clicked + 1, 'No', 'Yes')
FROM mytable
SqlFiddleDemo2
No need to use nested Replace or Case statement. Try using IF, which is way simpler
SELECT
icon_clicked,
IF(icon_clicked,'Yes','No')
FROM myTable
SQL FIDDLE DEMO
This is the query i execute after insertation in some table in my database. Here i am getting rate_like_id and all other fields i also save them but when i use CONCAT and trying to save them as json it inserts NULL value via trigger.
Is this a wrong way to do this. Is ther any other way i can save this type of data via trigger mysql.
INSERT INTO `log_activity`(`visitor_id`,
`rating_like_id`,
`type`,
`response`,
`created_by`,
`created_date`)
VALUES (new.created_by,
new.rating_like_id,
CASE WHEN new.is_like = NULL THEN "Rating" ELSE "Like" END ,
-- Here is this column Should not be null but it is coming null when INSERTED
CONCAT(
'{"card_id":','"',new.card_id,'"',
',"card_type":','"',new.card_type,'"',
',"user_id":','"',new.user_id,'"',
',"is_like":','"',new.is_like,'"',
',"has_rated":','"',new.has_rated,'"',
',"rate":','"',new.rate,'"',
',"created_by":','"',new.created_by,'"',
',"created_date":','"',new.created_date,'"',
',"card_type":','"',new.card_type,'"','}'),
new.created_by,
new.created_date)
what is wrong with this .. all other fields are saved correctly only CONCAT field is not getting inserted properly.
Yes I am able to insert value like this
CONCAT(" hi "," how "," are "," you ", " ? ")
Is this problem because i am using "new.fieldName" inside CONCAT ... i see THIS question they are doing the same thing .. ofcource it is less complex compare to mine.
If you see comments and conversation between me and marcB.. you will get the answer...
Here i want to show what changes i made to my query to make it work.
marcB said :- Remember that sql null is contagious. if ANY of the fields you're concatting are themselves null, the ENTIRE result becomes null
so you can see my query in question.. i do not have checked for any value is it null or not. So i just had to add the null check.
INSERT INTO `log_activity`(`visitor_id`,
`rating_like_id`,
`type`,
`response`,
`created_by`,
`created_date`)
VALUES (new.created_by,
new.rating_like_id,
CASE WHEN new.is_like = NULL THEN "Rating" ELSE "Like" END,
CONCAT('{"card_id":',
'"',
IFNULL(new.card_id, ''),
'"',
',"card_type":',
'"',
IFNULL(new.card_type, ''),
'"',
',"user_id":',
'"',
IFNULL(new.user_id, ''),
'"',
',"is_like":',
'"',
IFNULL(new.is_like, ''),
'"',
',"has_rated":',
'"',
IFNULL(new.has_rated, ''),
'"',
',"rate":',
'"',
IFNULL(new.rate, ''),
'"',
',"created_by":',
'"',
IFNULL(new.created_by, ''),
'"',
',"created_date":',
'"',
IFNULL(new.created_date, ''),
'"',
',"card_type":',
'"',
IFNULL(new.card_type, ''),
'"',
'}'),
new.created_by,
new.created_date)
It checks for the null value of the field.
I need a little help in queries.
I have a table like this:
id value
1 rs-123
2 rsa-123
I need to get the first row if the user queries in following ways : rs123, rs-123, rs 123 (either using or skipping the space and dash).
WHERE REPLACE(REPLACE(value, '-', ''), ' ', '')
= REPLACE(REPLACE($val , '-', ''), ' ', '')
I expected to get full name without middle initial if there is no middle name, but if column "M_NAME" is Null, the select statement returns empty. How can i solve this?
SELECT CONCAT(`Employee`.`F_NAME`, ' ', LEFT(`Employee`.`M_NAME`, 1), '. ', `Employee`.`L_NAME`) FROM `ccms`.`Employee` WHERE HR_ID = '223';
CONCAT returns NULL if any argument is null. You can solve this by making sure that no null argument is null by wrapping any nullable column in either IFNULL or COALESCE (the latter can take more than two arguments).
SELECT
CONCAT(
IFNULL(F_NAME, ''),
' ',
IFNULL(CONCAT(LEFT(M_NAME, 1), '. '), ''),
IFNULL(L_NAME, '')
)
FROM
ccms.Employee
WHERE
HR_ID = '223';
What this does is replace NULL column values with an empty string, which is probably your intent. Note that I updated the selection of M_NAME so that the period is only added if the value is not null by using this very behavior.
EDIT: You can use backticks and qualify column names if you want, but it's not necessary for this exact query.
Use COALESCE()
Returns the first non-NULL value in the list, or NULL if there are no non-NULL values.
SELECT CONCAT(`Employee`.`F_NAME`, ' ', COALESCE(LEFT(`Employee`.`M_NAME`, 1), ''), '. ', `Employee`.`L_NAME`) FROM `ccms`.`Employee` WHERE HR_ID = '223';
Use IFNULL().
Any place you have a possibly NULL field, wrap it with IFNULL(whatever, '') and then you'll get an empty string instead of a result-killing NULL.
another simple solution is use CONCAT_WS. It will work defenitely.
SELECT
CONCAT_WS(''
F_NAME,
'',
LEFT(M_NAME, 1),
L_NAME) FROM
ccms.Employee WHERE HR_ID = '223';