Saturday, March 03, 2012

Best Data Types for Currency/Money in MySQL?

So you want to know what the best data type is for storing currency/money values in MySQL?

The Short Answer

When handling money in MySQL, use DECIMAL(13,2) if you know the precision of your money values or use DOUBLE if you just want a quick good-enough approximate value.

The Details

On some database management systems (DBMS) there is a data type specially set aside for handling money.  However, MySQL doesn't have one so the choice of best representation is left to the programmer.

Since about 1999, using MySQL 3, I have generally used the DOUBLE data type to represent money values as it stores decimals at reasonably high precision. The values stored are approximations, but the number of decimals treated accurately is enough for normal money values.  The ROUND function is helpful when doing aggregation queries, such as:

SELECT
  ROUND(SUM(amount), 2) AS total_amount
FROM orders
WHERE created_at > '2012-01-01'

However, since MySQL 5 there are some better data types for storing exact money values.  From the MySQL manual:
"The DECIMAL and NUMERIC types store exact numeric data values. These types are used when it is important to preserve exact precision, for example with monetary data. In MySQL, NUMERIC is implemented as DECIMAL, so the following remarks about DECIMAL apply equally to NUMERIC."
The DECIMAL data type requires you to specify the number of digits before the decimal point and the number of digits after the decimal point.

So if your application needs to handle money values up to a trillion dollars (or euros or pounds), then this should work:
DECIMAL(13, 2)
However, considering the rate that the central banks are printing money these days, we might all soon need to be processing larger values for currency.

I hope this helps.

References

 
One Last Thing

One of the services my company offers is database conversion solutions.  Are you looking to convert spreadsheet data to a MySQL database?  Check out SQL Converter's new Expert Conversion Service.  The classic Excel macro is still available as well.

Thursday, March 01, 2012

Working on SQL Converter for Excel Refresh for 64-bit Excel

Even though Microsoft is known for being fanatical about maintaining backwards compatibility, SQL Converter for Excel apparently doesn't work so well in 64-bit Excel 2010 on Windows 7.  Unfortunately that was an environment that we did not have on any of our systems.  I am configuring a new copy Windows 7 Pro in a Parallels virtual machine so that I can get a refresh working.

In the mean time, check out our new Expert Conversion Service at http://www.sqlconverter.com/expert.html.