DEV Community

Vahid Yousefzadeh
Vahid Yousefzadeh

Posted on

PostgreSQL 19: ON CONFLICT DO SELECT

When inserting data into PostgreSQL, you may encounter a situation where the row already exists. Traditionally, you could use ON CONFLICT DO NOTHING and execute another SELECT to retrieve the existing row. Alternatively, you could use ON CONFLICT DO UPDATE with an update that does not actually change any data.
PostgreSQL 19 introduces ON CONFLICT DO SELECT, providing a simpler way to handle this scenario. It allows an INSERT statement to return either the newly inserted row or the existing conflicting row, without performing an unnecessary UPDATE.
In this article, we will explore these approaches using a practical user registration scenario.

Creating the users table

Let's start by creating a table to store user account information.

vahiddb=# CREATE TABLE tbl_users (
    user_id          BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    email            VARCHAR(100) UNIQUE NOT NULL,
    full_name        VARCHAR(100),
    registered_at    TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE
Enter fullscreen mode Exit fullscreen mode

The email column has a UNIQUE constraint to prevent multiple accounts from being registered with the same email address.
Now, let's register our first user:

vahiddb=# insert into tbl_users (email,full_name) 
 values('vahidusefzadeh@gmail.com','Vahid Yousefzadeh');
INSERT 0 1
vahiddb=# select * from tbl_users;
 user_id |          email           |     full_name     |         registered_at
---------+--------------------------+-------------------+-------------------------------
       1 | vahidusefzadeh@gmail.com | Vahid Yousefzadeh | 2026-11-24 11:09:01.753137+03
(1 row)
Enter fullscreen mode Exit fullscreen mode

Inserting an Existing Email

Imagine that the application receives another registration request with the same email address. PostgreSQL raises an error:

vahiddb=# INSERT INTO tbl_users (email, full_name)
 VALUES ('vahidusefzadeh@gmail.com', 'Vahid Yousefzadeh');

ERROR:  duplicate key value violates unique constraint "tbl_users_email_key"
DETAIL:  Key (email)=(vahidusefzadeh@gmail.com) already exists.
Enter fullscreen mode Exit fullscreen mode

However, our application does not necessarily want an error. It may simply need the existing user's user_id.
Let's explore the available solutions.

Using ON CONFLICT DO NOTHING with a CTE

One traditional approach is to use ON CONFLICT DO NOTHING and then retrieve the existing user's ID with a SELECT statement.

vahiddb=# WITH tbl_users_new AS (
    INSERT INTO tbl_users (email, full_name)
    VALUES ('vahidusefzadeh@gmail.com', 'Vahid Yousefzadeh')
    ON CONFLICT (email) DO NOTHING
    RETURNING User_id
)
SELECT User_id
FROM tbl_users_new
UNION ALL
SELECT User_id
FROM tbl_users
WHERE email = 'vahidusefzadeh@gmail.com'
LIMIT 1;

 user_id
---------
       1
(1 row)
Enter fullscreen mode Exit fullscreen mode

This query handles both situations:
If the user does not exist, the INSERT succeeds and the CTE returns the newly generated ID.
If the user already exists, the INSERT does nothing, and the second SELECT retrieves the existing ID.

Using ON CONFLICT DO UPDATE to retrieve the existing ID

Another common workaround is to use ON CONFLICT DO UPDATE and return the ID.
For example:

vahiddb=# INSERT INTO tbl_users (email, full_name)
VALUES ('vahidusefzadeh@gmail.com', 'Vahid Yousefzadeh')
ON CONFLICT (email)
DO UPDATE
SET email = EXCLUDED.email
RETURNING User_id;

 user_id
---------
       1
(1 row)

INSERT 0 1

Enter fullscreen mode Exit fullscreen mode

This works, but notice the UPDATE operation:

SET email = EXCLUDED.email
Enter fullscreen mode Exit fullscreen mode

We are assigning the existing email its current value just to retrieve the user's ID.
Even though the value does not change, PostgreSQL still performs an UPDATE. This can create a new row version, generate WAL, and fire UPDATE triggers. It can also affect audit columns or other application logic.
In other words, we are modifying a record when our actual requirement is only to retrieve it.
This is where PostgreSQL 19 provides a better alternative.

ON CONFLICT DO SELECT

PostgreSQL 19 introduces a new conflict action:
ON CONFLICT (…) DO SELECT
Unlike DO NOTHING, this action returns the existing row when a uniqueness conflict occurs.
Unlike DO UPDATE, it does not modify the existing row.
The general syntax is:

INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...)
ON CONFLICT (unique_column)
DO SELECT [ FOR { UPDATE | NO KEY UPDATE | SHARE | KEY SHARE } ] [ WHERE condition ]
RETURNING column1, column2, ...;
Enter fullscreen mode Exit fullscreen mode

Let's apply it to our user registration example:

vahiddb=# INSERT INTO tbl_users (email, full_name)
 VALUES ('vahidusefzadeh@gmail.com', 'Vahid Yousefzadeh')
ON CONFLICT (email)
DO SELECT
RETURNING user_id, email, registered_at;
 user_id |          email           |         registered_at
---------+--------------------------+-------------------------------
       1 | vahidusefzadeh@gmail.com | 2026-11-24 11:09:01.753137+03
(1 row)

INSERT 0 1
Enter fullscreen mode Exit fullscreen mode

PostgreSQL detects the conflict on the email column and returns the existing user's information.
The same statement handles both cases:
If the email does not exist, PostgreSQL inserts a new user and returns the inserted row.
If the email already exists, PostgreSQL returns the conflicting row.

We no longer need a separate SELECT or an unnecessary UPDATE.
This is particularly useful for application-level get-or-create operations.

WHERE condition with DO SELECT

PostgreSQL 19 also allows us to specify a condition in the DO SELECT action. This lets us control whether the conflicting row should be returned.
For example, suppose we want to return the existing user only when the proposed full name differs from the stored full name.
We can use the EXCLUDED table to reference the values proposed for insertion and a target-table alias to reference the existing row.

vahiddb=# INSERT INTO tbl_users AS u (email, full_name)
VALUES ('vahidusefzadeh@gmail.com', 'Vahid')
ON CONFLICT (email)
DO SELECT
WHERE u.full_name != EXCLUDED.full_name
RETURNING user_id, email, full_name, registered_at;
 user_id |          email           |     full_name     |         registered_at
---------+--------------------------+-------------------+-------------------------------
       1 | vahidusefzadeh@gmail.com | Vahid Yousefzadeh | 2026-11-24 11:09:01.753137+03
(1 row)

INSERT 0 1
Enter fullscreen mode Exit fullscreen mode

Because the existing name is Vahid Yousefzadeh and the proposed name is Vahid, the condition is true.
Notice that PostgreSQL returns the existing full name, not the proposed value. Now let's execute the statement with the same name as the existing record:

vahiddb=# INSERT INTO tbl_users AS u (email, full_name)
VALUES ('vahidusefzadeh@gmail.com', 'Vahid')
ON CONFLICT (email)
DO SELECT
WHERE u.full_name = EXCLUDED.full_name
RETURNING user_id, email, full_name, registered_at;
 user_id | email | full_name | registered_at
---------+-------+-----------+---------------
(0 rows)

INSERT 0 0
Enter fullscreen mode Exit fullscreen mode

The condition evaluates to false, so PostgreSQL does not return the conflicting row.
An important distinction: the WHERE condition filters the row returned by DO SELECT. It does not update the existing user's information.
Using IS DISTINCT FROM instead of != also handles NULL values correctly.
Locking the conflicting row
Sometimes retrieving an existing row is not sufficient. An application may need to ensure that the row cannot be modified by another transaction while it performs additional operations.
PostgreSQL 19 allows us to request a row-level lock directly in the DO SELECT action.
For example:

INSERT INTO tbl_users (email, full_name)
VALUES ('vahidusefzadeh@gmail.com', 'Vahid Yousefzadeh')
ON CONFLICT (email)
DO SELECT FOR UPDATE
RETURNING user_id, email, full_name;
Enter fullscreen mode Exit fullscreen mode

When a conflict occurs, PostgreSQL retrieves the existing row and locks it for update.
The lock is held until the transaction ends.
This is useful when an application needs to retrieve an existing record and then perform additional operations that depend on that record remaining protected from concurrent updates.
Other supported locking options are:

  1. - FOR UPDATE
  2. - FOR NO KEY UPDATE
  3. - FOR SHARE
  4. - FOR KEY SHARE

Without a locking clause, DO SELECT does not request a row-level lock on the conflicting row.
Using the returned user_id to create or update a profile
Now let's extend our example to a more realistic application scenario.
A user account contains basic registration information, while additional professional information is stored in a separate table.
Create a User Profile Table and Insert a Record:

vahiddb=# CREATE TABLE tbl_user_profiles (
    profile_id       BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    user_id          BIGINT NOT NULL UNIQUE REFERENCES tbl_users(user_id),
    city             VARCHAR(50),
    job_title        VARCHAR(100)
);
CREATE TABLE

vahiddb=# insert into tbl_user_profiles(user_id,city,job_title)
 values(1,'Babol','Database Administrator');
INSERT 0 1

vahiddb=# select * from tbl_user_profiles;
 profile_id | user_id | city  |       job_title
------------+---------+-------+------------------------
          5 |       1 | Babol | Database Administrator
(1 row)
Enter fullscreen mode Exit fullscreen mode

Now suppose the user submits another registration or profile request. We want to:
Insert the user if the email does not exist.
Retrieve the existing user's ID if the email already exists.
Create the profile if it does not exist.
Update the profile if it already exists.

We can implement this workflow using PostgreSQL 19's DO SELECT inside a PL/pgSQL block.

vahiddb=# BEGIN;
DO $$
DECLARE
    v_user_id BIGINT;
BEGIN
    INSERT INTO tbl_users (email, full_name)
    VALUES ('vahidusefzadeh@gmail.com', 'Vahid Yousefzadeh')
    ON CONFLICT (email)
    DO SELECT
    RETURNING user_id INTO v_user_id;

    INSERT INTO tbl_user_profiles (user_id, city, job_title)
    VALUES (
        v_user_id,
        'Sari',
        'PostgreSQL Administrator'
    )
    ON CONFLICT (user_id)
    DO UPDATE
    SET city = EXCLUDED.city,
        job_title = EXCLUDED.job_title;
END $$;

COMMIT;
BEGIN
DO
COMMIT
Enter fullscreen mode Exit fullscreen mode

Let's verify the profile:

vahiddb=# select * from tbl_user_profiles;
 profile_id | user_id | city |        job_title
------------+---------+------+--------------------------
          5 |       1 | Sari | PostgreSQL Administrator
(1 row)
Enter fullscreen mode Exit fullscreen mode

The workflow successfully retrieved the existing user's ID and used it to update the corresponding profile.

Conclusion

PostgreSQL 19's ON CONFLICT DO SELECT provides a simple and efficient way to insert a new row or retrieve an existing one without unnecessary updates. It makes common get-or-create operations easier to implement and maintain.

Top comments (0)