Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

221
Vistas
Should I lock a PostgreSQL table when invoking setval for sequence with the max ID function?

I have the following SQL script which sets the sequence value corresponding to max value of the ID column:

SELECT SETVAL('mytable_id_seq', COALESCE(MAX(id), 1)) FROM mytable;

Should I lock 'mytable' in this case in order to prevent changing ID in a parallel request, such in the example below?

 request #1    request #2

 MAX(id)=5

              inserted id 6

 SETVAL=5

Or setval(max(id)) is an atomic operation?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Your suspicion is right, this approach is subject to race conditions.

But locking the table won't help, because it won't keep a concurrent transaction from fetching new sequence values. This transaction will block while the table is locked, but will happily continue inserting once the lock is gone, using a sequence value it got while the table was locked.

If it were possible to lock sequences, that might be a solution, but it is not possible to lock sequences.

I can think of two solutions:

  1. Remove all privileges on the sequence while you modify it, so that concurrent requests to the sequence will fail. That causes errors, of course.

  2. The pragmatic way: use

    SELECT SETVAL('mytable_id_seq', COALESCE(MAX(id), 1) + 100000) FROM mytable;
    

    Here 100000 is a value that is safely bigger than the number rows that might get inserted while your operatoin is running.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda