Created
April 22, 2021 09:44
-
-
Save huntfx/e236ff2b8dc69a2f9e9ed8b2f9dd4ab5 to your computer and use it in GitHub Desktop.
Function to convert bytes to KB/MB/TB etc in SQL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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