0

Why is this not working?

WITH ids AS (SELECT unique id FROM table1 WHERE cd = :cd AND
                                                yr = :yr)
SELECT NVL(person_id, NULL) FROM table2 WHERE id IN ids

In my actual code, the statement ids is used twice. I made this post to find out how to alias subquery and then use it in WHERE along with IN, as seen above.

I get the error : Warning: oci_execute(): ORA-00904: "IDS": invalid identifier

1
  • NVL(person_id, NULL)? Commented Dec 7, 2013 at 18:37

1 Answer 1

2

The cte is like a subquery, but it's not exactly the same, as your case illustrates. IN accepts a list of values or a subquery.

This should work fine:

SELECT NVL(person_id, NULL) 
FROM table2 
WHERE id IN (SELECT unique id 
             FROM table1 WHERE cd = :cd AND yr = :yr)

Update: You don't need to (can't) alias the subquery used with the IN operator, if you want to use the cte, you need a subquery that references it:

;WITH ids as (SELECT unique id 
              FROM table1 
              WHERE cd = :cd AND  yr = :yr)
SELECT NVL(person_id, NULL) 
FROM table2 WHERE id IN (SELECT * FROM ids)
Sign up to request clarification or add additional context in comments.

2 Comments

I had that originally, but I tried to alias the latter statement as in above. There is a reason I want to alias it, as that statement is twice in my code. I made this post to find out how to alias a subquery and then use that subquery in WHERE. Thank you.
Thank you for explaining that such a feat is not possible. In accordance with Stackoverflow's Friendly Exchange policy, I will upvote your answer by 1 and accept your answer in t - 1 minutes. Thank you ever so much.

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.