PostgreSQL using UUID vs Text as primary key

When dealing with UUID numbers store them as data type uuid. Always. There is simply no good reason to even consider text as alternative. Input and output is done via text representation by default anyway. The cast is very cheap.

The data type text requires more space in RAM and on disk, is slower to process and more error prone. @khampson’s answer provides most of the rationale. (Due to your pre-existing implementation, he doesn’t arrive at the same conclusion.)

This has all been asked and answered and discussed before. Related questions on dba.SE with detailed explanation:

  • Would index lookup be noticeably faster with char vs varchar when all values are 36 chars
  • What is the optimal data type for an MD5 field?

bigint?

Maybe you don’t need UUIDs (GUIDs) at all. Consider bigint instead. It only occupies 8 bytes and is faster in every respect. Its range is often underestimated:

-9223372036854775808 to +9223372036854775807

That’s 9.2 millions of millions of millions positive numbers. IOW, nine quintillion two hundred twenty-three quadrillion three hundred seventy-two trillion thirty-six something billion.

If you burn 1 million IDs per second (an insanely high number) you can keep doing so for 292471 years. And then another 292471 years for negative numbers. “Tens or hundreds of millions” is not even close.

UUID is really just for distributed systems and other special cases.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)