Teradata SQL NULLIF expression is used for setting some specific value to NULL. It compares two values and if they match then returns NULL else returns the first value which is passed to it.
Let's create a table which we will use here to demo NULLIF example.
CREATE VOLATILE TABLE TST_CASE ( EMPID INTEGER, NAME VARCHAR(30), YEARS_OF_EXP SMALLINT, SALARY INTEGER ) PRIMARY INDEX (EMPID) ON COMMIT PRESERVE ROWS;
Add some dummy data into the table.
INSERT INTO TST_CASE VALUES(1,'WILLIAM',5,50000); INSERT INTO TST_CASE VALUES(2,'SARA',3,30000); INSERT INTO TST_CASE VALUES(3,'ROBIN',-1,40000); INSERT INTO TST_CASE VALUES(4,'TED',7,70000); INSERT INTO TST_CASE VALUES(5,'LILY',-1,20000);
Preview the data in the table.
SELECT * FROM TST_CASE;
EMPID | NAME | YEARS_OF_EXP | SALARY |
---|---|---|---|
1 | WILLIAM | 5 | 50000 |
2 | SARA | 3 | 30000 |
3 | ROBIN | -1 | 40000 |
4 | TED | 7 | 70000 |
5 | LILY | -1 | 20000 |
Let's apply NULLIF function to change any value which is "-1" to NULL. So in the below example the function will compare value of column "YEARS_OF_EXP" to "-1" and if both the values match then it will convert it to NULL.
SELECT EMPID,NAME, NULLIF(YEARS_OF_EXP,-1) AS YEARS_OF_EXP ,SALARY FROM TST_CASE ORDER BY EMPID;
EMPID | NAME | YEARS_OF_EXP | SALARY |
---|---|---|---|
1 | WILLIAM | 5 | 50000 |
2 | SARA | 3 | 30000 |
3 | ROBIN | NULL | 40000 |
4 | TED | 7 | 70000 |
5 | LILY | NULL | 20000 |
It is similar to having a case statement where you compare two values and if the values are same then return NULL else return the first value.
Used to handle divide by zero scenarios e.g.
select x/nullif(y, 0) ….
returns null if y is zero, rather than a divide by zero exception