Upsert
Update if it exists, insert if not: an atomic operation for handling data duplication and synchronization
Update if it exists, insert if not: an atomic operation for handling data duplication and synchronization
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.
-- ํ
์ด๋ธ ์์ฑ (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 ํ
์ด๋ธ
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 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();
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()
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}")
Take a mock interview on this topic โ WIA SOOM AI Interview ยท Start for free