Start dates are stored in a comma-separated string in MySQL. I want a stored function to get the earliest start date from the CSV string
EG:
The string: 2018-04-16,2018-10-08,2018-11-15
The desired result: 2018-04-16
Start dates are stored in a comma-separated string in MySQL. I want a stored function to get the earliest start date from the CSV string
EG:
The string: 2018-04-16,2018-10-08,2018-11-15
The desired result: 2018-04-16
Assuming your date strings always have exactly three dates, then the following should work:
SELECT
LEAST(SUBSTRING_INDEX(dates, ',', 1),
SUBSTRING_INDEX(SUBSTRING_INDEX(dates, ',', -2), ',', 1),
SUBSTRING_INDEX(dates, ',', -1)) AS least_date
FROM yourTable;
2018-04-16
However, your current table has seriously poor design if you are storing dates as CSV strings. Instead, you should be storing each date in a separate record. Then, you could easily use the MIN function, possibly with GROUP BY, to get the answer you need.
This is close. - still some syntax errors:
CREATE FUNCTION min_date_from_csv(str VARCHAR(255))
RETURNS VARCHAR(12)
BEGIN
DECLARE mindate VARCHAR(12);
DECLARE x VARCHAR(12);
SET mindate = 0;
SET x = 0;
IF LOCATE(',',str)>0 THEN
mindate = SUBSTRING(str,0,(LOCATE(',',str)));
str = SUBSTRING(str,(LOCATE(',',str)));
TRIM(LEADING ',' FROM str);
ELSE
mindate = str;
END IF;
WHILE LOCATE(',',str)>0
x = SUBSTRING(str,0,(LOCATE(',',str)));
IF x <= mindate THEN
mindate = x;
END IF;
str = SUBSTRING(str,(LOCATE(',',str)));
TRIM(LEADING ',' FROM str);
END WHILE;
RETURN mindate;