はじめに
PostgreSQLで設計をする際、プライマリーキーにUUIDを使うことについて調べたときのメモです。
何を使用すればいいかは、デーブルのサイズやデータ量、いろいろな条件によって場合によります。厳密に正しい選択をしたい場合に関しては「推測するな、計測しろ」が正しいです。
あくまでメモのリンク集なので、結論や計測結果などはこの記事には記載されておりません。
公式ドキュメント
公式ドキュメントを読んでみたが、UUIDのパフォーマンスについての記載はなし。
-
UUID Typeについて
https://www.postgresql.org/docs/15/datatype-uuid.html -
UUIDの生成関数
https://www.postgresql.org/docs/15/functions-uuid.html -
UUIDの追加のモジュールについて
https://postgresql.org/docs/15/uuid-ossp.html
UUIDのデメリット
-
uuid を主キーとして使用すると、パフォーマンスに重大なデメリットが生じますか?
https://www.reddit.com/r/PostgreSQL/comments/mi78aq/any_significant_performance_disadvantage_to_using/?rdt=46851 -
MySQLでプライマリキーをUUIDにする前に知っておいて欲しいこと
https://techblog.raccoon.ne.jp/archives/1627262796.html -
MySQLとPostgreSQLと主キー
https://speakerdeck.com/hmatsu47/mysqltopostgresqltozhu-ki -
Postgres と MySQL における id, created_at, updated_at に関するベストプラクティス
https://zenn.dev/mpyw/articles/rdb-ids-and-timestamps-best-practices
MySQLではUUIDに明確なデメリットがある。
-
Postgres で主キーとして UUID を使用することの長所と短所
https://blog.bhanunadar.com/pros-and-cons-of-using-uuid-as-primary-key-in-postgres/ -
30%高速化、UUIDの欠点、WALの増大、プロセスとの比較
https://www.scalingpostgres.com/episodes/271-30-percent-faster-uuid-downsides-growing-wal-processes-vs-threads/
CUID
-
Prismaの公式ドキュメント CUID
https://www.prisma.io/docs/orm/reference/prisma-schema-reference#cuid -
CUID公式GitHub
https://github.com/paralleldrive/cuid?tab=readme-ov-file
CUIDは非推奨、CUID2を使ってくださいと公式には書かれている。PrismaではCUIDだが、このセキュリティ的な問題点は、UUIDにも同様に存在するため、今回は無視する。
- UUID/GUID、CUID、NanoID: 違いは何ですか?
https://dev.to/harshhhdev/uuidguid-cuid-nanoid-whats-the-difference-5dj1
この記事ではPrismaを使用する場合はCUIDが最良の選択と説明している。
- PostgreSQL と外部キーを使用した CUID と UUID
https://github.com/prisma/prisma/discussions/21489
PrismaでCUIDを使う場合に@db.VarChar(30)をつけるという話。
シーケンシャルID
- PostgreSQLの自動生成主キーの UUID,シーケンシャルID
https://www.cybertec-postgresql.com/en/uuid-serial-or-identity-columns-for-postgresql-auto-generated-primary-keys/