0

Could someone please assist with the below query ?

I have a table like below :

Code        alias   user
--------    -----   -------
7305553     BPP     (null)
8136852     BPP     AYU
8136852     BPP     TKL
7305553     BPFX    (null)
8136848     BPFX    YAO
11903927    CIX     (null)

And I want to retrieve the "Code" value by passing "alias" and "user" values, however when the "user" doesn't match/exist, I'd need the row with the null user. Eg :

select Code from my_table where alias = 'BPP' and user = 'TEST'

should return the 1st line code value (7305553) , as user "TEST" doesn't exist. Is this kind of best-matching behavior possible with some kind of conditional "where" ? (with some kind of case statement?)

2
  • 2
    select Code from my_table where alias = 'BPP' and (user = 'TEST' OR user IS NULL) ORDER by user ASC; Then you get one or two rows. Just adjust the ORDER clause to get the NULL as a second record when you have two ones, so you are sure which one is the NULL. Commented Jul 2, 2019 at 8:32
  • 1
    @AntonMitsev limit it to one also. Commented Jul 2, 2019 at 8:33

3 Answers 3

2

Try this:

SELECT
    CODE
FROM
    MY_TABLE
WHERE
    ALIAS = 'BPP'
    AND (USER = 'TEST' OR USER IS NULL)
    ORDER BY USER NULLS LAST
    FETCH FIRST ROWS ONLY

Cheers!!

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks very much. Best answer I think
0

Retrieve the row if the alias equals 'BPP' and the user equals 'TEST'
OR
The alias equals 'BPP' and the user IS NULL and there is no alias 'BPP' and user 'TEST'

select code from my_table where 
(alias = 'BPP' and user = 'TEST')
or
(alias = 'BPP' and user IS NULL and NOT EXIST (select 'X' from my_table where alias = 'BPP' and user = 'TEST'))

Comments

0

Try CASE in MySQL :

SELECT
    CODE
FROM
    MY_TABLE
WHERE
    ALIAS = 'BPP'
AND 
    CASE 
        WHEN USER != 'TEST' THEN 1=1 
        ELSE USER = 'TEST'
    END;

Hope this help.

4 Comments

thanks for the suggestion, however as per the tag I'm on oracle and not mysql
unfortunately it doesn't : ORA-00905: missing keyword
I already tried it with "END" as well on my side, still same error
Hope, There will be another syntax. I haven't Oracle DB so that i can't check for oracle.

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.