How to generate UUIDs in Prisma
October 22, 2023
UUIDs (Universally Unique Identifiers) are often used for uniquely identifying records in a database. Prisma makes it incredibly easy to use UUIDs for this purpose. In this guide, we'll go over how to generate and use UUIDs in Prisma.
For a detailed comparison of UUIDs versus other ID methods, check out our other post comparing UUID vs GUID vs CUID vs NanoID for database primary keys.
- Prisma CLI
- A database that supports UUIDs (e.g., PostgreSQL, MySQL 8.0+)
Setup Your Prisma Schema
Firstly, you'll want to specify that a field should be a UUID in your Prisma schema. Open
schema.prisma and modify it like this:
id field is set to be a UUID. The
@default(uuid()) directive tells Prisma to generate a UUID by default.
Apply the migration to update the database schema.
When you create a new user, Prisma will automatically populate the
id field with a UUID.
Retrieving data remains unchanged. You can query the
id field like any other field.
You can also update a UUID field if needed, though this is generally not recommended for fields serving as primary keys.
- For PostgreSQL, consider using the native
uuid-osspextension for UUID generation. You can enable it via a Prisma migration.
- For MySQL 8.0+, UUIDs are supported natively, and no additional configuration is needed.
- For SQLite, you will have to generate the UUID in your application code, as SQLite doesn't natively support UUID generation.
That's it. You've learned how to set up, insert, query, and update UUIDs in Prisma. It's a straightforward process that adds a layer of uniqueness and complexity to your data models.
How to automate Prisma migrations in a CI/CD pipeline
How to implement soft deletes in Prisma
How to use the shadow database in Prisma
How to reset and seed a Prisma database
UUID vs GUID vs CUID vs NanoID: A guide to database primary keys
How to squash migrations in Prisma