How to Write a Conditional in a MySQL Select Statement

How do you write a conditional in a MySQL select statement?

SELECT USER_ID, (CASE USER_ID WHEN 1 THEN 1 ELSE 0 END) as FIRST_USER FROM USER

How do I write a condition within an SQL Select statement

Something like this:

( (pupiltype = 0 and tbl_4.status = 1) or
(pupiltype = 1 and (tbl_4.status = 0 OR tbl_5.ID IS NOT NULL))
)

IF' in 'SELECT' statement - choose output value based on column values

SELECT id, 
IF(type = 'P', amount, amount * -1) as amount
FROM report

See http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html.

Additionally, you could handle when the condition is null. In the case of a null amount:

SELECT id, 
IF(type = 'P', IFNULL(amount,0), IFNULL(amount,0) * -1) as amount
FROM report

The part IFNULL(amount,0) means when amount is not null return amount else return 0.

Using an IF Statement in a MySQL SELECT query

The IF/THEN/ELSE construct you are using is only valid in stored procedures and functions. Your query will need to be restructured because you can't use the IF() function to control the flow of the WHERE clause like this.

The IF() function that can be used in queries is primarily meant to be used in the SELECT portion of the query for selecting different data based on certain conditions, not so much to be used in the WHERE portion of the query:

SELECT IF(JQ.COURSE_ID=0, 'Some Result If True', 'Some Result If False'), OTHER_COLUMNS
FROM ...
WHERE ...

MySQL query with conditional statement?

You could use this simple test:

WHERE (requires = 'privacy-weight' AND privacy-weight = 0) OR requires <> 'privacy-weight' OR requires IS NULL

The first part (requires = 'privacy-weight' AND privacy-weight = 0) prevents the output of:

privacy-weight | requires
-------------------------
1 | privacy-weight

But keeps:

privacy-weight | requires
-------------------------
0 | privacy-weight

While the second part OR requires <> 'privacy-weight' OR requires IS NULL will keep the following ones:

privacy-weight | requires
-------------------------
0 | NULL
1 | NULL
1 | NULL

MySQL Query - SELECT based on condition

SELECT id FROM table WHERE variable=1 OR <condition>

MYSQL syntax - how to use where query with conditional statement in query

Since SUCCESS_LOG is not a real field, you need to use HAVING to check on it.

HAVING `SUCCESS_LOG` LIKE 'NO'

Though, in this query, I would just check your MAIN.PROCESS (again). That would probably be more efficient.

WHERE `MAIN`.`PROCESS` = 0

using conditional where clauses in mysql select statement

This is a single line query.... Try This

SELECT * FROM persons p 
WHERE p.age = case when age = -1 then p.age else age end
and p.class = case when class = -1 then p.class else class end
and p.group = case when group = -1 then p.group else group end


Related Topics



Leave a reply



Submit