相关文章推荐
追风的水煮鱼  ·  mysql主键更新很慢_mysql ...·  2 年前    · 
面冷心慈的酱牛肉  ·  使用JSONObject时,你需要注意避免的 ...·  2 年前    · 
仗义的登山鞋  ·  使用未初始化内存的VS2022代码分析错误C ...·  2 年前    · 
坚韧的松鼠  ·  Linux Page ...·  2 年前    · 
Code  ›  Postgresql源码(66)insert on conflict语法介绍与内核执行流程解析开发者社区
源码 test select postgresql
https://cloud.tencent.com/developer/article/2111806
安静的回锅肉
2 年前
作者头像
mingjie
0 篇文章

Postgresql源码(66)insert on conflict语法介绍与内核执行流程解析

前往专栏
腾讯云
开发者社区
文档 意见反馈 控制台
首页
学习
活动
专区
工具
TVP
文章/答案/技术大牛
发布
首页
学习
活动
专区
工具
TVP
返回腾讯云官网
社区首页 > 专栏 > Postgresql源码分析 > Postgresql源码(66)insert on conflict语法介绍与内核执行流程解析

Postgresql源码(66)insert on conflict语法介绍与内核执行流程解析

作者头像
mingjie
发布 于 2022-09-19 15:39:27
494 0
发布 于 2022-09-19 15:39:27
举报

1 语法介绍

insert on conflict语法实现了upsert的功能,即在插入发生主键冲突、或唯一约束冲突时,执行on conflict后面的语句,将insert变成update或do nothing避免报错。

语法手册: https://www.postgresql.org/docs/current/sql-insert.html

测试用例:

drop table decoding_test;
CREATE TABLE decoding_test(x integer primary key, y text);
postgres=# select * from decoding_test;
 x  | y 
----+---
 12 | 9
postgres=# INSERT INTO decoding_test(x,y) values(12,9) on conflict (x) do nothing;
INSERT 0 1
postgres=# select * from decoding_test;
 x  | y 
----+---
 12 | 9
-- 没有报主键冲突,结果上看插入没有效果。
postgres=# INSERT INTO decoding_test(x,y) values(12,9) on conflict (x) do nothing;
INSERT 0 0
postgres=# select * from decoding_test;
 x  | y 
----+---
 12 | 9
(1 row)
postgres=# INSERT INTO decoding_test(x,y) values(101,20) on conflict (x) do update set y=EXCLUDED.y;
INSERT 0 1
postgres=# 
postgres=# select * from decoding_test;
  x  | y  
-----+----
  12 | 9
 101 | 20
-- 插入时发生主键冲突,执行后面的update语句,将y更新为400,EXCLUDED表示准备要新插入的这一行数据。
postgres=# INSERT INTO decoding_test(x,y) values(101,400) on conflict (x) do update set y=EXCLUDED.y;
INSERT 0 1
postgres=# select * from decoding_test;
  x  |  y  
-----+-----
  12 | 9
 
推荐文章
追风的水煮鱼  ·  mysql主键更新很慢_mysql 更新数据很慢_mysql 更新非主键 - 腾讯云开发者社区 - 腾讯云
2 年前
面冷心慈的酱牛肉  ·  使用JSONObject时,你需要注意避免的一个问题-51CTO.COM
2 年前
仗义的登山鞋  ·  使用未初始化内存的VS2022代码分析错误C6001 - 问答 - 腾讯云开发者社区-腾讯云
2 年前
坚韧的松鼠  ·  Linux Page Cache调优在Kafka中的应用 - vivo互联网技术 - 博客园
2 年前
今天看啥   ·   Py中国   ·   codingpro   ·   小百科   ·   link之家   ·   卧龙AI搜索
删除内容请联系邮箱 2879853325@qq.com
Code - 代码工具平台
© 2024 ~ 沪ICP备11025650号