Applications often need to create a database record only if it doesn't already exist. This operation is commonly called get-or-create. It appears in user registration, order processing, event ingestion, synchronization jobs, and many other database workflows.
For example, an application may receive an external customer identifier. Before creating a new customer record, it needs to check whether that identifier is already stored. If the record exists, the application should reuse it. Otherwise, it should insert a new record and return its database identifier.
A straightforward implementation performs a SELECT query followed by an INSERT query when no record is found. Although this approach looks simple, it introduces additional database round trips and can create race conditions when multiple requests execute simultaneously.
PostgreSQL provides INSERT ... ON CONFLICT for handling uniqueness conflicts safely. With the newer RETURNING capabilities available in PostgreSQL 19, applications can also retrieve the existing or newly inserted row through a more direct database operation.
This article explains how to implement get-or-create operations using PostgreSQL and Npgsql, how to avoid unnecessary round trips, and what developers should consider when designing this pattern for production applications.
Understanding the Traditional Get-or-Create Approach
Consider an application that stores external customers.
CREATE TABLE customers
(
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
external_id VARCHAR(100) NOT NULL UNIQUE,
customer_name VARCHAR(200) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
The external_id column has a unique constraint because the application must not create multiple records for the same external customer.
A traditional get-or-create implementation first searches for the customer.
SELECT id
FROM customers
WHERE external_id = @externalId;
If the query returns no row, the application executes another statement.
INSERT INTO customers
(
external_id,
customer_name
)
VALUES
(
@externalId,
@customerName
)
RETURNING id;
This requires at least two database round trips when the customer does not exist. When the customer already exists, it requires one round trip.
The application also needs to handle a concurrency problem.
Imagine two API requests arriving at almost the same time with the same external customer identifier. Both requests execute the SELECT statement and find no record. Both then attempt to insert the customer.
Because external_id has a unique constraint, one insertion succeeds and the other receives a uniqueness violation.
The application can catch that exception and query the record again, but this introduces additional code and database communication.
A better approach is to let PostgreSQL handle the conflict as part of the insertion operation.
Using INSERT ON CONFLICT for Get-or-Create
PostgreSQL supports INSERT ... ON CONFLICT, which allows an application to define what should happen when an insertion violates a unique constraint.
The basic statement looks like this:
INSERT INTO customers
(
external_id,
customer_name
)
VALUES
(
@externalId,
@customerName
)
ON CONFLICT (external_id)
DO NOTHING
RETURNING id;
If the customer does not exist, PostgreSQL inserts the row and returns its identifier.
If the customer already exists, PostgreSQL performs no insertion. In that case, RETURNING does not return the existing row because no row was inserted or updated.
This is an important detail. ON CONFLICT DO NOTHING prevents duplicate records, but it does not automatically return the identifier of the existing record.
A common solution is to use a second SELECT statement within the same SQL command.
WITH inserted AS
(
INSERT INTO customers
(
external_id,
customer_name
)
VALUES
(
@externalId,
@customerName
)
ON CONFLICT (external_id)
DO NOTHING
RETURNING id
)
SELECT id
FROM inserted
UNION ALL
SELECT id
FROM customers
WHERE external_id = @externalId
LIMIT 1;
This statement attempts the insertion and returns the identifier from either the inserted row or the existing record.
However, there is an important concurrency detail with this approach. Under PostgreSQL's default READ COMMITTED isolation level, the INSERT may wait for a concurrent transaction to finish, but the SELECT portion of the same statement uses the snapshot taken when the statement started. If the conflicting row was not visible in that snapshot, the SELECT may not find it.
Therefore, this pattern should not be treated as a universal concurrency-safe get-or-create solution under all concurrent workloads.
Understanding PostgreSQL 19 RETURNING OLD and NEW
PostgreSQL 19 introduces additional capabilities for INSERT ... ON CONFLICT ... RETURNING that make it possible to distinguish between the existing row and the proposed row.
The RETURNING clause can expose old and new row values. For an insertion, the new row represents the inserted data. When an ON CONFLICT DO UPDATE action occurs, the old row represents the conflicting row before the update, while the new row represents the resulting row.
For a get-or-create operation, the application can use a no-op conflict update and return the existing identifier when a conflict occurs.
For example:
INSERT INTO customers AS current_customer
(
external_id,
customer_name
)
VALUES
(
@externalId,
@customerName
)
ON CONFLICT (external_id)
DO UPDATE
SET external_id = current_customer.external_id
RETURNING
id,
old.id AS existing_id,
new.id AS resulting_id;
The exact RETURNING expressions should be chosen according to the required result. The old and new row references allow the statement to distinguish an inserted row from a row that was already present.
A simpler application-facing result can return the identifier from the resulting row:
INSERT INTO customers AS current_customer
(
external_id,
customer_name
)
VALUES
(
@externalId,
@customerName
)
ON CONFLICT (external_id)
DO UPDATE
SET external_id = current_customer.external_id
RETURNING id;
This returns the identifier for both the inserted and conflicting row.
The conflict action performs a no-op update to the existing external_id value. It does not change the customer's name or other business information.
This is useful because it provides one database command that returns the required identifier, including when concurrent requests attempt to create the same record.
However, a no-op update is still an UPDATE from PostgreSQL's perspective. It can create a new row version, generate write-ahead log activity, execute update triggers, and contribute to table bloat. It should not be used without considering those effects.
Implementing Get-or-Create With Npgsql
Npgsql is the PostgreSQL data provider for .NET. It allows C# applications to execute PostgreSQL commands using familiar ADO.NET APIs.
Install the Npgsql package in the application.
dotnet add package Npgsql
Create a service that accepts an NpgsqlDataSource through dependency injection.
using Npgsql;
public class CustomerRepository
{
private readonly NpgsqlDataSource _dataSource;
public CustomerRepository(NpgsqlDataSource dataSource)
{
_dataSource = dataSource;
}
public async Task<long> GetOrCreateCustomerAsync(
string externalId,
string customerName,
CancellationToken cancellationToken = default)
{
const string sql = """
INSERT INTO customers AS current_customer
(
external_id,
customer_name
)
VALUES
(
@externalId,
@customerName
)
ON CONFLICT (external_id)
DO UPDATE
SET external_id = current_customer.external_id
RETURNING id;
""";
await using var connection =
await _dataSource.OpenConnectionAsync(cancellationToken);
await using var command =
new NpgsqlCommand(sql, connection);
command.Parameters.AddWithValue(
"externalId",
externalId);
command.Parameters.AddWithValue(
"customerName",
customerName);
object? result =
await command.ExecuteScalarAsync(cancellationToken);
return Convert.ToInt64(result);
}
}
The repository performs one SQL command and retrieves the customer identifier through ExecuteScalarAsync.
NpgsqlDataSource is designed to be reused across the application. It manages connection pooling and provides a convenient way to create database connections without manually maintaining a single open connection.
A typical application registration looks like this:
builder.Services.AddSingleton(
NpgsqlDataSource.Create(
builder.Configuration.GetConnectionString("PostgreSQL")!));
builder.Services.AddScoped<CustomerRepository>();
The data source should be registered once and reused. Creating a new data source for every request is unnecessary and can interfere with efficient connection pooling.
Understanding the Trade-Off of a No-Op Update
The previous implementation is convenient, but developers should understand what happens when the customer already exists.
PostgreSQL does not treat the conflict action as a read-only operation. Even when the assigned value is identical to the existing value, the statement follows the UPDATE path.
This can have several consequences:
- Update triggers may execute.
- Row-level auditing logic may record an update.
- A new row version may be created.
- Additional write-ahead log activity may occur.
- Frequently executed operations may increase table maintenance requirements.
For a small lookup table or a workflow with relatively low conflict frequency, this may be an acceptable trade-off.
For a high-volume table receiving thousands of repeated get-or-create operations, unnecessary updates may become expensive.
The correct approach depends on the workload, table design, trigger behavior, and operational requirements.
Alternative: Use a Two-Statement Strategy When Updates Must Be Avoided
If the application must avoid no-op updates, a two-statement strategy is often easier to reason about.
First, attempt the insertion without modifying an existing row.
INSERT INTO customers
(
external_id,
customer_name
)
VALUES
(
@externalId,
@customerName
)
ON CONFLICT (external_id)
DO NOTHING
RETURNING id;
If an identifier is returned, the record was inserted successfully.
If no identifier is returned, execute a separate SELECT statement.
SELECT id
FROM customers
WHERE external_id = @externalId;
The application performs an additional round trip only when a conflict occurs.
This approach avoids unnecessary updates and their associated side effects.
It also handles the concurrent insertion scenario more clearly because the SELECT runs as a separate statement under READ COMMITTED isolation and receives a new statement snapshot.
For workloads where conflicts are uncommon, this may be a better design than performing an update for every existing record.
Choosing the Right Strategy
Different get-or-create implementations have different costs and behavior.
| Strategy |
Database commands |
Updates existing row |
Main consideration |
| SELECT followed by INSERT |
Up to 2 |
No |
Vulnerable to concurrent insertion without additional handling |
| INSERT ON CONFLICT DO NOTHING followed by SELECT |
1 or 2 |
No |
Extra round trip only when the row already exists |
| INSERT ON CONFLICT DO UPDATE with RETURNING |
1 |
Yes |
Convenient result retrieval but creates update side effects |
| Application-level retry after uniqueness conflict |
Variable |
No |
Requires careful exception handling and retry logic |
The number of commands alone should not determine the implementation.
A single statement that generates unnecessary writes may be less efficient than two statements that avoid modifying existing records. Measure the actual workload and consider the cost of network communication, locking, row versions, triggers, and database maintenance.
Handling Important Production Scenarios
A production get-or-create implementation should be designed around the database's actual uniqueness rules.
The unique constraint must exist in PostgreSQL. Checking for an existing record in application code is not a replacement for database-level uniqueness.
Also, the conflict target should match the intended business key. If customer identity depends on both tenant_id and external_id, the table should enforce a composite unique constraint.
ALTER TABLE customers
ADD CONSTRAINT uq_customers_tenant_external
UNIQUE (tenant_id, external_id);
The insertion should then use the same conflict target.
ON CONFLICT (tenant_id, external_id)
DO NOTHING
Another important consideration is whether an existing record should retain its original values. A get-or-create operation normally returns an existing record without changing its business data. If the application also needs to refresh the customer name, that should be treated as a separate update requirement rather than hidden inside the get-or-create operation.
Finally, use parameterized SQL for all external values. Npgsql parameters protect the application from SQL injection and avoid manually constructing SQL statements from user input.
Testing Get-or-Create Behavior
A repository test should cover both the insertion and conflict scenarios.
The first test verifies that a new customer is created and an identifier is returned. The second test calls the operation again with the same external identifier and verifies that the same database record is returned.
For concurrency testing, execute multiple requests using the same external identifier and verify that the database contains only one matching customer.
These tests should run against a real PostgreSQL instance rather than relying only on an in-memory substitute. Features such as unique constraints, ON CONFLICT, transaction isolation, and RETURNING behavior are database-specific and should be tested against PostgreSQL itself.
Also verify that the chosen implementation behaves correctly when update triggers are enabled and when the application uses a different transaction isolation level.
Summary
Get-or-create is a common database operation, but implementing it with a separate SELECT and INSERT can introduce unnecessary round trips and concurrency problems.
PostgreSQL's INSERT ... ON CONFLICT provides a reliable foundation for handling uniqueness conflicts. The newer RETURNING capabilities in PostgreSQL 19 make it possible to retrieve information about inserted and conflicting rows more directly.
With Npgsql, developers can execute these statements using parameterized SQL and retrieve the resulting identifier through a single database command.
A no-op conflict update is convenient when one-statement retrieval is important, but it still has the side effects of an UPDATE. When avoiding unnecessary writes is more important, INSERT ... DO NOTHING followed by a SELECT on conflict is often a better choice.
The best implementation depends on the application's concurrency requirements, database workload, and business rules. A good get-or-create design should protect data integrity first, minimize unnecessary database work, and make its behavior clear to the application.
Join the conversation! Your thoughts help the community grow.