views:

127

answers:

3

Hello, I'm very dubious about datatype of my database, I need to use different unit of measurements because I have different elements and different scales, and I'm sure about the limits used, because I take them from standard elements, but I'm afraid about the variety.

Just consider I work with 100 grams of product and take from it all elements, so, I'm sure I can't go over 100 grams for proteins, but i can reach 3500 kilojoule or 3,27 milligrams of iron element.

So I need various datatypes I think, but I'm not sure about the right kind.
I'll show the max values to be more clear about the unit limits:

grams          99,99 g
milligrams   9999,99 mg
micrograms  99999    µg
kilojoule    9999    kj

So, what is the right way?
I'm sure the best way (the best performance) is to store the various elements with their standard values (for example, kilojoule for calories) but what are the datatype equivalents?

A: 

I think that you can choose DECIMAL data type for such data. You can specify how many symbols need to store before comma and after. Like this:

DECIMAL (6, 4)

means that you can store maximum 999999.9999 value in this field.

Sergey Kuznetsov
DECIMAL (6, 4) is only correct on older versions of MySQL. More info in my Answer post.
micahwittman
A: 

Make use of MySql DECIMAL with precision as required. FLOAT might not give you the precision required to store the values exactly.

astander
+2  A: 

For a 999999.9999 max decimal in the current version of MySQL, you would need to define field as:

DECIMAL (10, 4)

(it's easily confused with DECIMAL (6, 4) which was correct in older versions of MySQL, but is incorrect on the latest)

SEE:

http://stackoverflow.com/questions/1523173/decimal3-2-values-in-mysql-are-always-9-99/1525090#1525090

http://stackoverflow.com/questions/1818046/what-does-m-d-mean-in-decimalm-d-exactly/1818057#1818057

micahwittman
thanks, perfect answer, especially with different MySql versions, so do You suggest me tu use different decimal type or one for all?
Vittorio Vittori
Based on the max values you provided: x_in_grams DECIMAL(4, 2), x_in_milligrams DECIMAL(6, 2), x_in_micrograms MEDIUMINT, x_in_kilojoule SMALLINT
micahwittman