1

Trying to update a table with a unique iD column as there is no unique key column in the same.

When using the below CTE, I am getting an error of relation does not exist for the CTE name in the update statement. but the same is working fine when select statement is executed.

Query used:

With updateid As
(
SELECT 
ID,
ROW_NUMBER() OVER (ORDER BY Model DESC) AS RN
FROM aud
)UPDATE updateid SET ID='AUD'||repeat('0',5-length(cast(RN as varchar)))||cast(RN as varchar)

Error encountered:

ERROR:  relation "updateid" does not exist
LINE 7: )UPDATE updateid SET ID='AUD'+replicate('0',5-len(cast(RN as...
                ^
SQL state: 42P01
Character: 95

The select statement that worked well:

With updateid As
(
SELECT 
ID,
ROW_NUMBER() OVER (ORDER BY Model DESC) AS RN
FROM aud
)Select * from updateid
1
  • 1
    The string concatenation operator in SQL is || - the + is for adding numbers. There also is no replicate() function in Postgres. And you can't update the result of a CTE in Postgres Commented May 23, 2021 at 21:10

2 Answers 2

2

You can use a sequence for this:

create sequence temp_sequence_x;

update t
    set id = nextval('temp_sequence_x');

drop sequence temp_sequence_x;

I don't recommend making the primary key a string, as your code suggests that you want to do. But you can, of course, put that logic into the set clause if needed.

Here is a db<>fiddle.

Note: If there are a group of keys that are unique, then there are alternative methods. However, your question does not provide that information. And, the sequence approach is pretty simple.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much....... for showing a new approach for the query.
1

If you still want to update the table from some source result set, you can use update ... from ... with join condition specified in where clause:

create table t
as
select q, null::int as w
from unnest(array[1,2,3]) as q
with s as (
  select row_number() over(order by q desc) as rn
    , ctid as row_id
  from t
)
update t
set w = rn
from s
where t.ctid = s.row_id
select *
from t
 q |  w
-: | -:
 3 |  1
 2 |  2
 1 |  3

db<>fiddle here

1 Comment

Thank you, the sample query worked well for me..... the update ran as expected. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.