Skipping AND when variable IS NULL - mysql

I have an existing Stored Procedure and i add some parameter to filter the result.But when #id_account is null it returns Empty Data. I want to skip AND when #id_account is null, i try IF condition but it wont work. Any suggestion? Thanks :D
AND
(
pd_account.id_account = #id_account
)

Put in the condition you really want, which is:
(pd_account.id_account = #id_account or #id_account is null)

Use:
AND
(
pd_account.id_account = COALESCE(#id_account,pd_account.id_account)
)
From COALESCE doc
Returns the first non-NULL value in the list, or NULL if there are no
non-NULL values.
So when #id_account is not provided the condition will be pd_account.id_account =pd_account.id_account which is equivalent to 1=1 always true.
You can use CASE like:
AND pd_account.id_account = CASE WHEN #id_account IS NOT NULL THEN #id_account
ELSE pd_account.id_account
END

Related

MySQL JSON_EXTRACT subquery not working when enclosed in IFNULL

Goal
Select a value based on a value returned by a subquery that is using JSON_EXTRACT which either returns a 'value' or NULL. IFNULL should be able to allow you to set a default value when the JSON_EXTRACT does not return a result.
Problem
When using a subquery that uses JSON_EXTRACT and returns a result, will return nothing when enclosed in IFNULL ignoring the default value.
Consider the following case
We want to select a SubscriptionPlan.name based on an identifier that is the result of a subquery using JSON_EXTRACT.
SELECT
subscriptionplan.name
FROM
SubscriptionPlan AS subscriptionplan
WHERE
subscriptionplan.identifier = (
SELECT
JSON_EXTRACT(product.data, '$.identifier')
FROM
Subscription AS subscription
JOIN
Product AS product ON product.productid = subscription.productid
WHERE
subscription.status = 'ACTIVE'
AND
subscription.ownerid = :userId
)
Case 1. SUCCESS without IFNULL
Subscription exists with status 'ACTIVE' and 'userId'
- Subquery result: 'PRO' and thus finds the SubscriptionPlan
- Final result: 'Professional'
Case 2. NOT FOUND without IFNULL
Subscription not found with status 'ACTIVE' and 'userId'
- Subquery result: NULL and thus does not find a SubscriptionPlan
- Final result: NULL
Now we add the IFNULL operation to default to 'FREE' subscription plan:
subscriptionplan.identifier = IFNULL(
( SELECT JSON_EXTRACT ... ),
'FREE'
)
Case 3. SUCCESS with IFNULL
Subscription exists with status 'ACTIVE' and 'userId'
- Subquery result: NULL even though the subscription was found !???
- Final result: NULL
Case 4. NOT FOUND with IFNULL
Subscription not found with status 'ACTIVE' and 'userId'
- Subquery result: FREE and thus finds the FREE SubscriptionPlan
- Final result: 'Free'
The IFNULL expression nullifies the subquery result, and it does not default to 'FREE'.
My thoughts are as follows:
Case 4: is using the IFNULL default value string 'FREE' and therefore works as intended
Case 3: subquery should return PRO and even if it returns NULL, it should default to 'FREE', neither happens
Maybe adding the IFNULL query adds another nesting layer where
What i've tried and did not work:
IF( () IS NULL, 'do stuff', 'do other stuff')
IF( ISNULL(<query<), 'do stuff', 'do other stuff')
IF( () = null , ..., ...)
IF( () = NULL , ..., ...)
IF( () = 'null' , ..., ...)
IF( () = 'NULL' , ..., ...)
Also according to Can't detect null value from JSON_EXTRACT:
IF ( JSON_EXTRACT(product.data, '$.identifier') = CAST('null' AS JSON), ...., ... )
All failures! Why is JSON_EXTRACT subquery not working when enclosed in IFNULL?
I've found out what caused the error.
JSON_EXTRACT adds quotes around its result resulting in "PRO" instead of PRO and therefore the IFNULL default is not triggered and the subscription plan, which is PRO, is not found using "PRO".
Add JSON_UNQUOTE around the JSON_EXTRACT solves the issue.

Concatenate only when all values are true in mysql

The following is the query I have used to concatenate siretagprefix and siretagsec
CONCAT('TZN',
`adggtnz`.`reg04_rpt_animreg`.`siretagprefix`,
`adggtnz`.`reg04_rpt_animreg`.`siretagsec`) AS `siretagid`,
The result of the query when siretagprefix and siretagsec when the values are null, I get TZN as the result. How can I concatenate only when all the values are true.
You could use CASE to check your column values
CASE WHEN `adggtnz`.`reg04_rpt_animreg`.`siretagprefix` IS NOT NULL
AND `adggtnz`.`reg04_rpt_animreg`.`siretagsec` IS NOT NULL
THEN
CONCAT('TZN',
`adggtnz`.`reg04_rpt_animreg`.`siretagprefix`,
`adggtnz`.`reg04_rpt_animreg`.`siretagsec`)
ELSE NULL END AS siretagid
You could use a case expression:
CASE WHEN `adggtnz`.`reg04_rpt_animreg`.`siretagprefix` IS NOT NULL AND
`adggtnz`.`reg04_rpt_animreg`.`siretagsec` IS NOT NULL
THEN CONCAT('TZN',
`adggtnz`.`reg04_rpt_animreg`.`siretagprefix`,
`adggtnz`.`reg04_rpt_animreg`.`siretagsec`)
END AS `siretagid`

How to select last column without Null in mySQL

I am facing an issue I cannot seem to find the solution of anywhere. I have a table in mySQL with following columns:
RoleDuty1
RoleDuty2
RoleDuty3
RoleDuty4
RoleDuty5
RoleDuty6
RoleDuty7
This table has just one row or record. I want to see which is the last column in the table which is Not NULL? meaning that I want to dynamically get Column Name RoleDuty7 as an answer from mySQL, since all of the columns have some value other than Null inside them.
Anyone has any idea how can I do this?
This is exactly what the coalesce function is for:
SELECT COALESCE(RoleDuty1,RoleDuty2,RoleDuty3,RoleDuty4,RoleDuty5,RoleDuty6,RoleDuty7,'All null) as FIRST_NON_NULL
FROM aTable
I think you have to use a COALESCE with a bunch of CASE statements, like this:
SELECT COALESCE(rd1, rd2, rd3, rd4, rd5, rd6, rd7)
FROM
(SELECT
CASE WHEN roleduty1 IS NOT NULL THEN 'roleduty1' ELSE NULL END AS rd1,
CASE WHEN roleduty2 IS NOT NULL THEN 'roleduty2' ELSE NULL END AS rd2,
....
FROM t) sub
SELECT (
CASE FirstNullColumn
WHEN 'RoleDuty1' THEN 'None'
WHEN 'RoleDuty2' THEN 'RoleDuty1'
WHEN 'RoleDuty3' THEN 'RoleDuty2'
WHEN 'RoleDuty4' THEN 'RoleDuty3'
WHEN 'RoleDuty5' THEN 'RoleDuty4'
WHEN 'RoleDuty6' THEN 'RoleDuty5'
WHEN 'RoleDuty7' THEN 'RoleDuty6'
ELSE 'RoleDuty7'
END
) AS LastNonNullColumn
FROM (
SELECT (
CASE
WHEN RoleDuty1 IS NULL THEN 'RoleDuty1'
WHEN RoleDuty2 IS NULL THEN 'RoleDuty2'
WHEN RoleDuty3 IS NULL THEN 'RoleDuty3'
WHEN RoleDuty4 IS NULL THEN 'RoleDuty4'
WHEN RoleDuty5 IS NULL THEN 'RoleDuty5'
WHEN RoleDuty6 IS NULL THEN 'RoleDuty6'
WHEN RoleDuty7 IS NULL THEN 'RoleDuty7'
ELSE 'None'
END
) AS FirstNullColumn
FROM MyTable
)

NULL != NULL in mysql query

I am trying to do a query that sees if fields are equivalent. However, whenever the field is NULL it returns a false result. I even tried doing the same thing with the column itself:
SELECT * FROM `mturk_completion` WHERE (`mturk_completion`.`imdb_url` =
`mturk_completion`.`imdb_url` AND `mturk_completion`.`worker_id` = 'A3NF84Q37D7F35' )
And it only returns results where the column is not NULL. Why is this so, and how do I get around it?
Your title is absolutely correct for any SQL implementation (not just MySQL). NULL is not equal to anything (including another NULL).
You need to use explicit IS NULL check or COALESCE() function (or its RDBMS-dependent alternatives) to set some default value in case of NULL.
Your comparison of mturk_completion.imdb_url to itself is redundant and should always return True, except when mturk_completion.imdb_urlis Null, in which case it will return Null.
That's because the operator = returns either True, False when comparisons can be made or Null, when either of the two operators is Null
Try this to illustrate the situation.
SELECT 1 = NULL; -- returns NULL
SELECT 1 != NULL; -- also return NULL
SELECT ISNULL(1 = NULL); -- returns 1
SELECT ISNULL(1 != NULL); -- returns 1
If you rewrite your query like below, your problems with ignoring NULLs will go away:
SELECT * FROM `mturk_completion` WHERE worker_id = 'A3NF84Q37D7F35'
I think you can use
(table.Field = table2.Field OR COALESCE(table.Field, table2.Field) IS NULL)

MySQL Left Join, SELECT a field either from one or the other if null

I am trying to LEFT JOIN 2 tables. which is working out fine. But i am getting back two sets of fields named setting_value. iam trying to get tblSettings.setting_value only if tblAgencySettings.setting_value is NULL. How would i go about doing this? I know i can rename the fields, then in PHP i can check the tblAgencySettings.setting_value and if NULL then grab the tblSettings.setting_value but i prefer to keep this at MySQL.
SELECT `tblSettings`.`id`, `tblSettings`.`setting_name`,
`tblSettings`.`setting_value`, `tblAgencySettings`.`setting_value`
FROM `tblSettings` LEFT JOIN `tblAgencySettings`
ON `tblSettings`.`id` = `tblAgencySettings`.`setting_id`
AND `tblAgencySettings`.`agency_id` = '1'
WHERE `tblSettings`.`changeable` = '1'
slight issue i just noticed. i failed to mention this. if tblAgencySettings.setting_value does have a value. but changeable is not 1 then just select tblSettings.setting_value
Just add a COALESCE:
SELECT `tblSettings`.`id`, `tblSettings`.`setting_name`,
COALESCE(`tblAgencySettings`.`setting_value`, `tblSettings`.`setting_value`)
FROM `tblSettings` LEFT JOIN `tblAgencySettings`
ON `tblSettings`.`id` = `tblAgencySettings`.`setting_id`
AND `tblAgencySettings`.`agency_id` = '1'
WHERE `tblSettings`.`changeable` = '1'
The COALESCE function returns the first non-NULL value you give it so this:
COALESCE(`tblAgencySettings`.`setting_value`, `tblSettings`.`setting_value`)
Will be tblAgencySettings.setting_value if that's not NULL and tblSettings.setting_value if tblAgencySettings.setting_value is NULL.
If tblAgencySettings.setting_value can also be zero and you want to ignore that as well as NULL, then you could use this instead of the COALESCE above:
COALESCE(
IF(`tblAgencySettings`.`setting_value` = 0, NULL, `tblAgencySettings`.`setting_value`),
`tblSettings`.`setting_value`
)
The IF returns the second argument if the first is true and the third if the first argument is false so the above use converts zero to NULL. Or, you could go all the way to a CASE statement:
case
when `tblAgencySettings`.`setting_value` = 0 then `tblSettings`.`setting_value`
when `tblAgencySettings`.`setting_value` IS NULL then `tblSettings`.`setting_value`
else `tblSettings`.`setting_value`
end
Change your SQL Statement to this:
SELECT `tblSettings`.`id`, `tblSettings`.`setting_name`,
CASE WHEN `tblSettings`.`setting_value` IS NULL THEN `tblAgencySettings`.`setting_value`
ELSE `tblSettings`.`setting_value` END AS `setting_value`
FROM `tblSettings` LEFT JOIN `tblAgencySettings`
ON `tblSettings`.`id` = `tblAgencySettings`.`setting_id`
AND `tblAgencySettings`.`agency_id` = '1'
WHERE `tblSettings`.`changeable` = '1'
Here's a link to MYSQL CASE Statement for your reference.