COALESCE() to get Not null as well as NULL Values - mysql

I have my Mysql Query as :
select RecordID,ID,Name,Description,RecordDateTimeUTC,Location from
eemployee where RecordID like ? and(isNull(RecordDateTimeUTC) OR RecordDateTimeUTC= CASE WHEN COALESCE(?,'') = '' THEN RecordDateTimeUTC ELSE ? END)........
Now my query There are lott of fields(? --> this is where i am putting my data for filter perpose) upon which user can query so i am using coalesce but the disadvantage of using coalesce is it doesn't give me null values when i want to get all data present in employee table , so to get null values i have used isNull function.
Now i am testing the above query for two use cases
1-->User can pass percentage in RecordID:-In this case he should get all data either null as well as not null values :
select RecordID,ID,Name,Description,RecordDateTimeUTC,Location from
eemployee where RecordID like '%'
and(isNull(RecordDateTimeUTC) OR RecordDateTimeUTC= CASE WHEN COALESCE('','') = '' THEN RecordDateTimeUTC ELSE '' END)
2-->User can filter data based on RecordDateTimeUTC:- If user passes this parameter then he should get all not null data satisfying the above filteration.:-
select RecordID,ID,Name,Description,RecordDateTimeUTC,Location from
eemployee where RecordID like '%' and(isNull(RecordDateTimeUTC) OR RecordDateTimeUTC= CASE WHEN COALESCE('2012-07-09 11:11:00','') = '' THEN RecordDateTimeUTC ELSE '2012-07-09 11:11:00' END)
For the first use case it is working fine but for the second use case it is giving me filtered data as well as null Data
So what should be my query so that both my use cases are supported by the above single query.
I am using MYSQl Query Browser to test my query
Thanks in advance

It looks like you're trying to make parameters optional while using a single static SQL statement. In that case I would imagine you mean something like:
SELECT RecordID,ID,Name,Description,RecordDateTimeUTC,Location
FROM eemployee
WHERE (#RecordId IS NULL OR RecordID LIKE #RecordId)
AND (#RecordDateTimeUTC IS NULL OR RecordDateTimeUTC = #RecordDateTimeUTC)
If the parameter value is NULL, it will be omitted completely from the filter, otherwise the passed value will be used.
Note you can't use ? here because of the need to re-use the parameter - unless you want to specify each parameter twice, that is. Specifying a name makes the query a lot more readable IMHO.

Related

Query not working when I target a different column with exact same query

Known working query fails when I target a different column(same data types). This query works:
Select * from assets WHERE type = '' AND os LIKE '%7%' AND status <> 'Discarded'
BUT this query doesn't work (it returns empty set):
Select * from assets WHERE model = '' AND os LIKE '%7%' AND status <> 'Discarded'
The ONLY difference is the column type is changed to model. Both columns are varchar and there are records that meet both of the query conditions. I have tried putting `` around the field names, it didn't help.
From the comments: expression AND status <> 'Discarded' does not allow NULL values.
In SQL, NULL <> 'Discarded' is false, just like NULL = 'Discarded' is false as well. To check for nullness, you need to use IS NULL.
I think that your query should be expressed as:
SELECT *
FROM assets
WHERE
model = ''
AND os LIKE '%7%'
AND (status IS NULL OR status <> 'Discarded')
NB: it might be worth noting that storing empty strings is, generaly speaking, not a good idea. It is usually simpler to use NULL as a default value.

prepared mysql query where value may be NULL

I'm using node's mysql library and trying to do a query like so:
connection.query(`SELECT * FROM table WHERE name = ? AND field = ?`, ['a', value]);
The problem I'm running into is that sometimes value = 1 but sometimes value = null.
From my testing, results only return when the query is written as WHERE value IS null and doesn't work with WHERE value = null.
Q: How can I use the prepared query if the value may be null?
Sorry to make you disappointed, but YOU CANNOT
You should use different comparative statement, which is
WHERE value IS NULL
WHERE value = <your value>
Regards to the Mysql Reference, null values are treated differently, furthermore null values are a missing values. So You can't use arithmetic comparison for NULL
Here is the reference https://dev.mysql.com/doc/refman/8.0/en/working-with-null.html
Nobody mentioned spaceship operator <=>, it works with null-to-null comparsions
Here is great spaceship operator description
Maybe you want try this:
SELECT * FROM table WHERE IFNULL(name, 'null') = 'null' AND IFNULL(field, 'null') = 'null'
But the next problem, you cannot fill your field with value 'null', or it will makes your query and data ambiguous.

If one value is returned for a parameter then set as default, if more than one value is returned do not select a default

We have a series of reports which return a set of values for a parameter based on the userID. This works and we're happy with the way it works.
Now we need to implement a default parameter setting. The logic being
If there is only one value in the parameters available dataset, then set that as the default.
If there is more than one value in the parameters available dataset, then leave the parameter blank.
This is what I have so far - I know I have the following issues:
-Parameters cannot read fields, therefore I need the expression to look at the dataset as a whole.
-I'm unsure what my then statement should be to allow the user to review all available values without them being selected.
=IIf(CountDistinct(Fields!storekey.Value, "UserStoreVerification")) = 1, First(Fields!storekey.Value, "UserStoreVerification")," ")
You can create a separate dataset to populate the "default values" for the parameter. In this dataset you can add logic to count the number of rows that would be returned by the other dataset that provides the parameter values. If there are greater than 1 values returned by the first query then the second dataset just returns NULL (i.e. no default values are selected).
Example
If your original dataset for parameter values (e.g. "dsParamProduct") used a query like this:
SELECT ProductNumber
FROM dbo.Product
WHERE Available = 'Yes'
Then the dataset query for the default values (e.g. "dsParamProductDefault") could be something like this:
DECLARE #ValueCount INT
SELECT #ValueCount = COUNT(*)
FROM
(
SELECT ProductNumber
FROM dbo.Product
WHERE Available = 'Yes'
) vals
IF #ValueCount = 1
SELECT ProductNumber
FROM dbo.Product
WHERE Available = 'Yes'
ELSE
SELECT NULL
Supplying "NULL" as the default value when there is more than one value will mean none of the available values are selected and therefore the user will have to manually select them (assuming that NULL isn't a valid value for your parameter - if it is then make sure the default query will return something else that is definitely not valid). If there is only one possible value then the default value query just returns the same result as the parameter values dataset, which means that the parameter value will be selected.
Set up another parameter that is dependent on the first, same type but slightly different name, and do your code at bottom with one suggested change:. Change " " at the end before the parenthese end to be 'NOTHING' instead. I believe this is interpreted by SQL as NULL which is what you want.
Now you should be getting population of the parameter so I would debug and check it by just dragging and dropping it to the design surface and it should be black if you have more than one default value. You can optionally make this parameter 'hidden' once you can confirm it works.
Now you trick your main dataset with a nifty predicate (or else use some other logic if it suits you better)
Where value = isnull(#DependentParam, value)
Basically this is stating "if the parameter is not null use it, else equate the clause to be everything as it will assume value = value".

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.

MySQL: selecting rows where a column is null

I'm having a problem where when I try to select the rows that have a NULL for a certain column, it returns an empty set. However, when I look at the table in phpMyAdmin, it says null for most of the rows.
My query looks something like this:
SELECT pid FROM planets WHERE userid = NULL
Empty set every time.
A lot of places said to make sure it's not stored as "NULL" or "null" instead of an actual value, and one said to try looking for just a space (userid = ' ') but none of these have worked. There was a suggestion to not use MyISAM and use innoDB because MyISAM has trouble storing null. I switched the table to innoDB but now I feel like the problem may be that it still isn't actually null because of the way it might convert it. I'd like to do this without having to recreate the table as innoDB or anything else, but if I have to, I can certainly try that.
SQL NULL's special, and you have to do WHERE field IS NULL, as NULL cannot be equal to anything,
including itself (ie: NULL = NULL is always false).
See Rule 3 https://en.wikipedia.org/wiki/Codd%27s_12_rules
SELECT pid FROM planets WHERE userid IS NULL
As all are given answers I want to add little more. I had also faced the same issue.
Why did your query fail? You have,
SELECT pid FROM planets WHERE userid = NULL;
This will not give you the expected result, because from mysql doc
In SQL, the NULL value is never true in comparison to any other value, even NULL. An expression that contains NULL always produces a NULL value unless otherwise indicated in the documentation for the operators and functions involved in the expression.
Emphasis mine.
To search for column values that are NULL, you cannot use an expr = NULL test. The following statement returns no rows, because expr = NULL is never true for any expression
Solution
SELECT pid FROM planets WHERE userid IS NULL;
To test for NULL, use the IS NULL and IS NOT NULL operators.
operator IS NULL tests whether a value is NULL.
operator IS NOT NULL tests whether a value is not NULL.
MySQL comparison operators
There's also a <=> operator:
SELECT pid FROM planets WHERE userid <=> NULL
Would work. The nice thing is that <=> can also be used with non-NULL values:
SELECT NULL <=> NULL yields 1.
SELECT 42 <=> 42 yields 1 as well.
See here: https://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html#operator_equal-to
Info from http://w3schools.com/sql/sql_null_values.asp:
1) NULL values represent missing unknown data.
2) By default, a table column can hold NULL values.
3) NULL values are treated differently from other values
4) It is not possible to compare NULL and 0; they are not equivalent.
5) It is not possible to test for NULL values with comparison
operators, such as =, <, or <>.
6) We will have to use the IS NULL and IS NOT NULL operators instead
So in case of your problem:
SELECT pid FROM planets WHERE userid IS NULL
Had the same issue where query:
SELECT * FROM 'column' WHERE 'column' IS NULL;
returned no values.
Seems to be an issue with MyISAM and the same query on the data in InnoDB returned expected results.
Went with:
SELECT * FROM 'column' WHERE 'column' = ' ';
Returned all expected results.
SELECT pid FROM planets WHERE userid is null;
I had the same issue when converting databases from Access to MySQL (using vb.net to communicate with the database).
I needed to assess if a field (field type varchar(1)) was null.
This statement worked for my scenario:
SELECT * FROM [table name] WHERE [field name] = ''