MySQL IF function - WHERE 'field1 > 0' ? 'field2 < field1' : '' - mysql

I need help translating this into a MySQL statement. I need to do something like:
WHERE IF 'field1 > 0' THEN 'field2 < field1'
Right now, I have this MySQL statement, but doesn't work?:
SELECT * FROM `my_table` WHERE IF(field1>0, field2<field1, 1=1) AND field3='1';
Please advise a solution for this. Thank you!

You can achieve this by using logical ANDs and ORs.
WHERE (field1 > 0 AND field2 < field1) OR (field1 <= 0 AND <else part of the statement>)
The <else part of the statement> is the condition that you want to check if field1 is not > 0, unless there is no such a clause, in which case remove the OR and everything after it.

You only want to check field2 < field1 if field1 > 0, so code it that way:
SELECT * FROM `my_table`
WHERE ((field1 > 0 AND field2 < field1) OR field1 <= 0)
AND field3 = '1';

You should be using a case statement:
SELECT * FROM `my_table`
WHERE
field2< CASE WHEN (field1>0) THEN field1 ELSE field2+1 END
AND field3='1';

Related

What is wrong in this query ? I'm getting an error as "select is not valid at this position for this server version, expecting : '(', WITH"

My Query
error: select is not valid at this position for this server version, expecting : '(', WITH
set #prev="SAME";
select `date`, `COL1` , `COL2` ,
if( `COL1`>`COL2` and ( (#prev="SAME") or (#prev="UP") ) ) then
"DOWN", #prev:="DOWN"
else if( `COL1` < `COL2` and ( (#prev="SAME") or (#prev="DOWN") ) ) then
"UP", #prev:="UP"
else
"SAME"
END IF
as 'sign'
from
temp;
You cannot use IF...THEN within a query. You can use IF(condition, truevalue, falsevalue) or CASE WHEN condition THEN value1 WHEN condition2 THEN value2 ELSE something END.
IF...THEN is procedural syntax.
Following is the answer, it worked:
set #prev="SAME";
select date, COL1 , COL2 ,
CASE
WHEN( COL1>COL2 and ( (#prev="SAME") or (#prev="UP") ) )
THEN
#prev:="DOWN"
WHEN( COL1 < COL2 and ( (#prev="SAME") or (#prev="DOWN") ) )
THEN
#prev:="UP"
ELSE "SAME"
END as 'sign'
from
temp;

Using And & OR condition in MySQl With Same Query

How to use the And, OR condition in the same MySQL where query.
SELECT * FROM Table_name
WHERE filed_name = 0 AND (field1 != '' AND field2 ='')
OR (field1 = '' AND field2 != '') AND filed3 = 1;
I want to more than 2 fileds in brackets.
You can include as many conditions as you need within parentheses, but you do need to be careful with OR and you may find it necessary to combine multiple sets of conditions with parentheses. When this happens consistent formatting and use of indents can help you maintain the required logic.
SELECT *
FROM Table_name
WHERE (field_name = 0
AND (field1 != '' AND field2 ='')
)
OR (field3 = 1
AND (field1 = '' AND field2 != '')
)
;
Do note that the query above is a guess; I have assumed you need 2 sets of conditions.
SQL refer to columns (not at fields)
anyway you can use all the columns you need in each where condition
SELECT *
FROM Table_name
WHERE col0 = 0
AND col1 != ''
AND col2 =''
OR (col1 = '' AND col2 != '' AND col3 ='YOUR_VALUE')
AND col3 = 1
OR (col4 = 'your_value4' AND col5> 100 );
the parentheses are needed for change the priority in evalaution of the condition ...

How to check if field is null or empty in MySQL?

I am trying to figure out how to check if a field is NULL or empty. I have this:
SELECT IFNULL(field1, 'empty') as field1 from tablename
I need to add an additional check field1 != "" something like:
SELECT IFNULL(field1, 'empty') OR field1 != "" as field1 from tablename
Any idea how to accomplish this?
Either use
SELECT IF(field1 IS NULL or field1 = '', 'empty', field1) as field1
from tablename
or
SELECT case when field1 IS NULL or field1 = ''
then 'empty'
else field1
end as field1
from tablename
If you only want to check for null and not for empty strings then you can also use ifnull() or coalesce(field1, 'empty'). But that is not suitable for empty strings.
Using nullif does the trick:
SELECT ifnull(nullif(field1,''),'empty') AS field1
FROM tablename;
How it works: nullif is returning NULL if field is an empty string, otherwise returns the field itself. This has both the cases covered (the case when field is NULL and the case when it's an empty string).
Alternatively you can also use CASE for the same:
SELECT CASE WHEN field1 IS NULL OR field1 = ''
THEN 'empty'
ELSE field1 END AS field1
FROM tablename.
You can use the IFNULL function inside the IF. This will be a little shorter, and there will be fewer repetitions of the field name.
SELECT IF(IFNULL(field1, '') = '', 'empty', field1) AS field1
FROM tablename
You can create a function to make this easy.
create function IFEMPTY(s text, defaultValue text)
returns text deterministic
return if(s is null or s = '', defaultValue, s);
Using:
SELECT IFEMPTY(field1, 'empty') as field1
from tablename
By trimming and comparing, we ensure we also take care of empty or tab or space character content in the field.
SELECT
CASE
WHEN LTRIM(RTRIM(col_1))='' or col_1 IS NULL THEN 'Not available'
ELSE col_1
END AS col_alias
FROM
my_table
SELECT * FROM (
SELECT 2 AS RTYPE,V.ID AS VTYPE, DATE_FORMAT(ENTDT, ''%d-%m-%Y'') AS ENTDT,V.NAME AS VOUCHERTYPE,VOUCHERNO,ROUND(IF((DR_CR)>0,(DR_CR),0),0) AS DR ,ROUND(IF((DR_CR)<0,(DR_CR)*-1,0),2) AS CR ,ROUND((dr_cr),2) AS BALAMT, IF(d.narr IS NULL OR d.narr='''',t.narration,d.narr) AS NARRATION
FROM trans_m AS t JOIN trans_dtl AS d ON(t.ID=d.TRANSID)
JOIN acc_head L ON(D.ACC_ID=L.ID)
JOIN VOUCHERTYPE_M AS V ON(T.VOUCHERTYPE=V.ID)
WHERE T.CMPID=',COMPANYID,' AND d.ACC_ID=',LEDGERID ,' AND t.entdt>=''',FROMDATE ,''' AND t.entdt<=''',TODATE ,''' ',VTYPE,'
ORDER BY CAST(ENTDT AS DATE)) AS ta
If you would like to check in PHP , then you should do something like :
$query_s =mysql_query("SELECT YOURROWNAME from `YOURTABLENAME` where name = $name");
$ertom=mysql_fetch_array($query_s);
if ('' !== $ertom['YOURROWNAME']) {
//do your action
echo "It was filled";
} else {
echo "it was empty!";
}

Using if Statement In PHPMyAdmin

ok i want to execute this query in PHPMyAdmin
update dle_post set full_story =concat(full_story ,"[H1]My List[/H1]
[RL1]") where category="283"
but want to add some thing like
if " )" in full_story or in short_story then this will execute
thanks
Add this condition -
...
WHERE
category="283"
AND (LOCATE(' )', full_story) > 0 OR LOCATE(' )', short_story ) > 0)
LIKE this ?
UPDATE dle_post
SET full_story = CONCAT(full_story ,"[H1]My List[/H1] [RL1]")
WHERE category = "283" AND
(full_story LIKE '%)%' OR short_story LIKE '%)%')

Detect if value is number in MySQL

Is there a way to detect if a value is a number in a MySQL query? Such as
SELECT *
FROM myTable
WHERE isANumber(col1) = true
You can use Regular Expression too... it would be like:
SELECT * FROM myTable WHERE col1 REGEXP '^[0-9]+$';
Reference:
http://dev.mysql.com/doc/refman/5.1/en/regexp.html
This should work in most cases.
SELECT * FROM myTable WHERE concat('',col1 * 1) = col1
It doesn't work for non-standard numbers like
1e4
1.2e5
123. (trailing decimal)
If your data is 'test', 'test0', 'test1111', '111test', '111'
To select all records where the data is a simple int:
SELECT *
FROM myTable
WHERE col1 REGEXP '^[0-9]+$';
Result: '111'
(In regex, ^ means begin, and $ means end)
To select all records where an integer or decimal number exists:
SELECT *
FROM myTable
WHERE col1 REGEXP '^[0-9]+\\.?[0-9]*$'; - for 123.12
Result: '111' (same as last example)
Finally, to select all records where number exists, use this:
SELECT *
FROM myTable
WHERE col1 REGEXP '[0-9]+';
Result: 'test0' and 'test1111' and '111test' and '111'
SELECT * FROM myTable
WHERE col1 REGEXP '^[+-]?[0-9]*([0-9]\\.|[0-9]|\\.[0-9])[0-9]*(e[+-]?[0-9]+)?$'
Will also match signed decimals (like -1.2, +0.2, 6., 2e9, 1.2e-10).
Test:
drop table if exists myTable;
create table myTable (col1 varchar(50));
insert into myTable (col1)
values ('00.00'),('+1'),('.123'),('-.23e4'),('12.e-5'),('3.5e+6'),('a'),('e6'),('+e0');
select
col1,
col1 + 0 as casted,
col1 REGEXP '^[+-]?[0-9]*([0-9]\\.|[0-9]|\\.[0-9])[0-9]*(e[+-]?[0-9]+)?$' as isNumeric
from myTable;
Result:
col1 | casted | isNumeric
-------|---------|----------
00.00 | 0 | 1
+1 | 1 | 1
.123 | 0.123 | 1
-.23e4 | -2300 | 1
12.e-5 | 0.00012 | 1
3.5e+6 | 3500000 | 1
a | 0 | 0
e6 | 0 | 0
+e0 | 0 | 0
Demo
Returns numeric rows
I found the solution with following query and works for me:
SELECT * FROM myTable WHERE col1 > 0;
This query return rows having only greater than zero number column that col1
Returns non numeric rows
if you want to check column not numeric try this one with the trick (!col1 > 0):
SELECT * FROM myTable WHERE !col1 > 0;
This answer is similar to Dmitry, but it will allow for decimals as well as positive and negative numbers.
select * from table where col1 REGEXP '^[[:digit:]]+$'
use a UDF (user defined function).
CREATE FUNCTION isnumber(inputValue VARCHAR(50))
RETURNS INT
BEGIN
IF (inputValue REGEXP ('^[0-9]+$'))
THEN
RETURN 1;
ELSE
RETURN 0;
END IF;
END;
Then when you query
select isnumber('383XXXX')
--returns 0
select isnumber('38333434')
--returns 1
select isnumber(mycol) mycol1, col2, colx from tablex;
-- will return 1s and 0s for column mycol1
--you can enhance the function to take decimals, scientific notation , etc...
The advantage of using a UDF is that you can use it on the left or right side of your "where clause" comparison. this greatly simplifies your SQL before being sent to the database:
SELECT * from tablex where isnumber(columnX) = isnumber('UnkownUserInput');
hope this helps.
Another alternative that seems faster than REGEXP on my computer is
SELECT * FROM myTable WHERE col1*0 != col1;
This will select all rows where col1 starts with a numeric value.
Still missing this simple version:
SELECT * FROM myTable WHERE `col1` + 0 = `col1`
(addition should be faster as multiplication)
Or slowest version for further playing:
SELECT *,
CASE WHEN `col1` + 0 = `col1` THEN 1 ELSE 0 END AS `IS_NUMERIC`
FROM `myTable`
HAVING `IS_NUMERIC` = 1
You can use regular expression for the mor detail https://dev.mysql.com/doc/refman/8.0/en/regexp.html
I used this ^([,|.]?[0-9])+$. This is allows handle to the decimal and float number
SELECT
*
FROM
mytable
WHERE
myTextField REGEXP "^([,|.]?[0-9])+$"
I recommend: if your search is simple , you can use `
column*1 = column
` operator interesting :) is work and faster than on fields varchar/char
SELECT * FROM myTable WHERE column*1 = column;
ABC*1 => 0 (NOT EQU **ABC**)
AB15*A => 15 (NOT EQU **AB15**)
15AB => 15 (NOT EQU **15AB**)
15 => 15 (EQUALS TRUE **15**)
SELECT * FROM myTable WHERE sign (col1)!=0
ofcourse sign(0) is zero, but then you could restrict you query to...
SELECT * FROM myTable WHERE sign (col1)!=0 or col1=0
UPDATE: This is not 100% reliable, because "1abc" would return sign of
1, but "ab1c" would return zero... so this could only work for text that does not begins with numbers.
you can do using CAST
SELECT * from tbl where col1 = concat(cast(col1 as decimal), "")
I have found that this works quite well
if(col1/col1= 1,'number',col1) AS myInfo
Try Dividing /1
select if(value/1>0 or value=0,'its a number', 'its not a number') from table