MySQL - Adding new column with default value when condition is met - mysql

I have an existing requests table in which I want to add a new column request_type. I want to set the default value of this column to A when a certain column is not null else B. I wrote the following query which shows syntax error for MySQL version 5.7.9 -
alter table requests
add column request_type enum('A','B','C') collate utf8_unicode_ci not null default (case when userid is not null then 'A' else 'B' end)

MySQL does not support expressions for the DEFAULT.
But you can use MySQL 5.7's new feature for GENERATED columns: http://mysqlserverteam.com/generated-columns-in-mysql-5-7-5/
If you're using an older version of MySQL, you'd have to use a trigger to keep the enum column updated according to userid.

Related

set default value to field if empty string is inserted through query

So I have table A which contains a column Z with default value set to string "diverse".
The queries come in from a php script which takes the data from a jqueryAJAX post request.
I would like to have my DB set the respective field of column Z to default value if the query received an empty string for insertion into/update of this column.
I really would like to accomplish this using mysql functionality, without using any more custom coded php logic.
I already read about using WHEN/THEN logic here:
Set default value if empty string is passed MySQL
and here
MySQL update CASE WHEN/THEN/ELSE
but these don't explain how I permanently configure a table/column in a way that it exposes this "default" behavior not just on receiving a NULL value, but also on receiving an empty string.
Besides:
If I set a column to NOT NULL and also add a default value for the column, would the query just fail if I tried to insert a/update to a NULL value, or would the DB instead flip to the default value?
MySQL/MariaDB will put the value to a column you specify in the insert/update-statement. If you do not provide a value, the default (if specified) will be used.
If you want to use the default value even if the insert/update-statement does provide a value (NULL / empty string), you will have to have the logic somewhere. The options are that you put the logic in your application code (PHP) or if you want to do it in MySQL/MariaDB, you can use a trigger to check the new value and act accordingly.
CREATE TRIGGER ins_A BEFORE INSERT ON A
FOR EACH ROW
BEGIN
IF NEW.Z is null or NEW.Z='' THEN
SET NEW.Z = 'diverse';
END IF;
END;
And do the same for UPDATE
Please follow 2 case bellow:
create table Test
(
a varchar(400) not null default 'test',
b varchar(10)
)
collate = utf8mb4_unicode_ci;
Case 1:
INSERT INTO Test (a, b) VALUES (NULL, 'case1');
=> resul: error because column a required not null;
Case 2:
INSERT INTO Test (b) VALUES ('case1');
=> OK, and result of column a = defaul value = test

Change INT Default value of mysql(phpmyadmin) in mysql version 5.7.2

Currently, I have the MySQL 5.6 version. In this version INT type column will take 0 automatically even by default value is none.
Column = question_status, Type= INT, Default= None
Old query : INSERT INTO tbl_question (question_status) VALUES ('');
Above Query will Run Perfectly on my older version.
Now, I have imported the database into a newer version of MySQL 5.7.2
New query : INSERT INTO tbl_question (question_status) VALUES ('');
Above query is same but it says I have to change the default value of column because column datatype is INT.
if I'll change the default value manually to 0 in the newer version. It will run perfectly.
The problem is I have around 100 tables in a database and many INT Type columns so I cant change default value of every column one by one.
You can select all columns having an INT type with this query:
SELECT * FROM information_schema.columns WHERE table_schema = '<YOUR_DB>' data_type = 'INT'
Then it will be easy to write a simple script for a mass alter.

Is it possible to change default value of all table using SQL procedure?

I need to change the default value of sql table fields from 'none' to 'null' where the datatypes are char varchar longtext etc. And I want to keep the default value if its not 'none'. And there are more than 500 tables I need to alter. Is there any way to do so? And should I use PL? Is there any other methods to do so?Thanks in advance.
I assume you want to update the none to NULL and the column is of type varchar
update table_name set column = null where column = 'none';
you need to update schema of table as well, need to set the default value as NULL using alteration.
The code is:
ALTER TABLE 'tablename' ALTER COLUMN 'columnname' SET DEFAULT 'none'
First I selected all tables from database using this query:
$result = mysql_query("SHOW TABLES FROM 'database'";
And selected all columns using a loop:
mysql_fetch_field
Then I run the code: And it worked .Thank you every one who tried to help me.

MySQL ALTER TABLE add column: error at another column

ok, i have people table and try run sql-script with the next command:
ALTER TABLE `people`
ADD COLUMN `name_spelling`
VARCHAR(255) NULL DEFAULT NULL
AFTER `last_name`;
Then I'll get a error:
[22001][1292] Data truncation: Incorrect date value:
'0000-00-00' for column 'birth_date' at row 35
At this row birth_date is NULL, but if I try set some date like 2016-05-05 at this column and row and than set NULL back -- all works is correct at this row, but get error on some next null date.
In addition, not all null date values return error.
Maybe your MySQL has some option such as the NO_ZERO_DATE SQL mode (I think it's not the only mysql config that prevents 0000-00-00 dates). This would prevent you from using 0000-00-00 as a value. It happened to me before that I had a table already created violating that condition. It will not be editable until you change the value or disable what's preventing you to set 0 dates.
For reference :http://dev.mysql.com/doc/refman/5.7/en/sql-mode.html
I ran into this issue once and the fix i had was to to edit mysql.cnf file
Replace : sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'
with this :
sql_mode='STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'
Notice i removed the No_ZEROs in that options.

Set default value to all columns in a database

I am working in a PHP + MySQL application. The application is working fine for me. But when I hosted it in another server, I got a MySQL error:
Error Code: 1364. Field 'field' doesn't have a default value
I know this is a problem with the MySQL version and we should setup default values for all columns. But currently I have more than 100 tables. So I need to set default value to NULL for all columns in all tables that has no default value yet.
I can't make use of the strict mode option, because the server is a shared one. Is it possible to setup in a single step rather than setting for each and every table ? If not possible tell me the easiest way to setup it.
Any help would be greatly appreciated
For anyone else with this problem, it will take a bit of coding to perform automatically, but the following would be how you would do so:
First run the following query:
SELECT table_schema,table_name,column_name,data_type FROM information_schema.columns WHERE IS_NULLABLE='NO' AND column_default is null AND column_key=''
Next, for each row returned from the above query perform the following:
If data_type contains 'int' set default to 0
else if data_type='datetime' set default to '0000-00-00 00:00:00'
else if data_type='date' set default to '0000-00-00'
else if data_type='time' set default to '00:00:00'
else set default to ''
create and run the following query with all [[...]] variables replaced with their proper values:
ALTER TABLE `[[table_schema]]`.`[[table_name]]` ALTER COLUMN `[[column_name]]` SET DEFAULT '[[default]]'
This should replace the default values for all databases, all tables, all columns that are set to be NOT NULL and are not primary keys and have no default value set.
Another solution that i found is like:-
Get all column name put it in array...
Now push values in column array for inserting -- with ZERO value for all those arrays we do not have values.
FOR EXAMPLE:
in a table we have COLUMN
NAME LASTNAME COMPNAME PHONO EMAIL ADDRESS ALTERPERSON ALTERPHONE ALTEREMAIL
Now after migration we see the eeror
Error Code: 1364. Field 'field' doesn't have a default value
if we run a INSERT QUERY LIKE
mysqli_query($con,'insert into table
(NAME,LASTNAME,COMPNAME,PHONO,EMAIL,ADDRESS) values
(NAME,LASTNAME,COMPNAME,PHONO,EMAIL,ADDRESS)')
now it will give error...
So just turn the table
get all the column value from DB.TABLE
put it in an array or do it like one by one using while loop or for loop....
check insert values for each column
put condition if insert value is equal to ZERO or NULL then insert ZERO it will solve all issues.
WHY ZERO --
because it will work for VARCHAR,TEXT,INT,BIGINT and in many Data Types except time or date function and DATE/TIME data type got ZERO values by default...
=============================== Another option...
run a PHP code
get all TABLE NAME
then for each TABLE NAME
get all COLUMN NAME
and run this command as in function under loop
ALTER TABLE DB.TABLEnAME CHANGE columnNAME_A columnNAME_A
VARCHAR(100) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL
DEFAULT NULL;
=======================
And its DONE