Postgres inserts with ON CONSTRAINT DO UPSET, and FOR loops to avoid violating constraints

  • does not allow to read a value from a subquery for <expression>
  • does not allow to perform multiple times in case the constraint is violated more than once.
yourRecord RECORD;
nextAvailableValue bigint;
FOR yourRecord IN (SELECT * from yourTable) LOOP
SELECT MAX(col1)+1 INTO nextAvailableValue
FROM table_with_values
WHERE col2 =;

INSERT INTO other_table(
END $$;




Software Engineer @ London []

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Create Amazing GIS Data-Driven Maps Using ArcGIS API for JavaScript

Map of US showing population living in poverty by county

Install and Create Vue.js project using CLI (Angular to Vue.js-Part )

Thank You 🙏

Create an infinite scrolling animation with CSS 💥

Higher Order Components

How to deploy React App on Firebase

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Elvis Ciotti

Elvis Ciotti

Software Engineer @ London []

More from Medium

Postgresql User Management in Nutshell

Distributed SQL Tips and Tricks — December 16th, 2021

Trigger a build/release pipeline from the different projects in ADO using REST API


Restore MySQL InnoDB Cluster from mysqlbackup(MySql Enterprise Backup)