What is the difference between `add()`, `merge()`, and `add_all()` in SQLAlchemy?

Beginner

Answer

  • add(): Adds a single new object to the session. If object already exists, raises an error.
  • merge(): Merges the state of an object into the session. If object exists, updates it; if not, creates new one.
  • add_all(): Adds multiple objects to the session at once.
# add() - for new objects
session.add(User(name="Alice"))
# merge() - for existing or uncertain objects
user = session.merge(User(id=1, name="Updated Alice"))
# add_all() - for multiple objects
session.add_all([User(name="Bob"), User(name="Charlie")])