Day 4 - CASE and NULL
Day 4 - CASE and NULL
• In simple terms whenever you see a column name next to the CASE keyword it is called as a SIMPLE CASE EXPRESSION
as you are locking the logic to only one column which indicates that all the conditions you will be writing will only be on
that specific column.
• Whenever, you don’t see any column name next to the CASE keyword it is called as SEARCHED CASE EXPRESSION which
indicates that you are not locking the logic only to one column you can give the logic on any column as per your
requirement.
• Consider this employees table.
• As the question above clearly indicates that the salary has to be increased based on JOB_ID. It means I need to write a
query based on the JOB_ID i.e. on the basis of a single column so we can say that we will be writing a SIMPLE CASE
EXPRESSION.
• Consider this employees table.
• As the question above clearly indicates that the salary has to be increased based on JOB_ID and Employee_id.It means I
need to write a query based on the JOB_ID and Employee_id i.e. on the basis of multiple column so we can say that we
will be writing a SEARCHED CASE EXPRESSION.
• NULL, In database context, is the total absence
of a value in a certain field and it means that the
field value is unknown.
NULL
• NULL is not same as ZERO value for a numerical
field, text field or space.
• Below are the list of functions available in MySQL that can help you to deal with NULL.
1. ISNULL
2. IFNULL
3. COALESCE
ISNULL:
Consider the below table where you can see a column by the name commission_pct where you see some values as NULL
and there are some real values present in the column.
Let’s suppose you want to replace these NULL with 0 or some other value given or decided by the business you can make use
of IFNULL function.
When I write the below query you can see that the rows where
it was NULL a new column has been added where the NULL is
showing as zero (as I have written a SELECT statement)
and wherever, there was a value it remained as it is.
Update table_name
Set column_name = ifnull(column_name,0);
COALESCE:
Unlike IFNULL, Coalesce can take multiple arguments. The thing that we need to keep in mind is the datatype of the column as
all the values or arguments that you provide to replace for NULL for the column should be of the same datatype as the
column.