3

In Oracle, is there an easy way to perform this in a single query, or is this the correct approach?

SELECT MAX(ID) INTO n_FOO_ID FROM FOO WHERE BAR = n_InputVar and ConditionalFlag IS NULL;

IF n_FOO_ID IS NULL OR n_FOO_ID = 0 THEN
    SELECT MAX(ID) INTO n_FOO_ID FROM FOO WHERE BAR = n_InputVar;
END IF;

What I'm trying to do is get the maximum ID where my condition matches an input variable, but prioritizing rows that don't have a conditional flag.

Most of my database experience is in SQL Server, where I would do something like this:

SELECT TOP 1 ID INTO @FooID FROM FOO WHERE Bar = @InputVar ORDER BY ConditionalFlag, ID DESC

But this doesn't seem to work the same on Oracle, or the more likely...I'm not doing it correctly. Can anyone provide any advice?

Thanks!

1 Answer 1

4

I believe the Oracle equivalent of:

SELECT TOP 1 ID 
INTO @FooID 
FROM FOO 
WHERE Bar = @InputVar ORDER BY ConditionalFlag, ID DESC

is

SELECT ID FROM
( SELECT ID 
  INTO FooID 
  FROM FOO 
  WHERE Bar = InputVar ORDER BY ConditionalFlag, ID DESC
) WHERE ROWNUM = 1;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! That did exactly what I needed it to. I tried something similar, but I had the 'where rownum = 1' on the inner query. I didn't think to try wrapping an outer query around that. Thanks again!

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.