4

I'm new to databases and have been considering using a UUID as the primary key in my project, but I read some things which made me interested to learn more about the performance.

Currently, I am using the uuid data type and the default value is set to gen_random_uuid().

First of all, I was wondering: would UUIDs be less performant as a primary key?

If so...

  • Are there any tips to optimize it, e.g. would it help if the PK was sequential, but another field contained a UUID, specifically for public exposure?
  • Are there any similar alternatives which may be more performant?

(I'm not working with data of any considerable scale just yet; it's more of a theoretical question.)

3
  • Adding another column with another unique index would certainly make things slower, not faster. Btw: there is no such thing as AUTOINCREMENT in Postgres Commented Sep 23, 2022 at 19:45
  • 2
    Use a ulid instead Commented Sep 23, 2022 at 19:46
  • 1
    To expound on what @AsadAwadia said, using a ulid is better since they are sortable. Spec here: github.com/ulid/spec random UUID's destroy performance because btree indices work best when the data can be sorted. ULID's are unfortunately not native, but you can find peoples' functions around. Commented Sep 23, 2022 at 20:18

2 Answers 2

8

UUIDs are slower than keys generated by a sequence. You'll just have to accept that, there is no way around it. For that reason you use UUIDs only if you have a compelling reason, like the keys are generated outside the database or need to be unique across several database.

There is some deeper discussion of this in my article.

Sign up to request clarification or add additional context in comments.

Comments

2

While this post focuses on MySQL, the solution offered could just as easily apply to any other database. It shows a significant performance boost by rearranging a UUID to have the time-related component be the first part of the value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.