Check for NULL or empty variable (MySQL stored procedure) - mysql

Can someone indicate the proper syntax to determine whether a variable is NULL or empty and then take appropriate action to set the variable depending on the result.
I currently have a test for NULL which works fine (part of a MySQL SELECT statement / stored procedure).
IFNULL(#previousTs, '2017-00-04 00:00:01') ts
I want to include (in the same single line) a test for empty (NULL or empty both results in #previousTs being set to 2017-00-04 00:00:01).

You can try like this:
IF(#previousTs IS NULL or #previousTs= '', '2017-00-04 00:00:01', #previousTs )

Related

MySQL don't read second OR condition if the first one is true

I'm trying to make an SQL-statement where I get the parameters from c# code.
The problem is that some of the parameters can be 'null'. But in MySQL I can't properly read WHERE column=NULL and I can only do WHERE column IS NULL.
So I was trying to make the statement like this:
SELECT *
FROM table
WHERE column=param #(param given from C#)
OR column IS param
I thought this would work fine because MySQL shouldn't care about the second condition if the first one is already true (like Python). And it does work when param is null. But there's an error when param is a string because then MySQL reads: WHERE column IS 'string'.
Is there a way to solve this?
You seem to want <=>, the null-safe equality operator:
WHERE column <=> param
Basically, NULL <=> NULL is true, while NULL = NULL is undefined.
Note that you should be properly passing your parameter to the query, using a prepared statement. String 'null' is not the same thing as a null value.

Mysql select query if condition parameter is null then ignore the parameter

I have the following condition (m.idAgent = agent OR agent is null). It simply returns me all agents if i pass null to agent param.
But how can i achieve the same thing in MYSQL.
I.e if i pass null then that part of the where condition should be ignored and only the other conditions which are not null should be considered.
You could use COALESCE as follows:
WHERE COALESCE(agent, m.idAgent) = m.idAgent
This should work because when agent is NULL, it would just be replaced with the RHS of the comparison, and therefore would always pass. I presume that the following is actually what your code looks like:
WHERE COALESCE(?, m.idAgent) = m.idAgent
Here the ? is a placeholder for a value to be bound in the statement.

JSON_SET isn't updating null JSON field in MySQL

I have a nullable JSON MySQL 5.7 field which I am finding almost impossible to get working.
Example query:
UPDATE `json_test` SET `data` = JSON_SET(`data`, '$.a', 1)
If the field data is NULL already, it won't update.
If it's { "a" : 2 }, then it'll update correctly to 1. I need it to set if not set already, which is what JSON_SET is supposed to do.
Any ideas what's happening?
1) An alternative is to check for null and return an valid empty JSON set ({}) to JSON_SET in those situations, so it just puts in the new data.
UPDATE json_test SET data = JSON_SET(IFNULL(data,'{}' ), '$.a', 1)
2) Finally, another option would be for the data specification to have a default value of {}, ex.
`dataJson TEXT DEFAULT '{}',`
I prefer the first option I presented as I like leaving fields NULL until I need them to have data but then I expect them to start packing in the JSON data immediately!
Updating the entire table for that is an overkill and changing the table definition as well.
This should have no noticeable performance impact:
UPDATE `json_test` SET `data` = JSON_SET(COALESCE(`data`,'{}'), '$.a', 1)
Explanation:
JSON_SET needs a full processing of the column in any case, so it will be evaluated for validity, parsed, etc.
The COALESCE changes a NULL field to an empty JSON object, so the json will be valid and the SET will be successful.
You probably won't be able to measure a performance difference.
it's not supposed to work with nulls
Otherwise, a path/value pair for a nonexisting path in the document is
ignored and has no effect.
Now mysql doesn't let you use a subquery on the same table that's being updated, but you could probably stil solve this with an UPDATE JOIN using CASE/WHEN but I am too lazy so I leave you with a two query solution.
UPDATE `json_test` SET `data` = JSON_SET(`data`, '$.a', 1) WHERE data IS NOT NULL;
UPDATE `json_test` SET `data` = JSON_OBJECT('$.a', 1) WHERE data IS NULL;

SQL NULL insertion not working

I'm having some odd SQL problems when inserting new rows into a table. I have set some columns to NULL, as I have with another table in my database. Obviously when no data is passed through on insertion it should enter NULL into the record, however currently it is not.
I have checked all settings in comparison with my other table (which is inserting records as NULL correctly) but can't find the issue. The columns appear as below, in both tables.
`statement_1` varchar(255) DEFAULT NULL,
No data is being pasted through (so not a blank space issue). Can anyone suggest why one table is doing as expected but the other is not?
Using below as the insert statement
$statement_a = "INSERT INTO statements (ucsid, statement_1, statement_2, statement_3, statement_4, statement_5, statement_6, statement_7, statement_8, statement_9, statement_10) VALUES (:ucsid, :statement_1, :statement_2, :statement_3, :statement_4, :statement_5, :statement_6, :statement_7, :statement_8, :statement_9, :statement_10)";
$q_a = $this->db_connection->prepare($statement_a);
$q_a->execute(array(':ucsid'=>$ucsid,
':statement_1'=>$statement_1,
':statement_2'=>$statement_2,
':statement_3'=>$statement_3,
':statement_4'=>$statement_4,
':statement_5'=>$statement_5,
':statement_6'=>$statement_6,
':statement_7'=>$statement_7,
':statement_8'=>$statement_8,
':statement_9'=>$statement_9,
':statement_10'=>$statement_10));
I can not add comments as I am new:
Try a simple INSERT statement using NOT phpmyadmin. Try
http://www.heidisql.com/ OR https://www.mysql.com/products/workbench/
INSERT INTO statements (ucsid) VALUES (123)
INSERT INTO statements (ucsid, statement_1) VALUES (123, NULL)
In both cases the statement_1 should be NULL. Which in your case most likely is not. However that would tell the problem lies in the database table and NOT with php or the php execute method you are using.
Also is the statement_1 field defined as NOT NULL and the default set as NULL? which can not happen.
Try recreating a new database and a new table with no records and than try inserting NULL as values as a test.
Also can you post the SQL of your database and table with Character Set and Collation
I've fixed the issue by ensuring that NULL is passed through the functions if nothing has been inserted by using the following code
if($_POST['statement_1'] == '') { $statement_1 = NULL; } else { $statement_1 = $_POST['statement_1']; }
Here the value passed by the varriable $statement_1 will be ""
Try this query SELECT * FROM my_table WHERE statement_1 ="".You will get rows.
Which means you are assigning some values to $statement_1 else it should be null.
Check your code. Hope this helps

How do you properly update a mysql field with NULL?

How does one properly update a mysql field with a NULL value when using a variable in the sql query?
I have a variable called $timestamp. When it's set to date( Y-m-d h:i:s ) I have to wrap it in quotes because I'm passing a string in my mysql query. When $timestamp is set to NULL, the database query contains '' as the value for $timestamp and the field updates to 0000-00-00 00:00:00. It's important to keep this field as NULL to show that the process has never been run before.
I don't want to use now() because then my sql statement is not in sync with my class variable $timestamp.
I don't want to set $timestamp to 'NULL' because then that variable is not accurate. It's no longer NULL, it's set to a string that contains the word NULL.
What am I missing here?
The correct SQL syntax to set a column to NULL is:
UPDATE Table SET Column = NULL WHERE . . .
(note the lack of quotes around the literal NULL).
Are you performing this UPDATE using SQL or using some kind of framework? If a framework, it should recognize NULL values and pass them to the database correctly for you.
After a lot of research, I've found that this is a well known problem with no good solution if you are writing your sql queries outright.
The correct solution is to use a database abstraction layer like PDO ( for PHP ), or Active Record ( used in frameworks like Codeignitor and Ruby on Rails ).