Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional selection in SQL?

Tags:

sql

I have the following SQL code:

SELECT eml AS "Email Address"
FROM emailtbl
WHERE DEPT LIKE 'E%'

My issue is that if the department starts in 'F' I must select fax instead of eml. What could I do to select eml if the dept starts with 'E' and select fax if the dept starts in 'F'

Thanks

like image 652
jmasterx Avatar asked Dec 26 '22 20:12

jmasterx


1 Answers

One option is to use a UNION ALL statement

SELECT eml AS "Entity"
FROM   emailtbl
WHERE  DEPT LIKE 'E%'
UNION ALL
SELECT fax AS "Entity"
FROM   emailtbl
WHERE  DEPT LIKE 'F%'

another one is to use a CASEstatement

SELECT CASE WHEN Dept LIKE 'E%' THEN eml ELSE fax END AS "Entity"
FROM   emailtbl
WHERE  DEPT LIKE 'E%' OR DEPT LIKE 'F%'
like image 101
Lieven Keersmaekers Avatar answered Jan 15 '23 22:01

Lieven Keersmaekers