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

SQL : instead of using a union want to use a where clause but one of the clauses is only true if another clause is true

I would like to not use a union in my SQL query – how can I rewrite the following query?

select 
    id,
    status,
    date
from 
    table
where 
    status = 'Active'
union
select 
    id,
    status,
    date
from 
    table
where 
    status = 'Cancelled'
    and cancel_reason_id is not null

How can I rewrite this without the union?

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

>Solution :

Use Boolean logic:

select 
    id,
    status,
    date
from table
where status = 'Active'
or (status = 'Cancelled' and cancel_reason_id IS NOT NULL)

If you are combining with other conditions then make sure you have the correct parentheses to make it evaluate properly, e.g.:

select 
    id,
    status,
    date
from table
where
(
  status = 'Active'
  or (status = 'Cancelled' and cancel_reason_id IS NOT NULL)
)
and some_other_condition

… so you aren’t caught out by the condition precedence rules.

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