PostgreSQL Best Practices

Chapter 1 · Practice 2 of 5

Choose types that match the data: text, numeric, bigint

From Schema design and data types

Why it matters

The right type gives you validation and correct maths for free. The wrong one pushes checks into every piece of code that touches the column.

  • Strings: use text. It performs the same as varchar(n); add a CHECK for length only when it is a real rule.
  • Money: use numeric for prices and anything that must add up exactly. Never real or double precision, which round, so sums drift.
  • Counters and IDs: use bigint for anything that can grow, since integer tops out around 2.1 billion.
  • Everything else: use boolean, uuid, inet and jsonb instead of strings that pretend to be them.

Avoid

  • float or double precision for prices and balances
  • integer primary keys on tables that can grow fast
  • Dates or numbers stored in text columns