Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DECIMAL vs INT what is the best optimized choice?

I'm sure this ask is incomplete without a precise context, so I'll try to explain it, and I'll try to be clear
I need to store a whole of data rapresented on the page with grams, milligrams, micrograms and kilojoule.

All of this data is like 99999.99g (kilojoule apart), so I could use DECIMAL(7,2) or DECIMAL(5,2) with older MySql versions.

However, I've saw in mysql site, DECIMAL datatype is more heavy than a MEDIUMINT (am I wrong?) that could be enough to store the data.
Mainly, I'll do numeric operations on decimals or floats from the user machine, and don't need to store them again, so I'm doubtful about what is the best datatype in this case.

so what is the best datatype in this case?

like image 696
vitto Avatar asked Dec 18 '22 04:12

vitto


2 Answers

One purpose of databases is to provide and ensure data integrity, and to store data in a format that is as close to the natural format of the type of data that needs to be stored. With that in mind, you should not attempt to optimize data types for the database engine prematurely (unless you've done benchmarks and you have a very good reason). Instead, your efforts are better spent on designing your table structures appropriately with the correct relationships and creating indexes where appropriate to help the database engine deal with the volume and types of data that you have. You will be surprised how much data a DB engine can process if the data is normalized properly and indexes and relationships are created where appropriate.

So, as a best practice, prefer the DECIMAL type for storing decimal or fractional numbers such as prices, fractional quantities etc.

like image 85
Mike Dinescu Avatar answered Jan 02 '23 10:01

Mike Dinescu


Store the data as it is with as much precision as you can. You can always truncate it when you select it.

You may regret not storing the extra data a year from now when you need the precision.

like image 27
Broam Avatar answered Jan 02 '23 10:01

Broam