Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update unique values in SQL using a PostgreSQL sequence?

In SQL, how do update a table, setting a column to a different value for each row?

I want to update some rows in a PostgreSQL database, setting one column to a number from a sequence, where that column has a unique constraint. I hoped that I could just use:

update person set unique_number = (select nextval('number_sequence') );

but it seems that nextval is only called once, so the update uses the same number for every row, and I get a 'duplicate key violates unique constraint' error. What should I do instead?

like image 469
Peter Hilton Avatar asked Sep 29 '08 08:09

Peter Hilton


People also ask

How do you refresh a sequence in PostgreSQL?

pg_get_serial_sequence can be used to avoid any incorrect assumptions about the sequence name. This resets the sequence in one shot: SELECT pg_catalog. setval(pg_get_serial_sequence('table_name', 'id'), (SELECT MAX(id) FROM table_name)+1);

How do I get unique column values in PostgreSQL?

Syntax: SELECT DISTINCT ON (column_1) column_alias, column_2 FROM table_name ORDER BY column_1, column_2; As the order of rows returned from the SELECT statement is unpredictable which means the “first row” of each group of the duplicate is also unpredictable.

Can we use distinct in PostgreSQL?

Removing duplicate rows from a query result set in PostgreSQL can be done using the SELECT statement with the DISTINCT clause. It keeps one row for each group of duplicates. The DISTINCT clause can be used for a single column or for a list of columns.


1 Answers

Don't use a subselect, rather use the nextval function directly, like this:

update person set unique_number = nextval('number_sequence');
like image 70
Grey Panther Avatar answered Oct 01 '22 15:10

Grey Panther