MySQL IFNULL CONCAT - mysql

I'm working on a query in which I have a column of account numbers, which I've formatted by using a CONCAT statement to make the numbers 1-11111 instead of 11111.
There is a column with prior account numbers, however this value is NULL unless there is actually a prior account number. To try to only format the account numbers if they exist, I did this:
IFNULL(CONCAT(LEFT(a.prior_acct, 1), '-', RIGHT(a.prior_acct, 5)), 0) AS prior_account
Now, this is properly formatting the account numbers that are there, into the 1-11111 format. However the NULL fields are returning with the hypen and not a 0 (equally acceptable would be a blank space).
I tried adding in an extra set of parenthesis around the full concat statement to see if that would take away the hyphen but no luck!
What am I missing? TIA!

Your query should work as it is unless you are actually storing empty string in prior_acct , not NULL.
SELECT IFNULL(CONCAT(LEFT('', 1),'-',RIGHT('', 5)),0); -- outputs -
SELECT IFNULL(CONCAT(LEFT(null, 1),'-',RIGHT(null, 5)),0); --outputs 0
It's not Oracle where empty string and NULL are the same. If you need to treat empty string as null , you need to specify it's explicitly. One way is
IFNULL(CONCAT(
IF(
TRIM(LEFT('', 1))='',NULL, TRIM(LEFT('', 1))
),
'-', RIGHT(a.prior_acct, 5)), 0) AS prior_account

Related

SQL Query on editing a quantity field

I have a dataset where the values are different, and I want to bring them into a single format.The values are stored as varchar
For ex.
1st Case: 1.23.45 should be 123.45
2nd Case: 125.45 should be 125.45
The first one, has two decimals. I want to remove the first decimal only(if there are 2) else let the value be as it is.
How do I do this?
I tried using replace(Qty,'.',''). But this is removing of them.
I think this can do (although I am not 100% sure about corner cases)
SET Qty = SUBSTRING(Qty, 1, LOCATE(Qty, '.') - 1) + SUBSTRING(Qty, LOCATE(Qty, '.') + 1, LENGTH(Qty) - LOCATE(Qty, '.') - 1)
WHERE LENGTH(Qty) - LENGTH(REPLACE(Qty, '.', '')
You can use a regular expression to handle this case.
Assuming there are only two decimals in your string the below query should be able to handle the case.
select (value,'^(\d+)(\.)?(\d+\.\d+)$',concat('$1','$2')) as a
Here we are matching a regular expression pattern and capturing the following
digits before first decimal occurrence in group one
digits before and after last decimal occurrence including the last decimal in group two.
Following that we are concatenating the two captured groups.
Note that the first decimal has been made optional using ? character and hence we are able to handle both type of cases.
Even if there are more than two decimal cases, I believe a properly constructed regular expression should be able to handle it.

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.

MySQL trim multiple 0 of string?

So I have a column of strings in a format like this: '123.123.123.123.123'.
I need to cut the string to the first two numbers like so: '123.123' that way I can GROUP BY the cut string to get the results needed.
I can do this easily by using SUBSTRING_INDEX(Version, '.', 2) however the problem arises when the second number part has multiple 0's therefore giving me duplicate entries in the query.
e.g. (10.00, 10.0) and 10.404, 10.4040 etc.
Is there a way to trim all unwanted zeros off the end of the string?
Note: I can only use straight MySQL or functions in this case.
EDIT:
I can get the desired result by replacing the first instance of '.0', trim the extra zeros and then replace the '.0' back
REPLACE(TRIM(TRAILING '0' FROM REPLACE(SUBSTRING_INDEX(Version, '.', 2), '.0', '^a')), '^a', '.0')
This probably is not the best option performance wise - therefore I will wait for others before accepting my own.
If you are only working with the first two components, then convert the values to a number, say:
cast(substring_index(version, '.', 2) + 0 as decimal(10, 4))
This will give everything with equal numeric values the same representation.
EDIT:
If you want to remove the trailing zeros from the end of the string, you can use this trick:
replace(rtrim(replace(substring_index(version, '.', 2), '0', ' ')), ' ', '0')
This replaces the zeros with spaces, then uses rtrim() and converts them back to zeroes.

Using COALESCE in MySQL

I'm just getting used to MySQL, I've come from a SQL Server background...
This SQL query builds an address how it should in SQL Server, how can I adapt it to use within MySQL. When I run it in SQL Server it displays all the data within each field, when run in MySQL it just shows me the first field.
Why would this be, what should I do different in MySQL?
SELECT COALESCE(House, '') + ' ' + COALESCE(StreetName, '') + ' ' + COALESCE(TownCity, '') + ' ' + COALESCE(Postcode, '') AS Display
FROM MyTable
WHERE Postcode LIKE '%A1 2AB%'
Use the concat() function:
SELECT concat(COALESCE(House, ''), ' ', COALESCE(StreetName, ''), ' ',
COALESCE(TownCity, ''), ' ', COALESCE(Postcode, '')
) AS Display
FROM MyTable
WHERE Postcode LIKE '%A1 2AB%';
You can also do this with concat_ws(). This eliminates the need for all the spaces:
SELECT concat_ws(COALESCE(House, ''), COALESCE(StreetName, ''),
COALESCE(TownCity, ''), COALESCE(Postcode, '')
) AS Display
FROM MyTable
WHERE Postcode LIKE '%A1 2AB%';
What happens in MySQL is that the + does just what you expect: it adds numbers. A string that contains a number is converted to a number automatically, with silent errors for strings that have no numbers. In practice, this means that a string that starts with a non-digit (and non-decimal point) is converted to a 0.
So, house, which presumably usually numeric, is converted to a number just fine. All the other strings are converted to numbers but become zero and the house number is not changed. You would have gotten much different results if your post codes were American-style zip codes (which are typically numeric).
EDIT:
As #fthiella points out, the coalesce() is not necessary for concat_ws(). The two statements would do different things, because NULLs in the original query result in repeated separators. NULLs in the concat_ws() version would have only a single separator (which might be desirable).
However, I would tend to keep the coalesce() anyway. The behavior of concat() and concat_ws() varies in this regard. concat() returns NULL if any of its arguments is NULL. concat_ws() skips NULL arguments after the initial separator. Who can remember that distinction? It sounds like a recipe for confusion in production code. So, I would also use coalesce() even though it is optional.

Mysql - Can you check for both a blank string and 0 in one condition?

I want to check in mysql if a column is either blank, ie '', or 0.
Is there a way to do this with one condition?
Like
WHERE order_id > ''
or
WHERE order_id != ''
Would either of these work, or is there a different solution?
This is more a question of data quality. In a well designed database, there should be a fairly clear-cut difference between '' and 0.
If you're being vague about it, there are quite a lot of values that could be interpreted as "blank" in addition to these two. NULL is the obvious one, but what about white space? Or a string containing 0.00, or even if you're looking for a numeric value, any non-numeric string.
Ideally, the data should be stored in a format that matches the type of data it is supposed to hold - for example, if you're expecting a numeric field, it should be an int, or another numeric type, depending on exactly what you want to store. That way, it can never contain a string value, so you would never need to check for it.
If you can't change the type in the DB itself, the next best solution is to cast the value as that data type you are expecting in the select query. eg:
SELECT CAST(myfield as int) as myfieldnum FROM table where myfieldnum != 0
See the MySQL manual for more info: http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html
However, in the end, it does depend on exactly what you are expecting the data field to contain, and how you want to react to different types of content.
Does this qualify as one condition?
... WHERE order_id IN ('0', '');
I experimented a bit and it seems the answer is:
WHERE order_id != 0
This will show results where order_id is not 0 and also not blank
why dont u use a smiple query where both of ur conditions are going to be tested
select * from tbl_name where order_id=' ' or order_id = 0
try this it will work