Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

CASE WHEN EXISTS in WHERE clause

I want to print all employee names and also if the employee is present in a table.


|  EMP_ID  | ENAME    |
| -------- | -------- |
|  1       |  ALLEN   |
|  2       |  MAX     |
|  3       |  BEN     |


|  EMP_ID  | EC_CODE   |
| -------- | --------  |
|  1       |  CONFIG_1 |
|  2       |  CONFIG_2 |
|  3       |  CONFIG_1 |



SELECT ename, 
            (CASE WHEN EXISTS (SELECT 1 FROM m_sys.m_emp_config ec WHERE ec_code = 'CONFIG_1' AND emp_id = emp.emp_id) THEN
              'Y' 
             ELSE 
              'N' 
             END ) config
        FROM emp emp

Can we write the CASE WHEN EXISTS in the Where clause instead of there?

I am new with SQL, please help me?

Expected Output for the sql:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ENAME CONFIG
ALLEN Y
MAX N
BEN Y

>Solution :

Your current query is correct for doing this via exists. Here is an alternative version using a left join:

SELECT DISTINCT
    e.ENAME,
    CASE WHEN ec.EMP_ID IS NOT NULL THEN 'Y' ELSE 'N' END AS CONFIG
FROM emp e
LEFT JOIN m_sys.m_emp_config ec
    ON ec.EMP_ID = e.EMP_ID AND
       ec.ec_code = 'CONFIG_1'
ORDER BY e.EMP_ID;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading