MySQL : Selecting alternative field if given field is empty - mysql

I wonder if is it possible to run mysql command which can select an alternative field if the first given field is empty, on the same table.
Example : I have table called "posts" which have "intro" and "content". In the same statement I would like to select as a result "content" if "intro" is empty, but not having both in the result array.
Thanks in advance

You can use IF function:
SELECT IF(LENGTH(intro)>0, intro, content)
FROM posts
Or you can test for NULL if you mean that empty is NULL

Coalesce is what you are looking for.
SELECT COALESCE(intro, content) AS column1
FROM table
Assuming intro is null and not a zero length string.

There two potential ways. When way is with a case statement.
Select case when field1 <> '' then field2 else field1 end
or you you can use coalesce.
select coalesce(field1, field2)

Related

How to select parts of string in MySQL 5.x

I have a varchar(255) field within a source table and the following contents:
50339 My great example
2020002 Next ID but different title
202020 Here we go
Now I am processing the data and do an insert select query on it. From this field I would need the INT number at the beginning of the field. IT IS followed by 2 spaces and a text with var length, this text is what I need as well but for another field. In General I want to to put text and ID in two fields which are now in one.
I tried to grab it like this:
SELECT STATUS REGEXP '^(/d{6,8}) ' FROM products_test WHERE STATUS is not null
But then I learned that in MySQL 5.x there are no regexp within the SELECT statement.
How could I seperate those values within a single select statment, so I can use it in my INSERT SELECT?
From the correct solution of user slaakso, resulted another related problem since somtimes the STATUS field is empty which then results in only one insert, but in case there is a value I split it into two fields. So the count does not match.
My case statement with his solution somehow contains a syntax problem:
CASE STATUS WHEN ''
THEN(
NULL,
NULL
)
ELSE(
cast(STATUS as unsigned),
substring(STATUS, locate(' ', STATUS)+3)
)
END
You can do following. Note that you need to treat the columns separately:
select
if(ifnull(status, '')!='', cast(status as unsigned), null),
if(ifnull(status, '')!='', substring(status, locate(' ', status)+2), null)
from products_test;
See db-fiddle

Two different queries on stimulsoft if variables are filled or not

I'm using the Stimulsoft Design to make reports and I'm using two variables to filter.
So I want to make the datasource to build one SQL statement if filter one is filled and the other is empty and another SQL if filter two is filled and the other is empty, and maybe an else statement...
So it would be something like this:
If filter one is filled and filter two is empty, then make SELECT 1, which is:
SELECT * FROM tableExample WHERE column1 LIKE '%{filter1}%'
If filter two is filled and filter one is empty, then make SELECT 2, which is:
SELECT * FROM tableExample WHERE id = '%{filter2}%'
and ID is a primary key.
Well, can I do that?
Maybe I could check it only using SQL, but I can't figure out how to do this, could someone help me please?
Thank you!
If you are looking for a single query which contains your logic you could try the following:
SELECT *
FROM tableExample
WHERE
(COALESCE(filter2, '') = '' AND COALESCE(filter1, '') <> '' AND
filter1 LIKE '%{filter1}%') OR
(COALESCE(filter1, '') = '' AND COALESCE(filter2, '') <> '' AND
id = '%{filter2}%')
Note, the somewhat ugly COALESCE calls are there because I don't know what you mean by empty. Does this mean NULL, empty string, or both?

How to get a substring of variable size for each row in MySQL?

I have a MySQL table with just a single text type column with lots of information in the same format, starting with a string like this:
Field1 : 1234
Field2 : Something
The column always starts with Field1 and Field2, but the values after each Field are different for each record.
What I need is to get the just the values of what's after Field1 and Field2 (in this case 1234 and Something) on a Query, the value after Field1 is easy because it's always 4 characters long, but the problem is the one after Field2 because it's size varies for each record, what I have so far is this:
SELECT SELECT substring(substring_index(COLUMN,'Field1 : ',-1),1,4) as Field1_value
FROM table
I know after Field2's value there's a line break, so I'll think of considering the \n character to delimit the value I need.
How do I get this substring of variable size for each row?
P.S. Yes the data is horribly structured, I'm not able to change it...
Well, finally I got it (thanks for your contributions everybody), this is the final resulting Query:
select substring(subcolumn, 9,5) as Field1,
substring(subcolumn, 24) as Field2
from (
select substring(COLUMN, 1, locate('\n',COLUMN,15)) as subcolumn
from table
) as X
Knowing the size of the strings "Field1 : " and "Field2 : ", this isolates those 2 strings and their following values from the rest of column's text, and then I use a substring (knowing that the value after Field1 is always 4 characters long helps), and the 15 in the substring is to ensure I look not for the second line break.
Supply a dynamic value as the last parameter of substring():
select
substring(your_column,
length('FieldX : ')+1,
length(your_column) - length('FieldX : ') + 1) as FieldX
from your_table;
This will work for any single-digit X in FieldX.
I think the simplest is:
SELECT SUBSTRING( Column, 10 ) AS Field1_value
FROM table
If the format of the columns is always the same FieldX : then:
SELECT
SUBSTRING(COLUMN, LOCATE(':', COLUMN)+2) as FieldValue
FROM table;
should give you what you need.
ADDED BASED ON CLARIFIED DATA
If you actually have data separated from Field2 value by \n then your query can become:
SELECT
SUBSTRING(COLUMN, LOCATE('Field1 : ', COLUMN)+9, 4) as Field1
SUBSTRING(COLUMN, LOCATE('Field2 : ', COLUMN)+9, LOCATE(CHAR(10), COLUMN) - LOCATE('Field2 : ', COLUMN)+9) as Field2,
SUBSTRING(COLUMN, LOCATE(CHAR(10), COLUMN)+1) as RestOfData
FROM table;
Something still tells me that whatever you return this data into should be able to parse it better.

Select query with IN clause: filling the blanks

I have the following problem with a MySQL query in C#:
Given a list of strings, I want to query the database for any rows that match said strings. The strings are unique in that each string matches no more than one row. Today, my query looks something like this:
SELECT Id FROM SomeTable
WHERE SomeColumn IN("foo", "bar", "baz")
Now, ideally I would like to be able to map the result from the query directly to the list of strings I supplied in the IN clause:
String Returned ID
------------------------------------------
foo 123
bar NULL <-- Missing row filled with NULL
baz 42
This works fine as long as all strings I pass to the query match a row. When one is missing, however, I would like to fill in the blank with a NULL as in the example above.
Is there any way to accomplish this?
Edit: I should probably have pointed out that the solution must scale to a lot of strings. The way I do it right now is that I pass 100 at a time through the IN clause.
You could do this:
SELECT
helper.SomeColumn,
SomeTable.Id
FROM
(
SELECT 'foo' AS SomeColumn
UNION SELECT 'bar'
UNION SELECT 'baz'
) AS helper
LEFT JOIN SomeTable ON SomeTable.SomeColumn = helper.SomeColumn
Of course you can create the helper table (as a temp table) beforehand instead of inline.
Anyway, maybe it is smarter and more efficient to just do the query you have (WHERE SomeColumn IN (...)) and simply figure out the missing rows in your application. You will loop over them anyway, so you will notice.
What you could do is SELECT the set of strings as a result set and then LEFT JOIN on SomeTable.SomeColumn.
Try this:
SELECT Id
FROM (
SELECT "foo" SomeColumn
UNION ALL
SELECT "bar" AS SomeColumn
UNION ALL
SELECT "baz" AS SomeColumn
) b
LEFT JOIN
SomeTable a
ON a.SomeColumn = b.SomeColumn

Dynamically changing the value in a column when it equals a certan value

I have a column of values that print out N/A. Instead of N/A, I'd like to print three dashes. One thing to note is that some of the values in the column are not N/A so I need to print those. Basically I want to substitute the N/A for "---". Can someone please tell me how I can do this?
Thanks
you can try the following. case statement documentation for mysql can be found here.
http://dev.mysql.com/doc/refman/5.0/en/case-statement.html
case
when field = 'N/A' then '---'
else field
end
How about this?
SELECT field1, field2, IF(field3='N/A','---',field3) AS field3 FROM table
Or did I misunderstood your question?
SELECT IF(STRCMP(my_column,'N/A'),my_column,'---')
FROM my_table
This is a revised version of ChssPly76's answer:
SELECT IF(field_name = 'N/A', '---', field_name) AS field_name
FROM table
This should correct the problem where all fields are printing out as --- and you will also have a properly named column in your results.