SQL NULLIF

SQL NULLIF function is not well known but could be very useful in some cases. It takes 2 parameters: it returns NULL if the 2 parameters are equal, otherwise it returns the value of the first parameter.

SQL NULLIF Function Syntax

NULLIF(expression1, expression2)

SQL NULLIF Function Example

Table: Users

UserId userName screenName
1 Liysheet Liy Sheet
2 Mohisy Mohisy
3 Nuoo Nuhoo
4 Mhquu Mhquu
5 Yuhiaa Uhiooo

Show NULL if userName is equal to screenName, otherwise show userName:

SELECT userId, NULLIF(userName, screenName)
FROM Users

The result will look like:

UserId NULLIF(userName, screenName)
1 Liysheet
2 NULL
3 Nuoo
4 NULL
5 Yuhiaa

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>