Insert a "-" after third character for whole column in SQL - mysql

I have a column (Name is the header of the column) with 8 character numbers. I am looking for a query to insert a '-' after the third character of every row of data.
For example if I have:
| Name |
|----------|
| 99912345 |
I want to get:
| Name |
|-----------|
| 999-12345 |
I have tried the following:
SELECT INSERT(name, 3, 0, "-");
The database I am using is called temp.Test1 on mySQL

You were close:
SELECT INSERT(name, 4, 0, '-') from mytable
Here is the demo:
DEMO

In MySQL, use substring to divide your value and concat to put it back together.
set #test = 99912345;
select concat(
substring(#test, 1, 3),
'-',
substring(#test, 4)
);
gives 999-12345
Edit: You can also make a virtual column which does this for you, and just retrieve the column in your application.
alter table `test1`
add `formattedName` varchar(9) as (
concat(
substring(`name`, 1, 3),
'-',
substring(`name`, 4)
)
);
select `formattedName` from `test`
See demo

Related

How to replace all the digits before hyphen with a new digit using MySQL? [duplicate]

I have a table called myTable which has a column called col1. This column contains data in this format: (1 or 2 digits)(hyphen)(8 digits).
I want to replace all the data in this column and replace everything before hyphen with 4, so this is an example:
--------------------------------
| old values | New Values |
--------------------------------
| 1-654283568 => 4-654283568 |
| 2-467862833 => 4-467862833 |
| 8-478934293 => 4-478934293 |
| 12-573789475 => 4-573789475 |
| 16-574738575 => 4-574738575 |
--------------------------------
I am using MySQL 5.7.19, I believe REGEXP_REPLACE is available in MySQL Version 8+... not sure how this can be achieved?
You don't need regex; you can use SUBSTRING_INDEX to extract everything after the hyphen and concatenate 4- to that:
UPDATE myTable
SET col1 = CONCAT('4-', SUBSTRING_INDEX(col1, '-', -1))
Demo on dbfiddle
This will work regardless of the number of characters after the hyphen.
Looking to your pattern seem you could avoid regexp
update myTable
set col1 = concat('4-', right(col1,8))
or
update myTable
set col1 = concat('4', right(col1,9))
Try this:
UPDATE testing SET val=REPLACE(val,SUBSTRING(val,1,LOCATE('-',val)),'4-');
Fiddle here :https://www.db-fiddle.com/f/4mU5ctLh8NB9iKSKZF9Ue2/2
Using LOCATE to find '-' position then use SUBSTRING to get only the front part of the '-'.
SELECT CONCAT( #new_prefix, SUBSTRING(old_value FROM LOCATE('-', old_value)) ) AS new_value
UPDATE sourcetable
SET fieldname = CONCAT( '4', SUBSTRING(fieldname FROM LOCATE('-', fieldname)) )
WHERE LOCATE('-', fieldname)
/* AND another conditions */

How to replace a regex pattern in MySQL

I have a table called myTable which has a column called col1. This column contains data in this format: (1 or 2 digits)(hyphen)(8 digits).
I want to replace all the data in this column and replace everything before hyphen with 4, so this is an example:
--------------------------------
| old values | New Values |
--------------------------------
| 1-654283568 => 4-654283568 |
| 2-467862833 => 4-467862833 |
| 8-478934293 => 4-478934293 |
| 12-573789475 => 4-573789475 |
| 16-574738575 => 4-574738575 |
--------------------------------
I am using MySQL 5.7.19, I believe REGEXP_REPLACE is available in MySQL Version 8+... not sure how this can be achieved?
You don't need regex; you can use SUBSTRING_INDEX to extract everything after the hyphen and concatenate 4- to that:
UPDATE myTable
SET col1 = CONCAT('4-', SUBSTRING_INDEX(col1, '-', -1))
Demo on dbfiddle
This will work regardless of the number of characters after the hyphen.
Looking to your pattern seem you could avoid regexp
update myTable
set col1 = concat('4-', right(col1,8))
or
update myTable
set col1 = concat('4', right(col1,9))
Try this:
UPDATE testing SET val=REPLACE(val,SUBSTRING(val,1,LOCATE('-',val)),'4-');
Fiddle here :https://www.db-fiddle.com/f/4mU5ctLh8NB9iKSKZF9Ue2/2
Using LOCATE to find '-' position then use SUBSTRING to get only the front part of the '-'.
SELECT CONCAT( #new_prefix, SUBSTRING(old_value FROM LOCATE('-', old_value)) ) AS new_value
UPDATE sourcetable
SET fieldname = CONCAT( '4', SUBSTRING(fieldname FROM LOCATE('-', fieldname)) )
WHERE LOCATE('-', fieldname)
/* AND another conditions */

MySql search integer range from number with dash

I have table in that I have one field with dash value. Like...
I need to search this with between condition.
For example if I have one value 25 then I need to search the records which include the value 25 like 20-31. In above image there are 6 records which include 25 value. So it should return 6 records.
Please help me in this query ? What would be the query for that ?
You can use MySQL's substring_index() function to easily get the data before and after the dash:
select substring_index(yourcolumn,'-',1) as `lower`, substring_index(yourcolumn,'-',-1) as `upper`
from yourtable
This way you can return the records where a certain value falls between the range:
select * from yourtable
where 25 between substring_index(yourcolumn,'-',1) + 0 and substring_index(yourcolumn,'-',-1) + 0
The + 0 forces MySQL to convert the result of substring_index() to a numeric value before the comparison.
You can use the following solution using SUBSTRING_INDEX:
SELECT *
FROM table_name
WHERE 25 >= CONVERT(SUBSTRING_INDEX(SUBSTRING_INDEX(column_name, '-', 1), '-', -1), UNSIGNED INTEGER)
AND 25 <= CONVERT(SUBSTRING_INDEX(SUBSTRING_INDEX(column_name, '-', 2), '-', -1), UNSIGNED INTEGER)
-- or
SELECT *
FROM table_name
WHERE 25 BETWEEN CONVERT(SUBSTRING_INDEX(SUBSTRING_INDEX(column_name, '-', 1), '-', -1), UNSIGNED INTEGER)
AND CONVERT(SUBSTRING_INDEX(SUBSTRING_INDEX(column_name, '-', 2), '-', -1), UNSIGNED INTEGER)
demo: http://sqlfiddle.com/#!9/4ac7b3/3/0
I recommend you to change your table design. I would split the column using the VARCHAR datatype to two columns using the INTEGER datatype. You can add two new columns with the the following ALTER TABLE commands:
ALTER TABLE table_name ADD colNameA INT;
ALTER TABLE table_name ADD colNameB INT;
To split the values of you current column and update the values to the new columns you can use the following UPDATE command:
UPDATE table_name SET
colNameA = CONVERT(SUBSTRING_INDEX(SUBSTRING_INDEX(column_name, '-', 1), '-', -1), UNSIGNED INTEGER),
colNameB = CONVERT(SUBSTRING_INDEX(SUBSTRING_INDEX(column_name, '-', 2), '-', -1), UNSIGNED INTEGER)
At the end you can remove the VARCHAR column using this ALTER TABLE command:
ALTER TABLE table_name DROP COLUMN col_name
Now you can use the following (simple) query to get the expected results:
SELECT *
FROM table_name
WHERE 25 >= colNameA AND 25 <= colNameB
-- or
SELECT *
FROM table_name
WHERE 25 BETWEEN colNameA AND colNameB
If you want to get values beween 35 and 39, you can use below query,
SELECT
*
FROM
yourtable
WHERE
35 && 39
BETWEEN SUBSTRING_INDEX(tablecolumn, '-', 1) + 0 AND
SUBSTRING_INDEX(tablecolumn, '-', - 1) + 0
I don't know how it possible with MySQL.
But using php it possible to check with range.
For e.g.
// First of all get all record from database.
$search = 10; // Your searching value.
// Loop all rows.
while($rows = mysqli_fetch_array($r)){
$explode = explode("-",$rows['dash']); // For get from-to value.
$range = isset($explode[0])&&isset($explode[1])?range($explode[0],($explode[1]-1)):array(); // For get range.
if(in_array($search,$range)){ // For check searching value is exist or not !
echo "Yes ! I get into ".$rows['dash']; // Do stuff.
}
}
Note: If 10-15 then it will check with 10,11,12,13,14.
According to me if you dont want to change the table structure then,
Just fetch the records as per your other condition, Then from that data check your amount between that field using foreach loop and explode. like
If you have $data as all data
foreach($data as $value){
$new_val=explode(',',$value['new_field']);
if(25 >= $new_val[0] && 25 <= $new_val[1]){
// here create new array
}
}

How to split the string in one column into two columns

I have a table like this
id value
------- ---------------
1 ind.kolkatta
2 ind.pune
3 ind.mumbai
4 pak.lahore
5 pak.karachi
6 uae.sharjah
I want to return the following table:
id contry place
------- --------- ----------
1 ind kolkatta
2 ind pune
3 ind mumbai
4 pak lahore
5 pak karachi
6 uae sharjah
how can i do that using MSSQL.? I have already done in MYSQL using SUBSTRING_INDEX function
My MySql query
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(`value`, '.', 1), '.', -1) as contry,
SUBSTRING_INDEX(SUBSTRING_INDEX(`value`, '.', 2), '.', -1) as place
FROM `table`
Try following query:-
SELECT ID, SUBSTRING(value, 1, CHARINDEX('.', value)-1) AS contry,
SUBSTRING(value, CHARINDEX(',', value)+1, LEN(value)) AS place
FROM YOUR_TABLE;
This might be helpful to you.
Hope the Below Query helps you.
SELECT id, SUBSTRING(value,1,3) as Country,SUBSTRING(value,4,LEN(value))AS Place FROM TableName
Try this:
SELECT Id,
LEFT(Value, CHARINDEX('.', Value)-1) AS Country,
STUFF(Value, 1, CHARINDEX('.', Value), '') AS Place
FROM Table
As per King King comment I checked the following
SELECT Id,
PARSENAME(value, 2) AS Country,
PARSENAME(Value, 1) AS Place
FROM Table
The above one worked, but I not sure about the version supported (I am using SSMS 2012).
Or just loop and it will parse out how ever many periods you have in your name.
DECLARE #FILE VARCHAR(55) = 'ind.kol.katta.test1.test2.test3.test4'
DECLARE #FILEFUN AS VARCHAR(55) = LEFT(#FILE,CHARINDEX('.',#FILE))
DECLARE #FILENAMEOUTPUT AS TABLE(Name Varchar(55))
WHILE LEN(#FILE) > 0
BEGIN
INSERT INTO #FILENAMEOUTPUT
SELECT REPLACE(#FILEFUN,'.','')
SET #FILE = REPLACE(#FILE,#FILEFUN,'')
SET #FILEFUN = iif(CHARINDEX('.',#FILE)=0,#FILE,LEFT(#FILE,CHARINDEX('.',#FILE)))
END
SELECT * FROM #FILENAMEOUTPUT

MySQL Query: limit result respecting substring count

I have a table like this
ROW ID | CONTENT
------------------------------------------------
test1 | foo, foo, foo
test2 | bar, bar
test3 | foo, foo
test4 | foo, foo, foo, foo
What I want to achieve is query that gives me the rows but limiting it respecting the occurrences of a substring.
Some examples could be:
Limit result to 3 "foo" occurrences -> should return test1
Limit result to 4 "foo" occurrences -> should return test1 and test3
Limit result to 100 "foo" occurrences -> should return test1,test3, test4
Limit result to 7 "foo" occurrences -> should also return test1,test3, test4
Is there any way to do this? Thanks in advance!
P.S. : I should have mentioned that the ',' can be any string without a predictable length.
SQL Fiddle
MySQL 5.5.32 Schema Setup:
CREATE TABLE Table1
(`ROW ID` varchar(5), `CONTENT` varchar(18))
;
INSERT INTO Table1
(`ROW ID`, `CONTENT`)
VALUES
('test1', 'foo, foo, foo'),
('test2', 'bar, bar'),
('test3', 'foo, foo'),
('test4', 'foo, foo, foo, foo')
;
Query 1:
SELECT *
FROM Table1
WHERE ((LENGTH(CONTENT) -
LENGTH(REPLACE(CONTENT, ',', ''))) + 1) < 3
AND SUBSTRING(CONTENT,1,LENGTH('FOO')) = 'FOO'
Results:
| ROW ID | CONTENT |
|--------|----------|
| test3 | foo, foo |
EDIT :
If you are dealing with phrases, it could look like this :
SQL Fiddle
MySQL 5.5.32 Schema Setup:
CREATE TABLE Table1
(`ROW ID` varchar(5), `CONTENT` varchar(48))
;
INSERT INTO Table1
(`ROW ID`, `CONTENT`)
VALUES
('test1', 'foo de foo refe foo'),
('test2', 'bar re bar'),
('test3', 'foo rer ef foo'),
('test4', 'foo rer foo fsdfs foo dfsfe foo')
;
Query 1:
SELECT *
FROM Table1
WHERE (LENGTH(CONCAT(' ',CONTENT,' ')) -
LENGTH(REPLACE(CONCAT(' ',UPPER(CONTENT),' '),
CONCAT(' ','FOO',' '), '')))
/(LENGTH('FOO')+2) < 3 AND
CONCAT(' ',CONTENT,' ') LIKE CONCAT('% ','FOO',' %')
Results:
| ROW ID | CONTENT |
|--------|----------------|
| test3 | foo rer ef foo |
You want to count the number of foos in the list. This is pretty easy:
select t.*
from t
where (char_length(concat(', ', content, ', ')) -
char_length(replace(concat(', ', content, ', '), ', foo, ', '1234567'))
) = 3;
The idea is to replace 'foo' with something that has one fewer character. However, you might want to be careful with 'foobars' and 'barfood' and other strings that could cause a false positive. So, this version just puts the separators at the beginning and end of the string.
Once you have this information, you can do whatever comparisons you would like.
MySQL unfortunately doesn't have any bulit-in function for what you want to do. You need something like SUBSTRING_COUNT, which doesn't exist. What you can do is, based on this answer` calculate that value.
Something like this might work:
SELECT rowid,
(LENGTH(content) - LENGTH(REPLACE(content, 'foo', ''))) / LENGTH('foo') AS cnt
FROM thetable
HAVING cnt > 0 && cnt < 4;
DEMO: http://sqlfiddle.com/#!2/10599/7