MySQL random string longer than 32 characters - mysql

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.

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..

MySQL update query to prepend digit to existing column with integers values

I have a mysql database column named like telephoneNo
Telephone No
25645656
45454545
45565656
I want to prepend two digits XX to every value of telephoneNo column
Telephone No
xx25645656
xx45454545
xx45565656
I was trying to workout with concat but its not with integer values in my case please help with update query
You can use CAST() to convert your integers explicitely:
UPDATE t SET phone=CAST(CONCAT('10', phone) AS UNSIGNED)
That will work with integer prefixes. However, I don't see solid reason to store phone numbers as integers and not strings
That's a hack change your col to varchar or something.
UPDATE table SET telephoneNo=9200000000+telephoneNo;
EDIT:
This method requires that all your numbers are of the same length, and 8 digits long, if all your numbers are more or less than 8 digits modify the number of 0's after the 92 accordingly
If your telephone column is int, you can use concat string function to concat with int or string even like below
SELECT CONCAT(xx, telephone);
(OR)
SELECT CONCAT('xx', telephone);
(OR)
Explicitly cast your int column value
SELECT CONCAT('xx', CAST(telephone AS CHAR));

Querying a string from int column?

I have a table:
CREATE TABLE `ids` (
id int(11) not null auto_increment,
PRIMARY KEY (id)
);
It contains some IDs: 111, 112, 113, 114 etc.
I made a query:
SELECT * FROM `ids` WHERE id = '112abcdefg'
I expected nothing but I've got a result, a row with ID of 112. Seems that MySQL quietly converted my string to integer and then compared it against column values.
How can I change the query so that querying the same string from id column will give no results as I expect? Is there a strict comparison modifier in MySQL?
One option is to CAST the 112 to CHAR to get a proper match:
WHERE CAST(id AS CHAR(12)) = '112abcdefg'
The 12 in CHAR is a guess; it should be large enough for your biggest id.
That will probably kill any chance of optimization, so another option (though one I'm not 100% sure of) is to use a BINARY comparison. I've tried this with a few different values and it works:
WHERE BINARY id = '112abcdefg'
You are comparing a string, just put the number with no quotes:
SELECT * FROM `ids` WHERE id = 112
If you dont, it will convert the string '112abcdefg' to a number and say its 112
The response you are seeing is because you are trying to compare an integer column to a string value. In that case, MySQL will type-cast the string literal value to an integer, and when it does that it starts from the left of the string and as soon as it reaches a character that cannot be considered part of a number, it strips out everything from that point on. So trying to compare "256abcd" to an integer column will result in actually comparing the number 256.
So your options (or at least a few of them) would be:
Validate the input string in your application code and reject it if it's not an integer (see the ctype_digit function in PHP).
Change the column type for the filename if you want to treat it as a string (e.g. a VARCHAR type).
Cast the column value to a string:
. . . WHERE CAST(Id AS CHAR) = '256aei'
Source
you can use this :
SET sql_mode = STRICT_TRANS_TABLES;
this sets you sql mode to strict checking, and then try firing the query you mentioned.
lame + kills optimization but serves it purpose
SELECT * FROM `ids` WHERE concat(id) = '112abcdefg';
that way you enforce casting to string
http://dev.mysql.com/doc/refman/5.1/en/type-conversion.html

Binary data in 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');