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

Return NULL for CTE where records not found

I have this SQL query using a Common Table Expression:

with a as (
    select top 1 flow_id
    from flow
    where invoice_id > 0
), b as (
    select '45' as col2
)
select *
from a, b

if none of the rows satisfy the condition invoice_id>0 in the flow table, then I get the following result:

Zero Results

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

I want the following result even if no records are found from flow table:

NULL if no record

Can this be done?

>Solution :

You can do this:

with a as (
    select top 1 flow_id
    from (values(1,-1)) as flow (flow_id,invoice_id)
    where invoice_id > 0
), b as (
    select '45' as col2
)
select *
from a
right join b on 1 = 1

So, use a right join making sure any row on the right side table is in irrespective of whether a row on the left side is found based on the join condition. In this case, there is no real linking as you did a CROSS JOIN effectively, so the condition is 1=1 to reflect that.

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