I created a new application and I am thinking where is the best place to generate a UUID.

  1. Generate a UUID in application level and persist it
  2. Generate a UUID in Database level

I have a feeling that is a better approach to generate the UUID in Database level.

What do you think and why?

Many thanks in advance

  • 3
    One of the reasons why you might want to use a UUID is because you want to generate it in the application. Other kinds of primary keys, like consecutive integers, cannot be generated in the application without an extra round trip to the database, making generating them in the database a more favorable approach. Jun 6, 2018 at 15:00
  • 1
    Beyond that, there are several other pros and cons. Which approach is "better" for you depends on what your specific requirements are. Jun 6, 2018 at 15:01

2 Answers 2


You may want to go with "both".

Generating the UUIDs in the application usually makes it easier to run tests as mocking DB logic can be quite fragile.

On the other side of things, if you're developing and need to quickly populate fake data, it's easiest if the UUID can be generated as part of a simple insert statement.

TL;DR: it depends on the context


For most applications IDs should be generated in the DB as this will prevent duplicates if you have multiple client instances, for example load balanced web servers. There are database systems which have different consistency models from SQL RDBMSs which can have the same problem but then you are making an active choice to use an inconsistent DB.

  • 2
    Note that this doesn't really apply for UUIDs, as the entire point is that they are "unique" purely through probability.
    – Turksarama
    Jul 9, 2018 at 1:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.