Archive for MySQL

SQL – ifnull() Example, ifnull() function

Saturday, November 28th, 2009

SQL ifnull() function is used find null value in rows and returns value on our condition if null value found in column from database table name, otherwise if column value is not null it will return column value.

SQL ifnull() query example explains how to use ifnull() query in SQL.

Table class_name with all records without desired column name sorting

+---------+-------------+------------+------------+
| Roll_No | Name        | Class_Name | Year_Start |
+---------+-------------+------------+------------+
|       1 | Amit Mishra | B.Science  |       2005 |
|       2 | Robot       | B.Tech     |       2005 |
|       3 | Rohan       | M.Tech     |       2005 |
|       4 | Vivek       | B.Tech     |       2009 |
|       5 | Chander     | B.Science  |       2009 |
|       6 | Deepak      | B.Science  |       2009 |
|       7 | Gagan Deep  | B.Tech     |       NULL |
|       8 | Mohit Garg  | M.Tech     |       NULL |
+---------+-------------+------------+------------+

ifnull() examples

SELECT  Name, Year_Start, IFNULL(Year_Start,0) FROM class_name c;

Output

+-------------+------------+----------------------+
| Name        | Year_Start | IFNULL(Year_Start,0) |
+-------------+------------+----------------------+
| Amit Mishra |       2005 |                 2005 |
| Robot       |       2005 |                 2005 |
| Rohan       |       2005 |                 2005 |
| Vivek       |       2009 |                 2009 |
| Chander     |       2009 |                 2009 |
| Deepak      |       2009 |                 2009 |
| Gagan Deep  |       NULL |                    0 |
| Mohit Garg  |       NULL |                    0 |
+-------------+------------+----------------------+

SELECT  Name, Year_Start, IFNULL(Year_Start,2000) FROM class_name c;

Output

+-------------+------------+-------------------------+
| Name        | Year_Start | IFNULL(Year_Start,2000) |
+-------------+------------+-------------------------+
| Amit Mishra |       2005 |                    2005 |
| Robot       |       2005 |                    2005 |
| Rohan       |       2005 |                    2005 |
| Vivek       |       2009 |                    2009 |
| Chander     |       2009 |                    2009 |
| Deepak      |       2009 |                    2009 |
| Gagan Deep  |       NULL |                    2000 |
| Mohit Garg  |       NULL |                    2000 |
+-------------+------------+-------------------------+