DROP FUNCTION IF EXISTS _prev_month; DELIMITER // create function _prev_month ( _date varchar(8) ) returns VARCHAR(6) begin declare ret varchar(6); declare pmDate datetime; set pmDate = last_day(date_add( _date, interval -1 month)); set ret = concat(substring(pmDate, 1,4),substring(pmDate, 6,2)); RETURN ret; end; // DELIMITER ; select _prev_month('20220101')