What's your opinion on using UUIDs as database row identifiers, particularly in web apps?

后端 未结 15 2125
深忆病人
深忆病人 2020-12-12 12:43

I\'ve always preferred to use long integers as primary keys in databases, for simplicity and (assumed) speed. But when using a REST or Rails-like URL scheme for object insta

相关标签:
15条回答
  • 2020-12-12 13:20

    I work with a student management system which uses UUID's in the form of an integer. They have a table which hold the next unique ID.

    Although this is probably a good idea for an architectural point of view, it makes working with on a daily basis difficult. Sometimes there is a need to do bulk inserts and having a UUID makes this very difficult, usually requiring writing a cursor instead of a simple SELECT INTO statement.

    0 讨论(0)
  • 2020-12-12 13:23

    I think that this is one of these issues that cause quasi-religious debates, and its almost futile to talk about. I would just say use what you prefer. In 99% of systems it will no matter which type of key you use, so the benefits (stated in the other posts) of using one sort over the other will never be an issue.

    0 讨论(0)
  • 2020-12-12 13:23

    I think using a GUID would be the better choice in your situation. It takes up more space but it's more secure.

    0 讨论(0)
  • 2020-12-12 13:27

    Why couple your primary key with your URI?

    Why not have your URI key be human readable (or unguessable, depending on your needs), and your primary index integer based, that way you get the best of both worlds. A lot of blog software does that, where the exposed id of the entry is identified by a 'slug', and the numeric id is hidden away inside of the system.

    The added benefit here is that you now have a really nice URL structure, which is good for SEO. Obviously for a transaction this is not a good thing, but for something like stackoverflow, it is important (see URL up top...). Getting uniqueness isn't that difficult. If you are really concerned, store a hash of the slug inside a table somewhere, and do a lookup before insertion.

    edit: Stackoverflow doesn't quite use the system I describe, see Guy's comment below.

    0 讨论(0)
  • 2020-12-12 13:32

    I can't say about the web side of your question. But uuids are great for n-tier applications. PK generation can be decentralized: each client generates it's own pk without risk of collision. And the speed difference is generally small.

    Make sure your database supports an efficient storage datatype (16 bytes, 128 bits). At the very least you can encode the uuid string in base64 and use char(22).

    I've used them extensively with Firebird and do recommend.

    0 讨论(0)
  • 2020-12-12 13:32

    Rather than URLs like this:

    http://example.com/user/783
    

    Why not have:

    http://example.com/user/yukondude
    

    Which is friendlier to humans and doesn't leak that tiny bit of information?

    0 讨论(0)
提交回复
热议问题