๐Ÿ—„๏ธ Databases

Upsert

Update + Insert

Update if it exists, insert if not: an atomic operation for handling data duplication and synchronization

๐Ÿ“– Detailed Explanation

Upsert is a compound word of "Update" and "Insert", and is a database feature that, in a single operation, updates data if it exists and inserts it as new if it does not. In the traditional "check with SELECT โ†’ UPDATE if it exists, INSERT if it does not" pattern, a race condition can occur between the two queries, but Upsert resolves this problem by processing atomically.

The syntax for implementing Upsert differs for each database. PostgreSQL uses `INSERT ... ON CONFLICT DO UPDATE`, MySQL uses `INSERT ... ON DUPLICATE KEY UPDATE` or `REPLACE INTO`, and SQL Server uses the `MERGE` statement. MongoDB provides the `upsert: true` option for `updateOne/updateMany`. Most ORMs also support an upsert method.

The core of Upsert is the "conflict detection key". You must specify which column is used to determine whether the data exists. In PostgreSQL, you specify a column that has a PRIMARY KEY or UNIQUE constraint in the `ON CONFLICT (column)` clause. Composite keys are also supported, and finer-grained conflict detection is also possible by combining with a partial index.

Particularly useful use cases for Upsert include external API data synchronization, state aggregation in event sourcing, cache updates, and updating a user's last activity time. Even when processing large volumes of data in bulk, it can be handled at once without checking the existence of each record individually, which contributes greatly to performance improvement.

๐Ÿ’ป Code Example

PostgreSQL: INSERT ON CONFLICT (recommended)

-- ํ…Œ์ด๋ธ” ์ƒ์„ฑ (email์ด UNIQUE)
CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    email VARCHAR(255) UNIQUE NOT NULL,
    name VARCHAR(255),
    login_count INT DEFAULT 0,
    last_login TIMESTAMP,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- ๊ธฐ๋ณธ Upsert: email ์ถฉ๋Œ ์‹œ name๊ณผ last_login ์—…๋ฐ์ดํŠธ
INSERT INTO users (email, name, last_login)
VALUES ('user@example.com', 'John Doe', NOW())
ON CONFLICT (email)
DO UPDATE SET
    name = EXCLUDED.name,
    last_login = EXCLUDED.last_login,
    updated_at = CURRENT_TIMESTAMP;

-- login_count ์ฆ๊ฐ€ํ•˜๋Š” Upsert
INSERT INTO users (email, name, login_count, last_login)
VALUES ('user@example.com', 'John Doe', 1, NOW())
ON CONFLICT (email)
DO UPDATE SET
    login_count = users.login_count + 1,
    last_login = EXCLUDED.last_login,
    updated_at = CURRENT_TIMESTAMP;

-- ์กฐ๊ฑด๋ถ€ ์—…๋ฐ์ดํŠธ (WHERE ์ ˆ)
INSERT INTO users (email, name)
VALUES ('user@example.com', 'New Name')
ON CONFLICT (email)
DO UPDATE SET
    name = EXCLUDED.name
WHERE users.name != EXCLUDED.name;  -- ์ด๋ฆ„์ด ๋‹ค๋ฅผ ๋•Œ๋งŒ ์—…๋ฐ์ดํŠธ

-- ์ถฉ๋Œ ์‹œ ์•„๋ฌด๊ฒƒ๋„ ์•ˆ ํ•จ (์‚ฝ์ž…๋งŒ ์‹œ๋„)
INSERT INTO users (email, name)
VALUES ('user@example.com', 'John Doe')
ON CONFLICT (email) DO NOTHING;

-- Upsert ๊ฒฐ๊ณผ ํ™•์ธ (RETURNING)
INSERT INTO users (email, name)
VALUES ('user@example.com', 'John Doe')
ON CONFLICT (email)
DO UPDATE SET name = EXCLUDED.name
RETURNING id, email,
    (xmax = 0) AS inserted;  -- true๋ฉด INSERT, false๋ฉด UPDATE

MySQL: ON DUPLICATE KEY UPDATE

-- MySQL ํ…Œ์ด๋ธ”
CREATE TABLE products (
    id INT PRIMARY KEY AUTO_INCREMENT,
    sku VARCHAR(50) UNIQUE NOT NULL,
    name VARCHAR(255),
    price DECIMAL(10,2),
    stock INT DEFAULT 0,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

-- ๊ธฐ๋ณธ Upsert
INSERT INTO products (sku, name, price, stock)
VALUES ('SKU-001', 'Product A', 29.99, 100)
ON DUPLICATE KEY UPDATE
    name = VALUES(name),
    price = VALUES(price),
    stock = VALUES(stock);

-- MySQL 8.0+: ๋ณ„์นญ ์‚ฌ์šฉ (VALUES() deprecated)
INSERT INTO products (sku, name, price, stock)
VALUES ('SKU-001', 'Product A', 29.99, 100) AS new_values
ON DUPLICATE KEY UPDATE
    name = new_values.name,
    price = new_values.price,
    stock = new_values.stock;

-- ์žฌ๊ณ  ์ฆ๊ฐ€ (๊ธฐ์กด ๊ฐ’ ํ™œ์šฉ)
INSERT INTO products (sku, name, price, stock)
VALUES ('SKU-001', 'Product A', 29.99, 50)
ON DUPLICATE KEY UPDATE
    stock = stock + VALUES(stock);

-- REPLACE INTO (์ฃผ์˜: ๊ธฐ์กด row ์‚ญ์ œ ํ›„ INSERT)
-- AUTO_INCREMENT๊ฐ€ ๋ณ€๊ฒฝ๋˜๊ณ  ์—ฐ๊ด€ CASCADE ์‚ญ์ œ ๋ฐœ์ƒ ๊ฐ€๋Šฅ
REPLACE INTO products (sku, name, price, stock)
VALUES ('SKU-001', 'Product A', 29.99, 100);

MongoDB: updateOne with upsert

// MongoDB upsert ์˜ˆ์ œ
const { MongoClient } = require('mongodb');

async function upsertExamples() {
    const client = new MongoClient('mongodb://localhost:27017');
    await client.connect();
    const db = client.db('myapp');
    const users = db.collection('users');

    // ๊ธฐ๋ณธ Upsert: email๋กœ ์ฐพ์•„์„œ ์—…๋ฐ์ดํŠธ, ์—†์œผ๋ฉด ์‚ฝ์ž…
    const result = await users.updateOne(
        { email: 'user@example.com' },  // ํ•„ํ„ฐ (์ฐพ์„ ์กฐ๊ฑด)
        {
            $set: {
                name: 'John Doe',
                lastLogin: new Date()
            },
            $setOnInsert: {
                // INSERT ์‹œ์—๋งŒ ์„ค์ •๋˜๋Š” ํ•„๋“œ
                createdAt: new Date(),
                loginCount: 0
            },
            $inc: {
                loginCount: 1  // ํ•ญ์ƒ ์ฆ๊ฐ€
            }
        },
        { upsert: true }  // upsert ํ™œ์„ฑํ™”
    );

    console.log(`Matched: ${result.matchedCount}, Modified: ${result.modifiedCount}, Upserted: ${result.upsertedCount}`);

    // ๋ฒŒํฌ Upsert (๋Œ€๋Ÿ‰ ์ฒ˜๋ฆฌ)
    const bulkOps = [
        { email: 'user1@example.com', name: 'User 1', status: 'active' },
        { email: 'user2@example.com', name: 'User 2', status: 'active' },
        { email: 'user3@example.com', name: 'User 3', status: 'inactive' }
    ].map(user => ({
        updateOne: {
            filter: { email: user.email },
            update: {
                $set: { name: user.name, status: user.status },
                $setOnInsert: { createdAt: new Date() }
            },
            upsert: true
        }
    }));

    const bulkResult = await users.bulkWrite(bulkOps);
    console.log(`Bulk upsert - Inserted: ${bulkResult.upsertedCount}, Modified: ${bulkResult.modifiedCount}`);

    // findOneAndUpdate with upsert (์—…๋ฐ์ดํŠธ๋œ ๋ฌธ์„œ ๋ฐ˜ํ™˜)
    const updatedUser = await users.findOneAndUpdate(
        { email: 'user@example.com' },
        {
            $set: { lastLogin: new Date() },
            $inc: { loginCount: 1 }
        },
        {
            upsert: true,
            returnDocument: 'after'  // ์—…๋ฐ์ดํŠธ ํ›„ ๋ฌธ์„œ ๋ฐ˜ํ™˜
        }
    );
    console.log(updatedUser);

    await client.close();
}

upsertExamples();

Python SQLAlchemy ORM Upsert

from sqlalchemy import create_engine, Column, Integer, String, DateTime, func
from sqlalchemy.orm import sessionmaker, declarative_base
from sqlalchemy.dialects.postgresql import insert as pg_insert
from sqlalchemy.dialects.mysql import insert as mysql_insert
from datetime import datetime

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True, autoincrement=True)
    email = Column(String(255), unique=True, nullable=False)
    name = Column(String(255))
    login_count = Column(Integer, default=0)
    last_login = Column(DateTime)
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)


# PostgreSQL Upsert
def upsert_user_postgres(session, email: str, name: str) -> User:
    """PostgreSQL ON CONFLICT DO UPDATE"""
    stmt = pg_insert(User).values(
        email=email,
        name=name,
        login_count=1,
        last_login=datetime.utcnow()
    )

    # ์ถฉ๋Œ ์‹œ ์—…๋ฐ์ดํŠธํ•  ์ปฌ๋Ÿผ ์ง€์ •
    stmt = stmt.on_conflict_do_update(
        index_elements=['email'],  # ์ถฉ๋Œ ๊ฐ์ง€ ์ปฌ๋Ÿผ
        set_={
            'name': stmt.excluded.name,
            'login_count': User.login_count + 1,
            'last_login': stmt.excluded.last_login,
            'updated_at': datetime.utcnow()
        }
    ).returning(User)

    result = session.execute(stmt)
    session.commit()
    return result.scalar_one()


# MySQL Upsert
def upsert_user_mysql(session, email: str, name: str) -> int:
    """MySQL ON DUPLICATE KEY UPDATE"""
    stmt = mysql_insert(User).values(
        email=email,
        name=name,
        login_count=1,
        last_login=datetime.utcnow()
    )

    stmt = stmt.on_duplicate_key_update(
        name=stmt.inserted.name,
        login_count=User.login_count + 1,
        last_login=stmt.inserted.last_login,
        updated_at=datetime.utcnow()
    )

    result = session.execute(stmt)
    session.commit()
    return result.lastrowid


# ๋ฒŒํฌ Upsert (PostgreSQL)
def bulk_upsert_users(session, users_data: list[dict]) -> int:
    """์—ฌ๋Ÿฌ ์‚ฌ์šฉ์ž๋ฅผ ํ•œ ๋ฒˆ์— upsert"""
    stmt = pg_insert(User).values(users_data)

    stmt = stmt.on_conflict_do_update(
        index_elements=['email'],
        set_={
            'name': stmt.excluded.name,
            'login_count': User.login_count + 1,
            'last_login': stmt.excluded.last_login,
            'updated_at': datetime.utcnow()
        }
    )

    result = session.execute(stmt)
    session.commit()
    return result.rowcount


# ์‚ฌ์šฉ ์˜ˆ์‹œ
if __name__ == "__main__":
    engine = create_engine("postgresql://user:pass@localhost/mydb")
    Session = sessionmaker(bind=engine)
    session = Session()

    # ๋‹จ์ผ upsert
    user = upsert_user_postgres(session, "john@example.com", "John Doe")
    print(f"Upserted user: {user.email}, login_count: {user.login_count}")

    # ๋ฒŒํฌ upsert
    users_data = [
        {"email": "user1@example.com", "name": "User 1", "login_count": 1, "last_login": datetime.utcnow()},
        {"email": "user2@example.com", "name": "User 2", "login_count": 1, "last_login": datetime.utcnow()},
        {"email": "user3@example.com", "name": "User 3", "login_count": 1, "last_login": datetime.utcnow()},
    ]
    count = bulk_upsert_users(session, users_data)
    print(f"Bulk upserted {count} users")

    session.close()

Redis: natural key-based Upsert

import redis
import json
from datetime import datetime

r = redis.Redis(host='localhost', port=6379, decode_responses=True)

# Redis๋Š” ๊ธฐ๋ณธ์ ์œผ๋กœ SET์ด upsert ๋™์ž‘
# ํ‚ค๊ฐ€ ์žˆ์œผ๋ฉด ๋ฎ์–ด์“ฐ๊ณ , ์—†์œผ๋ฉด ์ƒ์„ฑ

def upsert_user_session(user_id: str, session_data: dict):
    """์‚ฌ์šฉ์ž ์„ธ์…˜ upsert"""
    key = f"session:{user_id}"
    session_data['updated_at'] = datetime.utcnow().isoformat()

    # ๊ธฐ์กด ๋ฐ์ดํ„ฐ ์œ ์ง€ํ•˜๋ฉด์„œ ์—…๋ฐ์ดํŠธ (HSET)
    r.hset(key, mapping=session_data)
    r.expire(key, 3600)  # 1์‹œ๊ฐ„ TTL

def upsert_with_conditional(user_id: str, field: str, value: str):
    """์กฐ๊ฑด๋ถ€ upsert: ํ•„๋“œ๊ฐ€ ์—†์„ ๋•Œ๋งŒ ์„ค์ • (HSETNX)"""
    key = f"user:{user_id}"
    return r.hsetnx(key, field, value)  # 1์ด๋ฉด ์‚ฝ์ž…, 0์ด๋ฉด ์ด๋ฏธ ์กด์žฌ

def upsert_counter(key: str, increment: int = 1):
    """์นด์šดํ„ฐ upsert: ์—†์œผ๋ฉด ์ƒ์„ฑํ•˜๊ณ  ์ฆ๊ฐ€"""
    return r.incrby(key, increment)  # ํ‚ค๊ฐ€ ์—†์œผ๋ฉด 0์—์„œ ์‹œ์ž‘

# ์‚ฌ์šฉ ์˜ˆ์‹œ
upsert_user_session("user123", {
    "ip": "192.168.1.1",
    "user_agent": "Mozilla/5.0",
    "last_page": "/dashboard"
})

# ์ฒซ ๋กœ๊ทธ์ธ ์‹œ๊ฐ„์€ ์ตœ์ดˆ 1ํšŒ๋งŒ ์„ค์ •
upsert_with_conditional("user123", "first_login", datetime.utcnow().isoformat())

# ํŽ˜์ด์ง€๋ทฐ ์นด์šดํ„ฐ
page_views = upsert_counter("pageviews:homepage:2024-01-15")
print(f"Today's homepage views: {page_views}")

๐Ÿ—ฃ๏ธ How It's Said in Practice

  • "When synchronizing external API data, don't do SELECT followed by INSERT/UPDATE โ€” handle it all at once with upsert for better performance."
  • "Updating a user's last login time with upsert using ON CONFLICT DO UPDATE is handled without a race condition."
  • "Checking the existence of each record individually when bulk loading data is slow. Let's batch them up and process them with upsert."
  • "In PostgreSQL, if you use RETURNING, you can tell whether it was an insert or an update after the upsert."
  • "Please explain when upsert is needed and how it differs from a simple INSERT/UPDATE."
  • "What are the problems with the SELECT followed by INSERT/UPDATE pattern in a concurrent environment, and how does upsert solve them?"
  • "What is the difference between PostgreSQL's ON CONFLICT and MySQL's ON DUPLICATE KEY UPDATE?"
  • "What are the performance optimization strategies when upserting large volumes of data?"

Take a mock interview on this topic โ†’ WIA SOOM AI Interview ยท Start for free

  • "Here you do SELECT and then branch on a condition to INSERT/UPDATE, but this can be simplified with upsert."
  • "You specified a non-unique column in ON CONFLICT. Please check the unique constraint."
  • "You used VALUES() instead of EXCLUDED, but EXCLUDED is recommended in PostgreSQL 15+."
  • "MySQL REPLACE INTO is DELETE followed by INSERT, so AUTO_INCREMENT changes. Use ON DUPLICATE KEY."

โš ๏ธ Cautions

  • UNIQUE constraint required: Upsert absolutely requires a UNIQUE or PRIMARY KEY constraint to detect conflicts. If run without a constraint, a new row is inserted every time. When upserting with a composite key, there must be a UNIQUE index on that combination of columns.
  • Note on MySQL REPLACE INTO: REPLACE INTO looks like an upsert, but it is actually DELETE followed by INSERT. The AUTO_INCREMENT value changes, and if there is ON DELETE CASCADE, related data is deleted. In most cases, use ON DUPLICATE KEY UPDATE.
  • Interaction with triggers: During an upsert, INSERT/UPDATE triggers fire differently depending on the situation. In PostgreSQL, only the triggers corresponding to the operation actually performed (INSERT or UPDATE) are executed. If you have trigger logic, test the upsert behavior thoroughly.

๐Ÿ”— Related Terms

๐Ÿ“š Learn More