Convert char(5) to tinyint(4) in mysql - mysql

I'm trying to insert rows from one table to the other. In the first table, the datatype of one column is char(5), but the same column has tinyint(4) datatype in the second table. When i run the insert query, it says
Incorrect integer value: '' for column 'x' at row 258
I cannot alter or modify the datatype now as it violates some constraints. Is there a way to use cast or convert char to tinyint?
Thanks.

You probably want something like this:
INSERT INTO newtable
SELECT CASE WHEN x = '' THEN 0 ELSE x END
FROM oldtable
I'm assuming that you want blanks to turn into zeros? If not, then provide the integer value you want blanks to have.
If there are other exceptions, use more alternatives in the CASE expression.

Related

ALTER COLUMN TYPE from tinyInt to Varchar in Mysql

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.

How to check whether integer contains 0 in MySQL?

Im trying to pull bunch of records from MySQL with condition whether the column value contains 0. If I convert to string and check with contains (%0%), it takes more time to execute.. Is there any short way to check on Integer column? Thank you..
You can probably run a regex on the integer column. Something like below.
SELECT fieldname FROM tablename WHERE fieldname REGEX '[0]';
About the performance, I believe that LIKE is faster than REGEX. But since your LIKE involves string conversion, this would have some difference in execution time
#SriniK You can use either POSITION() or LOCATE() in conjunction with CONVERT() to convert the column value into a string and then find if the string "0" exists within the string. Both of these functions return a positive number greater than 0 indicating the index of the substring within your string and they return a 0 if the string isn't found.
Here's how to create a simple test table to illustrate:
CREATE TABLE `testTable` (`id` INTEGER NOT NULL AUTO_INCREMENT, `someNum` INTEGER, PRIMARY KEY(`id`));
INSERT INTO `testTable` (`someNum`)
VALUES
(1),
(10),
(11),
(100),
(111),
(222),
(210);
And here are two queries illustrating both POSITION() and LOCATE():
SELECT `id`,
`someNum`,
POSITION('0' IN CONVERT(`someNum`, CHAR))
FROM `testTable`
WHERE POSITION('0' IN CONVERT(`someNum`, CHAR)) > 0
;
SELECT `id`,
`someNum`,
LOCATE('0', CONVERT(`someNum`, CHAR))
FROM `testTable`
WHERE LOCATE('0', CONVERT(`someNum`, CHAR)) > 0
;
I have mocked this up on dbfiddle here so you can get a better look at it.
If this doesn't get you what you need or if you don't understand something please leave a comment with details and I'll do what I can to help further. Good luck.

MySql Basic table creation/handing

I'm trying to create a simple table where I insert field and I do some checks in MySql. I've used Microsoft SQL relatively easy. Instead, MySql give evrrytime query errors without even specifying what's going on. Poor MySql software design apart, here's what I'm trying to do:
1 table with 4 fields with an autoincremental autogenerated number to det an ID as primary key
CREATE TABLE `my_db`.`Patients_table` (
`ID_Patient` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`Patient_name` VARCHAR( 200 ) NOT NULL ,
`Recovery_Date` DATETIME NOT NULL ,
`Recovery_count` INT NOT NULL
) ENGINE = MYISAM
a simple stored procedure to insert such fields and check if something exist before inserting:
CREATE PROCEDURE nameInsert(IN nome, IN data)
INSERT INTO Patients_table (Patient_name,Recovery_Date) values (nome,data)
IF (EXISTS (SELECT Recovery_count FROM Tabella_nomi) = 0) THEN
INSERT INTO (Patients_table (Recovery_count)
ELSE
SET Recovery_count = select Recovery_count+1 from Patients_table
END
this seems wrong on many levels and MySQL useless syntax checker does not help.
How can I do this? Thanks.
There seems to be a lot wrong with this block of code. (No offense intended!)
First, Procedures need to be wrapped with BEGIN and END:
CREATE PROCEDURE nameInsert(IN nome, IN data)
BEGIN
...[actually do stuff here]
END
Second, since your table is declared with all fields as NOT NULL, you must insert all fields with an INSERT statement (this includes the Recovery_Date column, and excludes the AUTO_INCREMENT column). You can add DEFAULT CURRENT_TIMESTAMP to the date column if you want it to be set automatically.
INSERT INTO Patients_table (Patient_name,Recovery_Date) values (nome,data)
Third, what exactly is your IF predicate doing?
EXISTS (SELECT Recovery_count FROM Tabella_nomi) = 0
If you want to check if a row exists, don't put the = 0 at the end. Also, Tabella_nomi isn't declared anywhere in that procedure. Also, your SELECT statement should have a WHERE clause, since I'm assuming you want to select a specific row (this is going to select a result set of all recovery_counts).
Fourth, the second INSERT statement seems a little messy. It should look more like the first INSERT, and keep the point I made above in mind.
INSERT INTO (Patients_table (Recovery_count)
Fifth, the ELSE statement
SET Recovery_count = select Recovery_count+1 from Patients_table
Has some problems too. SET is meant for setting variables, not values in rows. I'm not 100% sure what your intent is from this statement, but it looks like you meant to increment the Recovery_count column of a certain row if it already exists. In which case, you meant to do something like this:
UPDATE Patients_table SET Recovery_count = Recovery_count+1 WHERE <conditional predicate>
Where the conditional predicate is something like this:
Patients_name = nome
Try these things, and look at the errors it gives you when you try to execute the CREATE STATEMENT. I bet they're more useful then you think!

MySql insert statement to binary datatype?

I am using MySQL database.
I have one table having column with datatype binary(16).
I need help with the insert statement for this table.
Example:
CREATE TABLE `assignedresource` (
`distid` binary(16) NOT NULL
)
insert into assignedresource values ('9fad5e9e-efdf-b449');
Error : Lookup Error - MySQL Database Error: Data too long for column 'distid' at row 1
How to resolve this issue?
You should remove the hyphens to make the value match the length of the field...
Example:
CREATE TABLE `assignedresource` (
`distid` binary(16) NOT NULL
)
insert into assignedresource values ('9fad5e9eefdfb449');
Also, MySQL standard is to use this notation to denote the string as binary... X'9fad5e9eefdfb449', i.e.
insert into assignedresource values (X'9fad5e9eefdfb449');
Well, assuming that you want to strictly insert a hexadecimal string, first you need to remove the dashes and then "unhex" your string before inserting it into a binary(16) data type column, the code would go like this:
INSERT INTO `assignedresource` VALUES(UNHEX(REPLACE('9fad5e9e-efdf-b449','-','')));
Also... the "usable" data you are inserting is actually 8 bytes after undashing it, so binary(8) would do fine if you plan on not storing the dashes.
You can strip the hyphens and perpend 0x to the value unquoted, like this:
insert into assignedresource values (0x9fad5e9eefdfb449);
As well as, as this (mentioned in other answers):
insert into assignedresource values (X'9fad5e9eefdfb449');
Both are valid notation for a hexadecimal literal.
Your string is 18 char long, change the database
CREATE TABLE `assignedresource` (
`distid` binary(18) NOT NULL
)

Prepend a digit to the beginning of a field

I need to add a "0" before a integer field in a MYSQL table. How do I update those fields so they have a ) added to them? Thanks.
You can't unless you change the column type to string. However you can add the zero when reading the field:
SELECT CONCAT( '0', int_col ) FROM ....
If you want to format the output of all integer values in one column to a fixed column size, say 5, with leading zeroes for small numbers, use an ALTER TABLE statement like:
ALTER TABLE table MODIFY `col` INT(5) ZEROFILL;
Refer to MySQL 5.1 Reference Manual.