How to adjust phone number to same format? - mysql

I want to extract data from my database, and I wish the when I extract the data all the h/p number all is same format.
sample:
+60161234567
016-1234567
0161234567
To:
+6016-1234567

The following simple code will give you the expected Output.
SELECT
(CASE
WHEN contact_number RLIKE "^[+]([0-9]){10}" THEN CONCAT(SUBSTRING(contact_number,1,5), "-", SUBSTRING(contact_number,6,7))
WHEN contact_number RLIKE "^([0-9]){3}[-]([0-9]){7}" THEN CONCAT("+6",contact_number)
WHEN contact_number RLIKE "^([0-9]){10}" THEN CONCAT("+6",SUBSTRING(contact_number,1,3), "-", SUBSTRING(contact_number,4,7))
ELSE 'Number is not in correct format'
END) AS 'Phone Number'
FROM table_name;
We have to use the regular expression for checking number format. I have done the query based on the number format that you have given. If a different format is there then try corresponding regular expression.
In the query, the 1st case for the number like "+60161234567", the 2nd case for the number like "016-1234567" and Last case for the number like "0161234567".
I have attached my SQLFiddle to this solution. You can check it. Thank you!

You can use concat and substr function to change format of phone number column during extracting data as below:
SELECT CONCAT(SUBSTR( contact_number, 1, 5 ) , "-", SUBSTR( contact_number, 5 ) ) AS phone_no FROM test_table;

Try this:
SELECT CONCAT("+6",SUBSTRING(REPLACE(REPLACE(phone, '+6', ''), '-', ''),1,3), "-", SUBSTRING(REPLACE(REPLACE(phone, '+6', ''), '-', ''),4,7)) FROM `phone`

It seems that an h/p number is a phone number?
This isn't a number, in the data type sense, so it shouldn't be stored as one. Numbers can have math applied to them and represent some finite value. Varchar or char is probably the appropriate data type here. When inserting the data, standardize the way you record the data and fix it in your application before inserting. In the US, phone numbers can be shown as (555) 123-4567 or 555-123-4567 so you could just pick the format — or what I would do is store it as 5551234567 and then format it in the application when displaying it to the user (that way, the user can prefer one format or the other). At the minimum, though, you should standardize the format when inserting the string so that you don't have to deal later with a variety of formats.
For data that already exists, I think your best bet is to fix the whole database. I would use some programming or scripting language that's good at manipulating data to fix it in the database (personally I think Python is a good choice).

Related

Finding exact value in mysql

I'm trying to solve problem how to find exact value from string.
The problem is then searching in Column StringB for the value 1, it finds all rows containing 1. The idea is that if I look for value 1 in StringB it should only find where value is exact.
Using LIKE is not a perfect option since it will take all rows which contains 1, using = also is not a option since it searches for equal value.
Also tried to use INSTR, but it works almost same as LIKE.
Same with Locate.
There is currently stored formats:
number (example: "2" without "")
number. (example: "2." without "")
number.number (example: "2.23.52.12.35" without "")
And they don't change.
This column only stores numbers, no letter or other type of string ONLY numbers (integer type)
Is there any way to strictly search for value?
My database is InnoDB. Thank you for your time.
Try using REGEXP:
SELECT *
FROM yourTable
WHERE CONCAT('.', StringB, '.') REGEXP CONCAT('[.]', '2', '[.]');
Demo
We could also use LIKE instead of REGEXP:
SELECT *
FROM yourTable
WHERE CONCAT('.', StringB, '.') LIKE CONCAT('%.', '2', '.%');
If you do:
where stringB = 1
Then MySQL has to figure out what types to use. By the rules of SQL, it will convert '1.00' to a number -- and they match.
If you do
where stringB = '1'
Then the types do what you intend. And the values are compared as strings.
More: Keep the types consistent. Don't ever depend on implicit conversion.

SQL Query that checks only numeric characters in the database

I am working on a legacy system a client has. Phone numbers are stored in a multitude of ways. Ex:
514-879-9989
514.989.2289
5147899287
The client wants to be able to search the database by phone number.
How could this be achieved without normalizing the data stored in the database? Is this possible?
I am wondering if it is possible to have a query that looks like:
SELECT FROM table WHERE phonenumber LIKE %input%
but that takes into account only the numerical characters in the db?
$sql = "SELECT * FROM tab
WHERE replace(replace(phone, '.', ''), '-', '') like '%". $input ."%'"
Yes you can add more replace according to values in your table, as mentioned by #spencer7593 eg:
$sql = "SELECT * FROM tab
WHERE replace(replace(replace(replace(replace(replace(phone, '.', ''), '-', ''), '+', ''), '(', ''), ')', ''), ' ', '') like '%". $input ."%'"
but I would prefer to cleanup the data before the query.
The approach I would take with this (i.e. not having a "normalized" value with only digits available, and a restriction of not adding an additional column with the normalized value...)
I would take the user input for the search, and add wild cards in strategic locations. For example, if the user provides search input of 3155551212), then I'd run a query that has a predicate equivalent to this:
phonenumber LIKE '%315%555%1212%'
But if I'm not guaranteed that the provided search digits will be a full three digit area code, a three digit exchange (central office) code, and a four digit line number, for a broader search, I'd add wild cards between all of the provided digits, e.g.
phonenumber LIKE '%3%1%5%5%5%5%1%2%1%2%'
This latter approach is less than ideal, because it could potentially provide more matches than aren't intended. Especially if the user is providing fewer than ten digits. For example, consider a phonenumber value:
'+1 (315) 555-7172 ext. 123'
As a demonstration:
SELECT '+1 (315) 555-7172 ext. 123' LIKE '%3%1%5%5%5%5%1%2%1%2%'
, '+1 (315) 555-7172 ext. 123' LIKE '%315%555%1212%'
There's no builtin string function in MySQL that will extract the digit characters from a string.
If you want a function that does that, e.g.
SELECT only_digits_from('+1 (315) 555-7172 ext. 123')
to return
13155557172123
You'd have to create a stored function that does that. I wouldn't attempt doing it inline in the SQL statement, that would require an atrociously long and ugly expression.
This is piece of code i frequently use to clean up the database columns. I have modified to to be fit for your purpose.
Update Table SET Column =
replace
(replace
(replace(column,
'-','',
'.',''),
' ','')
)
WHERE Column is Not Null

How to read the value in a BINARY column in MySQL

I want to add a BINARY(35) column to a table in which values are written whose bits are each assigned to a specific meaning.
i.e. "000110001010..."
1st bit: day 1,
2nd bit: day 2,
etc..
I've found out how to write the value into the table
INSERT INTO MYTABLE VALUES(x'03011...');
but how do I retrieve it from the database?
If I cast the column as a character string, I'll loose everything past the first x'00' (NULL) in the value. In my application, its entirely possible that they'll still be '1's past this.
Because I'm using the C++ connector, I've only its API functions to retrieve the data so I'll need to know the type of the data retrieved. The API does not have a getBinary() function. If any of you can tell me which function to use, I'd really appreciate it.
Got the answer from another Q&A site.
SELECT HEX(mycolumn) FROM MYTABLE;
If anyone wants to read more about this:
Hexidecimal Literals: https://dev.mysql.com/doc/refman/5.7/en/hexadecimal-literals.html
Bit-Field Literals: https://dev.mysql.com/doc/refman/5.7/en/bit-field-literals.html
Substring(cast column as varchar), 1,1)

Extract Only charcters from a String

I have a column value like
lut00006300.txt
sand2a0000300.raw
I need to extract only character data from above given column values. I tried the below query and was able to get the first three characters.
select filesize,
substring(Filename FROM 1 FOR 3) AS Instrument from Collection;
Is there any approach to extract only the characters from the column value leaving the extensions
The results should be :
LUT
SAND2A
I think below query will helps you.
select filesize,Filename from Collection where Filename REGEXP '[:alpha]';
Refer:- http://dev.mysql.com/doc/refman/5.1/en/regexp.html
SELECT
filesize,
UPPER(SUBSTRING_INDEX(SUBSTRING_INDEX(Filename, '.', 1), '0', 1)) AS Instrument
FROM Collection;
This is a dirty solution, since you want to have the 2 in SAND2A.
Read more about the functions here.

MySQL Find similar strings

I have an InnoDB database table of 12 character codes which often need to be entered by a user.
Occasionally, a user will enter the code incorrectly (for example typing a lower case L instead of a 1 etc).
I'm trying to write a query that will find similar codes to the one they have entered but using LIKE '%code%' gives me way too many results, many of which contain only one matching character.
Is there a way to perform a more detailed check?
Edit - Case sensitive not required.
Any advice appreciated.
Thanks.
Have a look at soundex. Commonly misspelled strings have the same soundex code, so you can query for:
where soundex(Code) like soundex(UserInput)
use without wildcard % for that
SELECT `code` FROM table where code LIKE 'user_input'
thi wil also check the space
SELECT 'a' = 'a ', return 1 whereas SELCET 'a' LIKE 'a ' return 0
reference