How to show a column, but if null show another sql

Asked

Viewed 203 times

3

How to show a column, but if null show another sql as Example a table with the name tasks.

| id  |  nome    |  nome resumido |
+-----+----------+----------------+
| 1   | nome 1   | 1              |
| 2   | nome 2   | 2              |
| 3   | nome 3   | null           |

sql will take the short name, where null is it takes the name for example:

|  id | as nome  |
+-----+----------+
| 1   |  1       |
| 2   |  2       |
| 3   |  nome 3  |

If you can’t do it in sql I’m using the php language

  • 6

    You know the function coalesce?

3 answers

5


As commented in the question itself, it can be done using the COALESCE:

SELECT id, COALESCE(nome_resumido, nome) as nome
FROM nome_tabela

It is also possible to use the IFNULL:

SELECT id, IFNULL(nome_resumido, nome) as nome
FROM nome_tabela

In addition to these, as suggested in another response, it can be done using the CASE:

SELECT id, 
    CASE nome_resumido is null THEN nome
    ELSE nome_resumido END as nome
FROM nome_tabela
  • 1

    I used this and it was very simple and easier, another option I had found was in php code, but in sql got smaller the code.

2

Friend you can use mysql CASE:

SELECT nome, nome_resumido,
  CASE
    WHEN nome_resumido IS NULL OR nome_resumido = '' THEN nome
    ELSE nome_resumido
  END AS Nome
FROM Users;

I hope I helped friend.

0

I’m not sure I understand, but.

Need to use ISNULL/Function Operator.

Select ISNULL(a, b)

b is selected if a for Null.

You can even use WHEN/THEN a Select option, search "BOL better".

Essentially: It is the c switch/case block in SQL.

  • 1

    It’s a little confusing your explanation

Browser other questions tagged

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