0

I have the following SQL and i want theorder_item_wo_id column to return null if the item does not exist in the nested sql and return the value of a column oi.cop_workorder_id if it does.

How can i accomplish this?

SELECT 
    cop.wo_id,
    CASE
     WHEN EXISTS (SELECT oi.cop_workorder_id 
            FROM oseo_orderitem  oi
            WHERE oi.cop_workorder_id = cop.wo_id) THEN 
            oi.cop_workorder_id
     ELSE null
    END AS order_item_wo_id
FROM oseo_cop_wo cop
where cop.wo_id = '123';

It looks like the oi.cop_workorder_id does not get recognized outside of the nested sql.

ERROR: missing FROM-clause entry for table "oi"

2 Answers 2

4

Unless I am missing something, it seems you are overcomplicating this. Just use a LEFT JOIN:

SELECT 
    cop.wo_id,
    oi.cop_workorder_id AS order_item_wo_id
FROM oseo_cop_wo AS cop
    LEFT JOIN oseo_orderitem AS oi
        ON oi.cop_workorder_id = cop.wo_id
WHERE cop.wo_id = '123';
Sign up to request clarification or add additional context in comments.

1 Comment

dohh! I always over complicate, that's easy. Keeping things simple takes creativity.
1

use can use the COALESCE function. It works similar to Oracle's NVL function. I don't have PostgreSQL available to write and test this, however.

2 Comments

sorry, from the documentation, i don't see how i can use this.
ahhhh, I see, I was a little misdirected by your explanation. Looks like Justin provided the right solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.