Skip to content

Instantly share code, notes, and snippets.

@huntfx
Created April 22, 2021 09:44
Show Gist options
  • Save huntfx/e236ff2b8dc69a2f9e9ed8b2f9dd4ab5 to your computer and use it in GitHub Desktop.
Save huntfx/e236ff2b8dc69a2f9e9ed8b2f9dd4ab5 to your computer and use it in GitHub Desktop.
Function to convert bytes to KB/MB/TB etc in SQL
CREATE FUNCTION `format_bytes` (val float)
RETURNS varchar(20)
DETERMINISTIC
CONTAINS SQL
BEGIN
DECLARE pw smallint;
IF val < 1024 THEN
return CONCAT(val, ' B');
END IF;
SET pw = LEAST(7, FLOOR(LOG(val) / LOG(1024)));
RETURN CONCAT(ROUND(val / POW(1024, pw), 2), ' ', SUBSTR('KMGTPEZY', pw, 1), 'B');
END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment