Binary data in MySQL - mysql

I need to store binary data, such as 1110000, in MySQL. When I select it, I need the return value to be the same 1110000 again.
What data type should I use? Can I use bit? Or would varbinary be better?

When you're dealing with binary numbers you can use a bit field, e.g.:
bit(64)
is a bit field with up to 64 significant bits (the maximum size allowed).
In order to insert constant values, you can use the b'value' notation like so:
insert into bits values (b'0001001101001');
You can convert a bit field to a number by just adding 0 or using cast(). There's also the handy bin(), hex(), and oct() function to print the value in a particular base.
If non-numeric, varbinary or blob would be the most efficient storage method, binary is also available (it will pad shorter values with nil bytes tho).
In case, you don't want to deal with the conversions, you can store the string in a varchar or char. It will only use up about 8 times the space of a compact varbinary.
To insert/read from your app, you'll need to convert your sequence into a packed byte array, then store the packed string in the varbinary column. In C# you might use BitConverter, for php you might use pack/unpack.

Hope, this code can help you:
for select:
select conv(column_name, from_base, to_base) from table_name
//example:
select conv(column1, 10, 2) from table1;
for insert:
insert into table_name(column1) values( B'binary_data') ;
//example :
insert into table1(column1) values( B'1110000');
for query:
select column1,column2 from table_name where column1 & B('binary_data');
//example:
select column1, column2 from table1 where column1 & B('1110000');

Related

MYSQL, Insert the numeric characters of a string in a column to another column

I am trying to clean the telephone numbers of a database so we can easily search for them. In the column TEL we have rows like:
654-598-5487
654.254.2456
(458)-5458789 e.3
I want to copy all those values to a new column where only the numeric characters are transferred:
6545985487
6542542456
45854587893
The new column (TEL_NO_FORMAT) is a big int and it only allows numbers, but if I execute something like this:
UPDATE CLIENTS set `TEL_NO_FORMAT` = `TEL`
It will only transfer the first numeric characters found and ignore the rest:
654
654
NULL
Easiest way is the REGEXP_REPLACE(MySQL 8.0+):
SELECT *, REGEXP_REPLACE(tel_no_format, '[^0-9]','') AS result
FROM clients
Answering the question in an update query
UPDATE CLIENTS SET TEL_NO_FORMAT = REGEXP_REPLACE(TEL, '[^0-9]','');
You should replace the undesired char before
UPDATE CLIENTS set `TEL_NO_FORMAT` = replace(replace(replace(`TEL`, '.',''),'-',''),')','')
because some char (eg '-') are create problem during conversion ..
anyway rember that a big int can't manage properly eventual tel number 0 prefixed eg:
00453778988

Why * is Inserted in SQL

This happened when I was just testing.
I've created a table as
Create Table Test_Table
(
Field_char char(1)
);
When I want to insert value with code
Insert Into Test_Table(Field_char)
Select 13;
It inserts '*' in the column. For single digits it inserts them as it is. If the length is modified from 1 to 2, similar thing happen for 3 digits input such as 100 etc.
Why is this?
In your create statement you set the length of Field_char to 1 (char(1)). This means that your entries must have a length smaller or equal to 1. valid entries are 1,2 etc. Invalid entries are 12, 13 as they are longer than 1 char -> * is a placeholder to indicate invalid values.
EDIT: (Thanks To Vladimir)
To be more precise take a look here.
Truncating and Rounding Results
[...] Conversions to char, varchar, nchar, nvarchar, binary, and varbinary are truncated, except for the conversions shown in the following table.
There we have the following entry:
From data type int to data type char result *
where * = Result length too short to display
When you are writing
Insert Into Test_Table(Field_char)
Select 13;
The it is converting int to char. So your 13 is converted into *. If you want you can check by writing
select CONVERT(char(1),13)
If you want to see the result as 13 then you need to put that in single inverted comma like this:
Insert Into Test_Table(Field_char)
Select '13';
And also you need to increase the size of column as char(1) can hold only one character.
SQL FIDDLE DEMO
It simply Convert Int to Char
for Example
select CONVERT(char(1),13)
it will give *
Sql Implicitly convert int to char which is you column type..

Converting VARCHAR to DECIMAL values in MySql

I have imported a CSV file that contains string values (eg.eating) and floating values (eg. 0.87) into a table in my phpMyAdmin database. After I get ride of all the string values and retain only the rows that have the decimal values, I need to convert such values from VARCHAR to DECIMAL/FLOAT so that I can perform a MAX() on this attribute.
How do I do this? Each time I try doing this through the GUI in phpMyAdmin, all my values are automatically rounded off to 0 and 1s.
Please help me!
Without Converting you can find Maximum using this query
select max(cast(stuff as decimal(5,2))) as mySum from test;
check this SQLfiddle
your demo table:
create table test (
name varchar(15),
stuff varchar(10)
);
insert into test (name, stuff) values ('one','32.43');
insert into test (name, stuff) values ('two','43.33');
insert into test (name, stuff) values ('three','23.22');
Your Query:
For SQL Server, you can use:
select max(cast(stuff as decimal(5,2))) as mySum from test;
Be aware that if you convert from VARCHAR to DECIMAL and do not specify a precicision and maximum number of digits (i.e. DECIMAL instead of DECIMAL(5,2)) MySQL will automatically round your decimals to integer values.
I think you need to try doing something like this on your MySQL if you have admin privilege on your MySQL.
ALTER TABLE tablename MODIFY columnname DECIMAL(M,D)
for the M,D variables, read this - http://dev.mysql.com/doc/refman/5.0/en/fixed-point-types.html
And MySQL should be able to automatically converting a text to a numeric. Just that the data type in MySQL might not be a decimal yet that's why you can't store any decimal.
Hope it may help someone
select convert( if( listPrice REGEXP '^[0-9]+$', listPrice, '0' ), DECIMAL(15, 3) ) from MyProduct WHERE 1

MySQL random string longer than 32 characters

I am trying to generate a 36 character random string in MySQL using:
UPDATE my_table SET entity_uid = substring(MD5(RAND()) FROM 1 FOR 36);
but the result is always a 32 character string. Is there a way to get a longer string?
One option would be to generate two MD5 hashes, concatenate them together (for a total of 64 hex characters), and then take the first 36 characters of that:
SELECT SUBSTR(CONCAT(MD5(RAND()),MD5(RAND())),1,36)
(NOTE: an MD5 hash is 128-bits; the MySQL MD5() function returns 32 hex characters.)
If you use MySQL with version higher than 5.7.4, you can use the newly added RANDOM_BYTES function:
SELECT TO_BASE64(RANDOM_BYTES(40));
This will result in a random string such as r633j3sfgE85f3Jz+3AEx6Xo6qPXPUZruNimhId18iy+J1qOgZyCgg==.
UPDATE my_table SET entity_uid = UUID();
MD5 Returns the hash as a 32-character hexadecimal number.
According to MySQL
Calculates an MD5 128-bit checksum for the string. The value is
returned as a string of 32 hex digits, or NULL if the argument was
NULL. The return value can, for example, be used as a hash key. See
the notes at the beginning of this section about storing hash values
efficiently.

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
)