Postgresql - Using subqueries with alter sequence expressions

SqlPostgresqlSubquerySequenceAlter

Sql Problem Overview


Is it possible to use subqueries within alter expressions in PostgreSQL?

I want to alter a sequence value based on a primary key column value.

I tried using the following expression, but it wouldn't execute.

alter sequence public.sequenceX restart with (select max(table_id)+1 from table)

Sql Solutions


Solution 1 - Sql

I don't believe you can do it like that but you should be able to use the setval function direction which is what the alter does.

select setval('sequenceX', (select max(table_id)+1 from table), false)

The false will make it return the next sequence number as exactly what is given.

Solution 2 - Sql

In addition if you have mixed case object names and you're getting an error like this:

ERROR: relation "public.mytable_id_seq" does not exist

... the following version using regclass should be useful:

select setval('"public"."MyTable_Id_seq"'::regclass, (select MAX("Id") FROM "public"."MyTable"))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDanmaxisView Question on Stackoverflow
Solution 1 - SqlArthur ThomasView Answer on Stackoverflow
Solution 2 - SqlDuncan SmartView Answer on Stackoverflow