Just a collection of tips to make working with Postgres (and other SQL-like databases) easier
Measurement Unit
Take this case for an example, you have a product table and you want to store product information like its size
and weight by adding these columns to describe such properties: width
, length
, height
and
weight
.
id | name | width | length | height | weight |
---|---|---|---|---|---|
1 | ipad | 10 | 20 | 0.1 | 0.5 |
2 | macbook | 20 | 30 | 0.5 | 2 |
So what’s the problem with the above table? We are assuming that the size props (width, height and length) are measured in cm and the weight is measured in kg. Usually, we could put this logic in application layer to make sure we convert everything to cm and kg before inserting into the database. However, it could lead to even more problems
- What will happen if a new dev join the team? How can you make sure that person will know when to convert and when not?
- What will happen if a dev using pound join the team?
- What will happen if a dev accidentally assume the value in weight is in mg?
- Sometimes, you could do a double conversion, making thing worse.
- You need to remember adding comment to every place in your code, just to remind people which measurement unit that function is using.
- Which data type to choose? Integer, of course, is not a good choice. However, working with real, double, decimal or numeric is always harder compare to int. They could cause some problems with parsing and datatype for languages/libraries like Nodejs.