Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Learn PostgreSQL

You're reading from   Learn PostgreSQL Use, manage, and build secure and scalable databases with PostgreSQL 16

Arrow left icon
Product type Paperback
Published in Oct 2023
Publisher Packt
ISBN-13 9781837635641
Length 744 pages
Edition 2nd Edition
Languages
Arrow right icon
Authors (2):
Arrow left icon
Luca Ferrari Luca Ferrari
Author Profile Icon Luca Ferrari
Luca Ferrari
Enrico Pirozzi Enrico Pirozzi
Author Profile Icon Enrico Pirozzi
Enrico Pirozzi
Arrow right icon
View More author details
Toc

Table of Contents (22) Chapters Close

Preface 1. Introduction to PostgreSQL 2. Getting to Know Your Cluster FREE CHAPTER 3. Managing Users and Connections 4. Basic Statements 5. Advanced Statements 6. Window Functions 7. Server-Side Programming 8. Triggers and Rules 9. Partitioning 10. Users, Roles, and Database Security 11. Transactions, MVCC, WALs, and Checkpoints 12. Extending the Database – the Extension Ecosystem 13. Query Tuning, Indexes, and Performance Optimization 14. Logging and Auditing 15. Backup and Restore 16. Configuration and Monitoring 17. Physical Replication 18. Logical Replication 19. Useful Tools and Extensions 20. Other Books You May Enjoy
21. Index

Using UPSERT

In this section, we will look at the PostgreSQL way to make an UPSERT statement. There is no UPSERT statement in SQL, but the same effect can be achieved using an INSERT SQL statement.

UPSERT – the PostgreSQL way

In PostgreSQL, the UPSERT statement does not exist as in other DBMSes. An UPSERT statement is used when we want to insert a new record on top of the existing record or update an existing record. To do this in PostgreSQL, we can use the ON CONFLICT keyword:

INSERT INTO table_name(column_list) VALUES(value_list)
ON CONFLICT target action;

Here, ON CONFLICT means that the target action is executed when the record already exists (meaning when a record with the same primary key exists). The target action could be this:

 DO NOTHING

Alternatively, it could be the following:

DO UPDATE SET { column_name = { expression | DEFAULT } |
     ( column_name [, ...] ) = [ ROW ] ( { expression | DEFAULT } [, ...] ) |
     ( column_name [, ...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at R$50/month. Cancel anytime