Validate Date in MySQL using a custom function


Let us create a custom function to validate date in MySQL −

mysql> set global log_bin_trust_function_creators=1;
Query OK, 0 rows affected (0.03 sec)
mysql> delimiter //
mysql> create function isValidDate(actualDate varchar(255)) returns int
   -> begin
   -> declare flag int;
   -> if (select length(date(actualDate)) IS NOT NULL ) then
   -> set flag = 1;
   -> else
   -> set flag = 0;
   -> end if;
   -> return flag;
   -> end
   -> //
Query OK, 0 rows affected (0.11 sec)
mysql> delimiter ;

Case 1 −

When parameter is null value i.e. the date to be checked isn’t an actual date. Call the function using SELECT statement −

mysql> select isValidDate(NULL);

This will produce the following output i.e. not a date −

+-------------------+
| isValidDate(NULL) |
+-------------------+
| 0                 |
+-------------------+
1 row in set (0.05 sec)

Case 2 −

When parameter is an actual date value. Call the function using SELECT statement −

mysql> select isValidDate('2019-10-21');

This will produce the following output i.e. 1, an actual date −

+---------------------------+
| isValidDate('2019-10-21') |
+---------------------------+
| 1                         |
+---------------------------+
1 row in set (0.00 sec)

Updated on: 07-Apr-2020

808 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements