Solved Problems – SQL, Java, JBoss



PostreSQL: How create unique primary key with values after a table is already populated with data


Here’s how you can create a primary key with unique values, if say you need one for an existing table when using it with Java Persistence API.

1. Create a new field. I’ve named it ‘primary’ in this case.
2. Then create a new sequence. Here it’s called ‘primaryseq’.
3. Execute the following query:

UPDATE
public.tablename
SET

“primary” = NEXTVAL(‘primaryseq’)

WHERE “primary” IS NULL
;

Another solution you might want to take a look at.




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.