Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write a if condition within a select statement?

I have a column which needs to be populated with ture/false/(N/A) data. This column is part of a select statement So, How can i achieve this?

SELECT distinct 
program_id, 
prog_name,
Eitc_Active_Switch as Prog_Status,
progmap.client_id,
progmap.ORG_ID,
sec.calwinexists_ind as interface,
sec.Client_name
FROM ref_programs prog (nolock)
LEFT OUTER JOIN ref_county_program_map progmap (nolock)         
ON progmap.program_id=prog.prog_id AND progmap.CLIENT_ID=prog.CLIENT_ID 
INNER join sec_clients sec (nolock)
on sec.client_id=progmap.Client_id

'sec.calwinexists_ind as interface' is the column. the true/false should be displayed for only three records (AMC, AMBD, ACMNI) and 'N/A' for the rest of the records

Can anyone help me?

like image 408
userstackoverflow Avatar asked Apr 18 '11 22:04

userstackoverflow


People also ask

Can you use an IF statement in a select statement?

This isn't what the requester wanted, but is very useful to know that you can use if statements outside a select statement. EXISTS is good because it kicks out of the search loop if item is found. A COUNT runs until the end of table rows.

How do I add a condition to a query?

To add a condition, create a row in the Query Conditions list for the appropriate field from the Entity List pane. To add an AND condition, select the AND radio button in the Query Conditions title bar and do one of the following: Select an entity from the Entity List pane and select Add Condition from the pop-up menu.

Can you do conditional statements in SQL?

Conditional statements are used to define what logic is to be executed based on the status of some condition being satisfied. There are two types of conditional statements supported in SQL procedures: CASE. IF.


2 Answers

You should use CASE expression.

Example:

SELECT name,salary,
CASE    
WHEN  salary <= 2000 THEN 'low'
WHEN  salary > 2000 AND salary <= 3000 THEN 'average'
WHEN  salary > 3000 THEN 'high'
END AS salary_level
FROM employees
ORDER BY salary ASC

And in this way you should adapt your query to match your needs.

like image 128
Cristian Boariu Avatar answered Oct 22 '22 19:10

Cristian Boariu


Could you use a CASE WHEN control. Take a look at: http://dev.mysql.com/doc/refman/4.1/pt/control-flow-functions.html

like image 27
bruno.zambiazi Avatar answered Oct 22 '22 21:10

bruno.zambiazi