IF condition inside an Oracle SELECT

Asked

Viewed 13,964 times

1

There are other questions in this context, but I am a layman and do not understand. With this, I need help.

I have a SELECT for searching data in a database ORACLE, but I must make a condition IF within this SELECT.

Example:

I got the following SELECT:

SELECT
CAMPO1, CAMPO2, CAMPO3, CAMPO4, CAMPO5
FROM
TABELA1
WHERE
CAMPO1 = dado1 AND CAMPO2 = dado2

The condition would be like this:

IF CAMPO1 IS NULL, CAMPO1 = CAMPO3

There is the possibility to make this condition within this SELECT? Already researched this, I found some examples, but I could not understand.

If anyone can help me.

  • Armando Marques Sobrinho, I know you’re a duplicate, but as I mentioned, I couldn’t understand and I need help. I have little knowledge in manipulating databases and with this I have some difficulty in understanding.

  • Where CAMPO1 IS NULL AND CAMPO1 = CAMPO3. That’s what you want?

  • Voce can also do this directly within the select field list, type algorithm IF (CAMPO1 == 'NULL' THEN CAMPO1 = CAMPO2) as aliasdoif then you can use this "aliasdoif" field as if it were a normal table field

  • Great, I think this helps me. Thank you very much

  • 1

    Obs : If field1 is NULL any comparison with it and other will ALWAYS give false.

  • Managed to solve your problem?

Show 1 more comment

1 answer

3

In select you can use CASE Ex:

SELECT
     CASE WHEN CAMPO1 IS NULL THEN 'CAMPO1 NULL' 
       ELSE CAMPO1 END AS CAMPO1, 
     CAMPO2, 
     CAMPO3, 
     CAMPO4, 
     CAMPO5
FROM TABELA1
WHERE CAMPO1 = dado1 AND CAMPO2 = dado2

If I understand the question correctly, I think that’s kind of what you want.

Reference: CASE ORACLE

And also has COALESCE, this will return the first non-zero data of the set passed as parameter Ex:

SELECT
     COALESCE(CAMPO1,'CAMPO1 NULL') AS CAMPO1, 
     CAMPO2, 
     CAMPO3, 
     CAMPO4, 
     CAMPO5
 FROM TABELA1
 WHERE CAMPO1 = dado1 AND CAMPO2 = dado2

Reference COALESCE ORACLE

Browser other questions tagged

You are not signed in. Login or sign up in order to post.