I have a MYSQL database with GUID(or UUID) stored as Varchar(36). To improve performance, I want to convert them to Binary(16). For new values I can use something like
INSERT INTO sometable (SOMECOLUMN,UUID) VALUES
("Something",UNHEX([the-uuid]))
But how can I update the existing stored GUID values to Binary(16)?
Got the answer myself.
In case anyone else need it. Here it is
Change the Type of GUID column to VARBINARY to avoid right padding.
ALTER TABLE newtable MODIFY COLUMN id VARBINARY(36) NOT NULL;
Update the existing id data to the BINARY id
UPDATE newtable set id=UNHEX(REPLACE(id,'-',''));
Now change the column datatype to BINARY(16)
ALTER TABLE newtable MODIFY COLUMN id BINARY(16) NOT NULL;
Create a new column:
ALTER TABLE sometable ADD newColumn BINARY(16) AFTER UUID;
Update the table:
UPDATE sometable SET newColumn = UNHEX(UUID);
Drop the old column and rename the new one (if so desired—often best not to rename, so that application code that has not been updated will fail rather than use the table incorrectly):
ALTER TABLE sometable DROP UUID, CHANGE newColumn UUID BINARY(16);
Related
I need to change column type from tinyInt(used as bool) to Varchar, without loosing data.
I have found many answers on stack-overflow but all of them are written in postgres and I have no idea how to rewrite it in Mysql.
Answers for this problem on stack-overflow looks like that:
ALTER TABLE mytabe ALTER mycolumn TYPE VARCHAR(10) USING CASE WHEN mycolumn=0 THEN 'Something' ELSE 'TEST' END;
How would similar logic look like in Mysql?
The syntax you show has no equivalent in MySQL. There's no way to modify values during an ALTER TABLE. An ALTER TABLE in MySQL will only translate values using builtin type casting. That is, an integer will be translated to the string format of that integer value, just it would in a string expression.
For MySQL, here's what you have to do:
Add a new column:
ALTER TABLE mytable ADD COLUMN type2 VARCHAR(10);
Backfill that column:
UPDATE mytable SET type2 = CASE `type` WHEN 0 THEN 'Something' ELSE 'TEST' END;
If the table has millions of rows, you may have to do this in batches.
Drop the old column and optionally rename the new column to the name of the old one:
ALTER TABLE mytable DROP COLUMN `type`, RENAME COLUMN type2 to `type`;
Another approach would be to change the column, allowing integers to convert to the string format of the integer values. Then update the strings as you want.
ALTER TABLE mytable MODIFY COLUMN `type` VARCHAR(10);
UPDATE mytable SET `type` = CASE `type` WHEN '0' THEN 'Something' ELSE 'TEST' END;
Either way, be sure to test this first on another table before trying it on your real table.
I have 50 columns in the MySQL table. I want to sum all these columns and make a new column into the same table (sum50).
This should be stored permanently into the MySQL table whenever I update or insert new data.
I know how to sum up while performing the query but it does not store into the table permanently.
CREATE TRIGGER `name`
AFTER INSERT ON `table`
FOR EACH ROW
UPDATE `table` SET `table`.`coulms` = `table`.`col1`+.... `table`.`col50`+
I am trying the above trigger, but not working.
Should I have a blank column inserted into the table and perform trigger? Which trigger would be correct?
Instead of the trigger, add a generated column to your table:
alter table tablename add(sum50 int generated always as (col1 + col2 + ...) stored);
See a simplified demo.
How can I set my custom value in auto increment column when insert query fire in phpMyAdmin
I want like when I insert a data in MySQL at that time the auto increment column value add with like something ABC001 and next record will be ABC002
It there any way to setup this functionality
This is my table structure
I want new code for every insert query for red mark field
Yes, you can use a TRIGGER like this:
CREATE DEFINER=`root`#`localhost` TRIGGER `setDrinkk` BEFORE INSERT ON `yourTable`
FOR EACH ROW BEGIN
SET NEW.DrinkCode = CONCAT('ABC-', LPAD(NEW.db_id,4,'0'));
END
You'll have to add 2 more fields to the table..One field(eg:drink_text)containing the text 'ABC' and other field (Eg:drink_no) with autoincrement.
Set default value of drink_text as ABC.
Set autoincrement primary key for drink_no
ALTER TABLE tablename AUTO_INCREMENT=101;
Now in insert query you have to concatenate both the fields to drink_code
//your insert query
INSERT INTO tablename( user_id,club_id) VALUES ('xyz','abc');
//drink_code with custom string
UPDATE tablename SET drink_code = concat( drink_text, drink_no ) ;
I need two columns in table that would have same value on insert. Is there any way to do it from database side?
So you want to let one column use the auto_increment feature, but make another column in the same table also have the same value?
I can't think of a reason you would need this feature. Perhaps you could explain what you're trying to accomplish, and I can suggest a different solution?
A trigger won't work for this. It's a chicken-and-egg problem:
You can't change any column's value in an AFTER trigger.
But the auto-increment value isn't set yet when a BEFORE trigger executes.
It also won't work to use a MySQL 5.7 GENERATED column:
CREATE TABLE MyTable (
id INT AUTO_INCREMENT PRIMARY KEY,
why_would_you_want_this INT GENERATED ALWAYS AS (id)
);
ERROR 3109 (HY000): Generated column 'why_would_you_want_this'
cannot refer to auto-increment column.
You can't do it in a single SQL statement. You have to INSERT the row, and then immediately do an UPDATE to set your second column to the same value.
CREATE TABLE MyTable (
id INT AUTO_INCREMENT PRIMARY KEY,
why_would_you_want_this INT
);
INSERT INTO MyTable () VALUES ();
UPDATE MyTable SET why_would_you_want_this = LAST_INSERT_ID()
WHERE id = LAST_INSERT_ID();
You could alternatively generate the ID value using some other mechanism besides AUTO_INCREMENT (for example a Memcached incrementing key). Then you could insert the new value in both columns:
INSERT INTO MyTable (id, why_would_you_want_this) VALUES ($gen_id, $gen_id);
Define a before or after insert trigger and assign the value of the 2nd field in the trigger.
If the 1st field is an auto increment column, then you need to use an after insert trigger. If your application assigns value to the 1st field, then you can use a before insert trigger.
However, I would no necessarily duplicate the value on insert. You can leave the 2nd field as null on insert, which would mean that its value is the same as the 1st field's. The only drawback of this approach is that it may be more difficult to create joins on the 2nd field.
You can do this in one query by using the primary key (assumed to be id) and setting your column (assumed to be columnName):
"INSERT INTO tableName SET `columnName` = (SELECT MAX(x.id) FROM tableName x)+1"
This will not work if you have deleted the most recent primary key row however. To get past this, you can insert into the id as well:
"INSERT INTO tableName SET `columnName` = (SELECT MAX(x.id) FROM tableName x)+1, `id`= (SELECT MAX(x.id) FROM tableName x)+1"
However, this solution has the downside (or upside depending on the case) of reusing primary key values that have already been deleted.
suggested way:
To use the actual auto_increment value, you can do this:
"INSERT INTO tableName SET `columnName` = (SELECT `AUTO_INCREMENT` FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'db_name' AND TABLE_NAME = 'table_name')"
Sources that helped me solve this: Prashant Pimpale's answer
I stored date as a
varchar(256) latin1_swedish_ci
which shows up as: 11/22/2012
Now I wanted to convert the existing data and column to a DATE
What would be the easiest way to do this in SQL
thanks
To be on the safe side I personally would add a new column, Transfer the data and then delete
update `table` set `new_col` = str_to_date( `old_col`, '%m/%d/%Y' ) ;
Check the data is OK before you delete the column.
Edit to convert the existing data use:
STR_TO_DATE(t.datestring, '%d/%m/%Y')
Source: Convert String to Date
You may need to create a temp table to hold your data for conversion:
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
(create_definition,...)
[table_options]
[partition_options]
Then you can truncate the table:
TRUNCATE [TABLE] tbl_name
Then you can alter the column datatype:
ALTER TABLE tablename MODIFY columnname DATE;
Then you can reload from the temp table:
INSERT INTO table
SELECT temptable.column1, temptable.column2 ... temptable.columnN
FROM temptable;
Use the STR_TO_DATE function.
Make a new column that is the correct datatype, move the strings from the old column into the new one with the STR_TO_DATE function, and then delete the old column.
UPDATE table SET new_col = STR_TO_DATE(old_col);
MySQL STR_TO_DATE Reference.