Basic math calculations with fields in MySQL query (output in new column)

Written by - 0 comments

Published on March 7th 2012 - Listed in Linux DB MySQL


I was recently working on a script which calculates used disk space of user accounts. The limit (maxkb) and the used space (kbhomedir) are already written in a MySQL table:

mysql> select kunde,firstname,kbhomedir,maxkb FROM confixx.kunden WHERE kbhomedir>maxkb AND maxkb>0;
+-------+-----------+-----------+---------+
| kunde | firstname | kbhomedir | maxkb   |
+-------+-----------+-----------+---------+
| web1  | Sandro    |   2360508 | 2097152 |
+-------+-----------+-----------+---------+

So for the automated script this information is already good and the difference between value could be calculated in the shell or php script, but I wanted to have it calculated directly within the same query.
What I needed to know was if MySQL is able to use the values of two (or more) different columns and show the result in a newly created/dynamical column. The short answer is YES. And this is actually easier as some might think...

The following example shows how you can calculate the difference between kbhomedir and maxkb (directly in the SQL query):

mysql> select kunde,firstname,kbhomedir,maxkb,(kbhomedir-maxkb) AS difference FROM confixx.kunden WHERE kbhomedir>maxkb AND maxkb>0;
+-------+-----------+-----------+---------+------------+
| kunde | firstname | kbhomedir | maxkb   | difference |
+-------+-----------+-----------+---------+------------+
| web1  | Sandro    |   2360508 | 2097152 |     263356 |
+-------+-----------+-----------+---------+------------+

Note the mathematical calculation between the parantheses (kbhomedir-maxkb). The resulted value of this operation is then stored in the variable 'difference' which will be shown in the output as its own column.

OK, now I've got the difference. But for my automatical script it would be nice to show the amount in MB instead of this number, so the user knows how many MB he needs to delete.
As you've probably aleady had the idea, the same math calculation can be extended with a second (or more) operations:

mysql> select kunde,firstname,kbhomedir,maxkb,((kbhomedir-maxkb)/1024) AS diffMB FROM confixx.kunden WHERE kbhomedir>maxkb AND maxkb>0;
+-------+-----------+-----------+---------+----------+
| kunde | firstname | kbhomedir | maxkb   | diffMB   |
+-------+-----------+-----------+---------+----------+
| web1  | Sandro    |   2360508 | 2097152 | 257.1836 |
+-------+-----------+-----------+---------+----------+

Ergo... this user uses 257MB too much disk space in his account.


Add a comment

Show form to leave a comment

Comments (newest first)

No comments yet.