SQL nullif
Created By: chatGPT
The NULLIF function in SQL is used to compare two expressions. If both expressions are equal, the function returns NULL; otherwise, it returns the first expression. This is particularly useful for preventing divide-by-zero errors or handling optional parameters in queries.
SELECT
NULLIF(column_name, 0) AS result
FROM
table_name;
Consider a scenario where you want to calculate a ratio between two columns but want to avoid division by zero. The NULLIF function can help you achieve this safely by returning NULL when the denominator is zero.
SELECT
numerator,
denominator,
numerator / NULLIF(denominator, 0) AS ratio
FROM
table_name;
In addition to division, NULLIF can also facilitate conditional logic within your queries. For example, if you want to display an alternative value when a column equals a specific value, you can use NULLIF in combination with COALESCE.
SELECT
COALESCE(NULLIF(column_name, 'default_value'), 'alternative_value') AS result
FROM
table_name;
The NULLIF function is simple but very powerful. It helps to keep your data clean and avoids exceptions in your SQL queries, making your applications more robust.
-- Example to handle default values
SELECT
user_id,
username,
NULLIF(is_active, 1) AS is_active_status
FROM
users;