-1

I have update query that will manually change the field value as a unique string, the table already have a lost of data and the id as unique Pkey.

So I need the names should look like

mayname-id-1, 
mayname-id-2, 
mayname-id-3,     etc

I tried to update with string_agg, but that doesn't work in update queries

UPDATE mytable 
SET name = string_agg('mayname-id-', id);

How to construct string dynamically in an update query?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Sarath
  • 9,030
  • 11
  • 51
  • 84

3 Answers3

1

How about the following:

UPDATE mytable 
SET name = 'mayname-id-' || CAST(id AS text)
Linger
  • 14,942
  • 23
  • 52
  • 79
1

Typically, you should not add such a completely redundant column at all. It's cleaner and cheaper to generate it as functionally dependent value on the fly. You can use a view or a "generated column" for that. Details:

You can even have a unique index on such a functional value if needed.

Community
  • 1
  • 1
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
0

Use string concatenation

UPDATE mytable SET name = 'nayname-id-' || (id :: text);