Check for NULL or empty variable in a MySQL stored procedure


To check for NULL or empty variable, use the IF condition. Let us create a stored procedure −

mysql> delimiter //
mysql> create procedure checkingForNullDemo(Name varchar(20))
     begin
     if Name is NULL OR Name='' then
     select 'Adam Smith';
     else
     select Name;
     end if ;
     end
     //
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;

Case 1

When NULL is passed. Call the stored procedure using call command

mysql> call checkingForNullDemo(NULL);

This will produce the following output −

+------------+
| Adam Smith |
+------------+
| Adam Smith |
+------------+
1 row in set (0.00 sec)
Query OK, 0 rows affected, 1 warning (0.00 sec)

Case 2

When a value is passed. Call the stored procedure using the call command

mysql> call checkingForNullDemo('John Doe');

This will produce the following output −

+----------+
| Name     |
+----------+
| John Doe |
+----------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)

Updated on: 25-Feb-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements