CONCAT or REPLACE based on existance of value in MySQL - mysql

I have a simple sql query like below
SELECT REPLACE('TEST ABC XYZ NO JJJG', 'DEF', 'YES')
This will return same string as old one. I want here 'TEST ABC XYZ NO JJJG YES' as out put. If text exists, it should replace the text, else it should be appended at the end of the string.

Assuming column contains 'TEST ABC XYZ NO JJJG', then you could write a query like this:
SELECT
IF(
REPLACE(column, 'DEF', 'YES') = column, -- If the replacement yielded no changes
CONCAT(column, ' ', 'YES'), -- Simply append the text
REPLACE(column, 'DEF', 'YES') -- Otherwise returned the replaced result
) AS replaced_column
EDIT: To your comment (Simply change REPLACE() with INSTR()):
SELECT
IF(
INSTR(column, 'DEF') = column, -- If the column contains the text
REPLACE(column, 'DEF', 'YES'), -- Replace the result
CONCAT(column, ' ', 'YES') -- Otherwise append the text
) AS replaced_column

Related

Why CONCAT does not insert text for the first time into mySQL table?

I am using UPDATE to insert simple text into a table where the field is MEDIUMTEXT (nullable field).
It is strange that it does not work when the field is null initially. If I manually enter at least a one character/space, then it's working.
I want to append the new text into existing text in the field.
UPDATE pen SET
PEN_STATUS = #PenStat,
PEN_STATUS_CHANGE_REASON = CONCAT(PEN_STATUS_CHANGE_REASON,'\n',ChangeDate,':',EmployeeID,':',ChangeReason)
WHERE PEN_ID = PenID;
Why is this?
CONCAT does not handle NULL values. As explained in the MySQL manual:
CONCAT() returns NULL if any argument is NULL.
You want to use COALESCE to handle that use case, like :
UPDATE pen SET
PEN_STATUS = #PenStat,
PEN_STATUS_CHANGE_REASON = CONCAT(
COALESCE(PEN_STATUS_CHANGE_REASON, ''),
'\n',
ChangeDate,
':',
EmployeeID,
':',
ChangeReason
)
WHERE PEN_ID = PenID;
Presumably, because something is NULL. Try using CONCAT_WS() instead:
UPDATE pen
SET PEN_STATUS = #PenStat,
PEN_STATUS_CHANGE_REASON = CONCAT_WS('\n',
PEN_STATUS_CHANGE_REASON,
CONCAT_WS(':', ChangeDate, EmployeeID, ChangeReason
)
)
WHERE PEN_ID = PenID;
CONCAT_WS() ignores NULL arguments. Plus, the separator only needs to be listed once.

MysQL Update if a count condition is met

I have a table which consists of 5000 rows. I need SQL command that could update each row by removing all values in "(...)" if only one couple of () is found.
Basically, if I have a name in a row:
Name surname (extra info)
I need to remove "(extra info)" and leave only Name surname
But if there is no additional couple of ()
If there is a row
Name Surname(data) (extra info)
The script should not amend this name
In simple words, I need to update a name where is only one ( or ) symbol
Many thanks
can you try to find first '(' and substring to it ?
don't forget to use case for none ( in string
update userlogin
set fullname = case position('(' in FullName)
when 0
then fullname
else substring(Fullname,1,position('(' in FullName) - 1)
end
This is an implementation of my question. I used select to let me check the result before applying it to update request. The script shows a table of
3 columns: Id, Name, UpdatedName, where Name is what we have and UpdatedName what we will obtain
SELECT `Id`,`Name`,
(case when ((LENGTH(`Name`)-LENGTH(REPLACE(`Name`, '(', ''))) = 1)
THEN
SUBSTRING_INDEX(`Name`, '(', 1)
ELSE
'-'
END)
as updated_name,
FROM table
WHERE (LENGTH(`Name`)-LENGTH(REPLACE(`Name`, '(', ''))) = 1
LIMIT 0,1500
P.S. I used Id to allow me to amend values
SELECT CASE
WHEN fname = 'correct' THEN 'your condition'
WHEN sname = 'correct' THEN 'your second condition'
ELSE 'baz'
END AS fullname
FROM `databasetable`
or you can do as like also
CASE
WHEN action = 'update' THEN
UPDATE sometable SET column = value WHERE condition;
WHEN action = 'create' THEN
INSERT INTO sometable (column) VALUES (value);
END CASE

How to replace multiple values in 1 column in mysql SELECT query using REPLACE()?

I have a table with Boolean values (0 and 1 only) that needs to be CSV-ed to a client. I know I can do 1 replace like this:
SELECT REPLACE(email, '%40', '#'),
REPLACE(name,'%20', ' '),
REPLACE(icon_clicked, 1, 'Yes')
FROM myTable
WHERE id > 1000;
This will convert all the values of 1 to 'Yes', but how to do this in a single query for both 1 => Yes and 0 => No so Boolean result is stored in a single column? I tried to do this:
SELECT REPLACE(email, '%40', '#'),
REPLACE(name,'%20', ' '),
REPLACE(icon_clicked, 1, 'Yes'),
REPLACE(icon_clicked, 0, 'No')
FROM myTable
WHERE id > 1000;
But this query created an additional column for the 'No' string replace (so final result had 4 columns, email, name, icon_clicked->yes, icon_clicked->no)
One way is to nest REPLACE:
SELECT REPLACE(REPLACE(icon_clicked, 0, 'No'), 1, 'Yes')), ...
FROM myTable
...
or use CASE WHEN (this will work for most RDBMS comparing to IF function which is MySQL related):
SELECT CASE WHEN icon_clicked THEN 'Yes' ELSE 'No' END, ...
FROM myTable
...
SqlFiddleDemo
EDIT:
There is also one nice way utilizing ELT:
SELECT icon_clicked,
ELT(FIELD(icon_clicked,0,1),'No','Yes'),
ELT(icon_clicked + 1, 'No', 'Yes')
FROM mytable
SqlFiddleDemo2
No need to use nested Replace or Case statement. Try using IF, which is way simpler
SELECT
icon_clicked,
IF(icon_clicked,'Yes','No')
FROM myTable
SQL FIDDLE DEMO

Fetch numbers only from an address column in sql

Actually in my case I need to select street number from a address string, which means if the string is '1234 dummy789 road', I only want to get '1234', not '1234789' Another example is 'Plot 111 dummy 1220' then i want only '111'. and if the string is '111/2 dummy' then i want to get '111/2'
I tried following:
SELECT CASE WHEN substr(address , 1, 1) between '0' and '9'
THEN substr(address , 1, 1)
ELSE 'False'
END as add
from test
<?php
$ab = "1225584454 red 1555 blue";
$result = explode(" ", $ab, 2);
print_r($result);
?>
in this case this will gives you first string in your variable.
Assuming that you have civil number followed by space and street name I would suggest the following:
Put WHERE statement with REGEXP to get those, which start with digit-followed-by-space. And in returned field get only numeric portion with substring.
Something like this:
SELECT SUBSTRING(address, 0, LOCATE(' ', address)) FROM items WHERE `address` REGEXP '^[0-9]+ '>0;
Correction:
SELECT TRIM(LEFT(address, LOCATE(' ', address))) FROM items WHERE `address` REGEXP '^[0-9]+ '>0;

SQL CASE statement with NULL

I have the following query. According to http://dev.mysql.com/doc/refman/5.0/en/case.html, null=null is false, thus the first case row will never occur. What would be an alternative query to accomplish this?
SELECT CASE c1
WHEN NULL THEN CONCAT("Hi",name," Your value is NULL")
WHEN "v1" THEN CONCAT("Hello ",name," The value is ",
CASE c2
WHEN "v11" THEN "bla"
WHEN "v12" THEN "bla bla"
END
,")")
WHEN "v2" THEN CONCAT("Howdy there ",name," Yep, the value is ",
CASE c3
WHEN "v21" THEN "beebop"
WHEN "v22" THEN "bopbee"
END
,")")
END
AS myLabel
FROM mytable
WHERE bla="bla";
So use the where <condition> form of case:
SELECT CASE WHEN c1 is NULL THEN CONCAT('Hi', name, ' Your value is NULL')
WHEN c1 = 'v1'
THEN CONCAT('Hello ', name, ' The value is ',
(CASE WHEN c2 = 'v11' THEN 'bla'
WHEN c2 = 'v12' THEN 'bla bla'
END), ')'
)
WHEN c1 = 'v21
THEN CONCAT('Howdy there ', name, ' Yep, the value is ',
(CASE WHEN c3 = 'v21' THEN 'beebop'
WHEN c3 = 'v22' THEN 'bopbee'
END), ')'
)
END
FROM mytable
WHERE bla = 'bla';
Also, use single quotes for string (and date) constants. Don't use them for anything else, like quoting delimiters.
An alternative would be to use COALESCE to get a default value in case the field is NULL, and then use that default for comparison where you are comparing with NULL in your present your query, like so:
SELECT CASE COALESCE(c1,'')
WHEN '' THEN CONCAT("Hi",name," Your value is NULL")
Of course, '' may be a legitimate value on it's own, in which case you need to use another value as default. Owing to this, I would personally recommend Gordon's solution as the way to go.