title: MySQL Convert Bytes to Kilobytes, Megabytes, Gigabytes
body: <p>I have a logs table that stores various file sizes in bytes. I want to be able to query the database and return the smallest possible float which has been converted to MB GB etc. At present I can return the value in MB but how do I continue to divide further to smallest value and append the unit?</p>
  
  <pre><code>SELECT CONCAT( ROUND( SUM( data_transferred ) /1048576, 2 ) ,  ' MB' ) 
  FROM  `logs`
  </code></pre>
  
  <p>Any help would be appreciated.</p>
  
  <p>UPDATE:</p>
  
  <p>Based on the link voodoo417 provided I updated my query to the following, which will output the most relevant file size to two decimal places and append the unit (1000 Bytes, 1 KB, 500 MB, 2 GB, etc):</p>
  
  <pre><code>SET @bytes := (SELECT SUM(data_transferred) FROM wp_ddownload_statistics);
  
  SELECT
      CASE
  WHEN ABS(@bytes) &lt; 1024 THEN CONCAT( ROUND( @bytes, 2 ), ' Bytes')
        WHEN ABS(@bytes) &lt; 1048576 THEN CONCAT( ROUND( (@bytes/1024), 2 ), ' KB')
        WHEN ABS(@bytes) &lt; 1073741824 THEN CONCAT( ROUND( (@bytes/1048576), 2 ), ' MB')
        WHEN ABS(@bytes) &lt; 1099511627776 THEN CONCAT( ROUND( (@bytes/1073741824), 2 ), ' GB' )
        WHEN ABS(@bytes) &lt; 1125899906842624 THEN CONCAT( ROUND( (@bytes/1099511627776), 2 ), ' TB')
        WHEN ABS(@bytes) &lt; 1152921504606846976 THEN CONCAT( ROUND( (@bytes/1125899906842624), 2 ), ' PB' )
        WHEN ABS(@bytes) &lt; 1180591620717411303424 THEN CONCAT( ROUND( (@bytes/1152921504606846976) ,2), ' EB' )
        WHEN ABS(@bytes) &lt; 1208925819614629174706176 THEN CONCAT( ROUND( (@bytes/1180591620717411303424), 2), ' ZB' )
        WHEN ABS(@bytes) &lt; 1237940039285380274899124224 THEN CONCAT( ROUND( (@bytes/1208925819614629174706176), 2), ' YB' )
        WHEN ABS(@bytes) &lt; 1267650600228229401496703205376 THEN CONCAT( ROUND( (@bytes/1237940039285380274899124224), 2), ' BB' )
      END
  </code></pre>