[Postgres] On conflict Do Something Clause in Postgres

Instead of first checking to see if a record already exists within your table, we can do a on conflict do update. In this command, we can ether insert a row into our table, if it does exist, then check to see if all of the columns match up. This saves us a database call and is pretty straightforward to understand.

postgres=# insert into users (user_handle, first_name, last_name, email) 
values (uuid_generate_v4(), 'Lucie', 'Jones', 'Lucie-Jones@gmail.com') on conflict do nothing:

 

We can also choose to update instead of doing nothing:

postgres=# insert into users values (uuid_generate_v4(), 'Lucie', 'Hawkins', 'Lucie-Jones@gmail.com') 
on conflict (email) do update set first_name = excluded.first_name, last_name = excluded.last_name;

With this command (on conflict <column name> do), you choose the column in which there is a conflict (user has same email address, but has changed their last name, in this case), and then define the columns you wants to update when this conflict occurs. (eg. Lucie Jones' name will be updated to Lucie Hawkins because her account was identified by the email address conflict)

 

The excluded. refers to incoming data for that column.

 

This action is commonly referred to as an "upsert".

 

We can also update this query with a where clause.

postgres=# insert into users as u values (uuid_generate_v4(), 'Lucie', 'Cook', 'Lucie-Jones@gmail.com') 
on conflict (email) do update set first_name = excluded.first_name, last_name = excluded.last_name
where u.first_name <> 'Lucie';

<> for 'does not equal'

In this example, if there is an email conflict and the original records firstname is equal to 'Lucie' the row will not be updated

posted @   Zhentiw  阅读(162)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2019-10-08 [NgRx] Optimistically Editing Entity Data
2019-10-08 [Angular 8] Keep original DOM structure with ng-container
2019-10-08 [NgRx 8] Basic of NgRx8
2016-10-08 [NodeJS] Use Now alias for custom sub-domains
2016-10-08 [CSS3] Create a fixed-fluid-fixed layout using CSS calc()
点击右上角即可分享
微信分享提示