Skip to content

Instantly share code, notes, and snippets.

@jonavon
Created August 3, 2016 12:44
Show Gist options
  • Save jonavon/662a3d7fd3cea682343e7a2b997c99df to your computer and use it in GitHub Desktop.
Save jonavon/662a3d7fd3cea682343e7a2b997c99df to your computer and use it in GitHub Desktop.
MySQL overlap function
DELIMITER ;;
CREATE FUNCTION overlap_interval(x INT,y INT,a INT,b INT)
RETURNS INTEGER DETERMINISTIC
BEGIN
DECLARE
overlap_amount INTEGER;
IF (((x <= a) AND (a < y)) OR ((x < b) AND (b <= y)) OR (a < x AND y < b)) THEN
IF (x < a) THEN
IF (y < b) THEN
SET overlap_amount = y - a;
ELSE
SET overlap_amount = b - a;
END IF;
ELSE
IF (y < b) THEN
SET overlap_amount = y - x;
ELSE
SET overlap_amount = b - x;
END IF;
END IF;
ELSE
SET overlap_amount = 0;
END IF;
RETURN overlap_amount;
END ;;
DELIMITER ;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment