I am trying to find the lowest number in two columns of a row in the same table, with the caveat that one of the columns may be null in a particular row. If one of the colum
I've created a function which handles any number of dates, by concatenating them with a separator (CONCAT_WS) as first parameter to the function.
CONCAT_WS
besides dynamic number of parameters, will remove all NULL dates ;)
The function accepts two parameters:
CREATE FUNCTION `min_date`(`dates` TEXT, `delim` VARCHAR(10)) RETURNS DATE NO SQL DETERMINISTIC
BEGIN
DECLARE `result` DATE DEFAULT NULL;
DECLARE `count` TINYINT DEFAULT 0;
DECLARE `temp` DATE DEFAULT NULL;
IF `delim` IS NULL THEN SET `delim` = ','; END IF;
IF `dates` IS NOT NULL AND CHAR_LENGTH(`dates`) > 0 THEN
SET `count` = LENGTH(`dates`) - LENGTH(REPLACE(`dates`, `delim`, SPACE(CHAR_LENGTH(`delim`) - 1)));
WHILE `count` >= 0 DO
SET `temp` = SUBSTRING_INDEX(SUBSTRING_INDEX(`dates`, `delim`, `count` + 1), `delim`, -1);
IF `result` IS NULL OR `result` > `temp` THEN SET `result` = `temp`; END IF;
SET `count` = `count` - 1;
END WHILE;
END IF;
RETURN `result`;
END
Then, you can use in any combination of date fields or as static strings (as long as are valid dates or NULL):
SELECT min_date(CONCAT_WS(',', `date_column_1`, NULL, '2019-03-04', `date_column_2`), ',') AS `min_date`