Making a field empty in mysql for one row - mysql

Assume I have the following in my users table:
id name email
'1', 'foo', 'foo#bar.com'
'2', 'foo2', 'foo2#bar.com'
'3', 'foo3', 'foo3#bar.com'
'4', 'foo4', 'foo4#bar.com'
Question 1)
If I want to delete a column data for one of the fields. Is it safe if I set it to NULL (Please see the following update query in my example); in other words is it safe for all data types in mysql (int, varchar, bit,...) to assign NULL to make it empty?
UPDATE users
SET email = NULL
WHERE id = 3;
The above update query empties email field for user with id 3, but please confim this is the valid solutoin for all datatypes...
Question2)
After making the email field empty for user with id of 3 the following query is returning nothing:
select * from users where email is NULL
Am I doing something wronmg here?
Please let me know if you need more clarification if the question is vague...
Thanks

If NULL is allowed for the column in the table definition, then you can set NULL to any data type. Your code should work. What happens when you run "select * from users" in a command line or use a database manager?

UPDATE users
SET email = ''
WHERE id = 3;

Related

Mysql : Query to update email with unique random value

I need to anonymize emails in DB, so I try to set a query, but I cannot find a way to generate unique random string for each.
What I have so far is :
update candidate set email = (select CONCAT(SUBSTRING(MD5(RAND()) FROM 1 FOR 15) , '#test.fr'));
But obviously the value is not unique, is that possible with a simple query?
I tried solution here : https://harrybailey.com/2015/08/mysql-roughly-random-string-generation-for-updating-rows/ but same result, I got a
Error Code: 1062. Duplicate entry '0417da5fb3d071b9bd10' for key
'email'
You can use UUID
UPDATE `candidate` SET email = CONCAT(MD5(UUID()),'#test.fr');
and if you want exactly 15 characters
UPDATE candidate SET email=CONCAT(SUBSTRING(MD5(UUID()),1,15) , '#test.fr');

Null entering as 0 in the below query

In the below query I am saving into data base an array from multiple select2 options.
Here i have a database table participants with event_id(int, not null), user_id(int, null), p_mail(varchar, null).
When I pass proper id which is in users the data gets saved properly and null will be displayed in p_email column.
But when i pass some varchar values through array, the user_id is saved as 0 which should be NULL and Null is stored in p_email which should store the values.
foreach($resources as $r) {
global $response;
$sql = "INSERT INTO participants(event_id, user_id, p_email)
SELECT $response,
CASE
WHEN EXISTS (SELECT * from users where id = '$r') THEN
'$r'
ELSE NULL
END,
CASE
WHEN EXISTS (SELECT * from users where id = '$r') THEN
NULL
ELSE '$r'
END
FROM users WHERE id = 1;";
$query_result = $conn->query($sql) or die("Failed".$sql);
this is expected where it int is passed it should be stored in user_id column if id exists otherwise if its varchar it should be stored in p_email.
Present if I store a varchar which is not in users after checking instead of storing it in p_email. it stores null in p_email and 0 in user_id.
I think the issue here is that the id column is numeric. In the first test, you are presumably passing some legitimate numerical string id, such as '123'. MySQL has no issue internally converting between '123', the string, and 123, the number. However, in your second test, you are passing something like abc. In this case, MySQL appears to be converting that to a numeric value of 0. Also, assuming the id zero does exist, you would see NULL in your email column as well.
So, I think the correction here is to just bind numbers to your insert query, assuming the id column is really numeric.
And, you should read about using prepared statements in MySQL.
I cleared this issue by using LIKE instead of '=' in the code.

Pass value between tables with condition MySql

Im looking to make work this statement in MySql, I need to pass the value from table domains column webId only if this value is different than 0, and if so, I need it to copy this value into table customers column referwebId. The below code is giving me error: Unknown table 'domains' in field list..
What is wrong?
Thank you
BEGIN
if domains.webId NOT LIKE '0' then
insert into customers (referWebId) select
webId from domains;
END IF;
END
Why not do something like this
insert into customers (referWebId)
select webId from domains
where webId NOT LIKE '0';
Per your posted code you can't simply check like that way
if domains.webId NOT LIKE '0' then
Rather use INSERT ... ON DUPLICATE KEY UPDATE like below
insert into customers (referWebId)
select webId from domains where webId NOT LIKE '0'
on duplicate key update referWebId = values(referWebId);

Update any of a number of fields in an SQL statement

Is there any way to optionally update any of a number of fields in an SQL statement? I can only get so far as something like:
UPDATE Customer SET
ContactName = ? <=== what to do here if ? is null???
, CompanyName = ? <=== what to do here if ? is null???
, AddressId = ? <=== what to do here if ? is null???
, ...
WHERE CustomerId = ?
It must be a single statement due to a limitation of the wrapper layer and MySQL.
To clarify, I want to create one statement which will be run with one or more non-null values for the fields listed and will update only those fields where the value is not null, leaving the others alone.
This is for a RESTful update API where I don't want a separate statement for every possible combination of fields and I don't want to demand that the API caller supply every single field on the record, which would be unwieldy and would not be future-proof (adding a field breaks existing API calls). And because it's a REST API I am looking to map POST /customer/xxx?ContactName=...&CompanyName=... to update the record.
Not entirely clear on your goal, but I think you're looking for the coalesce feature; it will return the first non-null value:
mysql> SELECT COALESCE(NULL,1); -> 1
mysql> SELECT COALESCE(NULL,NULL,NULL); -> NULL
So you can set a 'default' to use in case the value is null:
UPDATE Customer SET
ContactName = COALESCE(?, <Some default>)
...
If you don't want to change the field, just use the current value:
UPDATE Customer SET
ContactName = COALESCE(?, ContactName)
Usually you would want to use the existing value if the parameter is null in an update:
UPDATE Customer SET
ContactName = COALESCE(?,ContactName)
UPDATE Customer SET
ContactName = ifnull(?,ContactName)
, CompanyName = ifnull(?,CompanyName)
, AddressId = ifnull(?,AddressId)
WHERE CustomerId = ?
SQL Fiddle

MYSQL INSERT - "0 rows inserted". Any suggestions why is that?

INSERT INTO fields (id_region, id_fields_info, subsidy_dka, id_rents_dka, type_uses, id_rented_from, id_categories, id_farmer, id_season)
SELECT
regions.id,
fields_info.id ,
120,
rents_dka.rent_dka,
"собствена",
rented_froms.id,
categories.id_category,
farmers.id,
seasons.id
FROM regions, fields_info, rents_dka, rented_froms, categories, farmers,
seasons
WHERE
region = "Азмък" AND
field_num = 2222 AND
rent_dka = 60 AND
name = "Десислав" AND
id_category = 3 AND
name = "Десислав" AND
season = "2012-2013"
So I have these tables:
regions,
fields_info,
rents_dka,
rented_froms,
categories,
farmers,
seasons
and they are filled with some data.
I've made a form where the user fills the fields with data from these tables, that I've mentioned, and when the submit button is clicked I want to fill table FIELDS in MYSQL with ID's which I get from the data, the user had entered.
to spot the problem, I'd proceed as follow:
execute an insert without cyrillic
remove all the and
make a default insert with default values
if you get "0 rows inserted" it means that the syntax is correct, but the where clause fails to find any matching entry. I suspect the problem is the AND with the cyrillic. Remove the ANDs until the query finds some entries
I got this case when i tried to insert into a table having a column unique and my SQL had the keyword IGNORE in it :
The query:
INSERT IGNORE INTO users SET `user_id` = 7321, `name`= 'test_name', `phone` = '+188888888';
If the query didn't have IGNORE, it would throw an error (because the column user_id was set unique and I already had a row with the same user_id) but due to IGNORE keyword it just ignores the query and hence results in 0 rows inserted.
Note: I know the question asked doesn't has IGNORE key in the query, but might help someone.