Mysql
 SQL >> Database >  >> RDS >> Mysql

4 modi per sostituire NULL con un valore diverso in MySQL

In MySQL, a volte non vuoi che i valori NULL vengano restituiti come NULL. Puoi volerli sostituire con stringhe come N/A, Not Applicable, None oppure con una stringa vuota.

Ecco quattro modi principali:

  • La funzione IFNULL()
  • La funzione COALESCE()
  • La funzione IF() combinata con IS NULL o IS NOT NULL
  • L'espressione CASE combinata con IS NULL o IS NOT NULL

Dati di esempio

USE Solutions; SELECT TaskCode From Tasks;

Risultato:

+----------+
| TaskCode |
+----------+
| gar123   |
| NULL     |
| NULL     |
| dog456   |
| NULL     |
| cat789   |
+----------+

Ci sono tre valori NULL e tre valori non nulli.

IFNULL()

IFNULL() accetta due argomenti: restituisce il primo se non è NULL, altrimenti restituisce il secondo.

SELECT IFNULL(TaskCode, 'N/A') AS Result FROM Tasks;

Risultato:

+--------+
| Result |
+--------+
| gar123 |
| N/A    |
| N/A    |
| dog456 |
| N/A    |
| cat789 |
+--------+

COALESCE()

COALESCE() è simile, ma accetta un numero qualsiasi di argomenti e restituisce il primo valore non NULL.

SELECT COALESCE(TaskCode, 'N/A') AS Result FROM Tasks;

Risultato:

+--------+
| Result |
+--------+
| gar123 |
| N/A    |
| N/A    |
| dog456 |
| N/A    |
| cat789 |
+--------+

Puoi anche concatenare più alternative:

SELECT COALESCE(NULL, TaskCode, 'None', 'N/A') AS Result FROM Tasks;

Risultato:

+--------+
| Result |
+--------+
| gar123 |
| None   |
| None   |
| dog456 |
| None   |
| cat789 |
+--------+

IF() con IS NULL o IS NOT NULL

SELECT IF(TaskCode IS NOT NULL, TaskCode, 'N/A') AS Result FROM Tasks;

Risultato:

+--------+
| Result |
+--------+
| gar123 |
| N/A    |
| N/A    |
| dog456 |
| N/A    |
| cat789 |
+--------+

Puoi anche invertire la condizione:

SELECT IF(TaskCode IS NULL, 'N/A', TaskCode) AS Result FROM Tasks;

CASE con IS NULL o IS NOT NULL

SELECT CASE WHEN TaskCode IS NOT NULL THEN TaskCode ELSE 'N/A' END AS Result FROM Tasks;

Risultato:

+--------+
| Result |
+--------+
| gar123 |
| N/A    |
| N/A    |
| dog456 |
| N/A    |
| cat789 |
+--------+

Anche qui puoi invertire la condizione:

SELECT CASE WHEN TaskCode IS NULL THEN 'N/A' ELSE TaskCode END AS Result FROM Tasks;