Generate uuid for all records in a table PostgreSQL
Enable the
uuid-ossp
extension (if not already enabled):Add a UUID column to your table:
Let's assume you have a table called
my_table
and you want to add a UUID column nameduuid_column
. You can use the following SQL command to add the column:This command adds a new column to your table with default values generated using the
uuid_generate_v4()
function.Update existing rows with UUID values:
To populate the newly added UUID column with UUIDs for all existing rows, you can use an
UPDATE
statement:This statement will generate a UUID for each row in your table and update the
uuid_column
with those values.Optional: Make the UUID column not nullable (if needed):
By default, the UUID column will allow
NULL
values. If you want to enforce that the UUID column cannot beNULL
, you can use the following SQL command:
Last updated