Updating Records

Replacing a Record

You can overwrite a full record with a request like this:

  const user = await xata.db.Users.createOrReplace("myid", { name: "Keanu Reeves" });

Note that in the above example, the whole record was overwritten. If you want to update only some of the fields, see the Partial Update section below. Also, the xata.version field was automatically incremented to 1. We'll talk more about this special column in the Optimistic Concurrency Control section.

Partial Update

In order to do a partial update to a record, you can use a request like this:

const user = await xata.db.Users.update("myid", { email: "newemail@example.com" });

// or, using the `update` method on the record object:

user.update({ email: "newemail@example.com" })

It's also possible to update a record if it exists, or create it if it doesn't exist:

  const user = await xata.db.Users.createOrUpdate("myid", {name: "Keanu Reave"});

Optimistic Concurrency Control

After executing a request, you will notice that the version field of the record is incremented automatically. In the TypeScript SDK, you can read the version by using the getMetadata() method on the record object. In the REST API, it is returned as the special column xata.version.

  // { version: 2}

The version field can be used to perform optimistic concurrency control, also known as "optimistic locking". Let's say you have two users of your web applications that are both trying to update the same record. They both retrieve the record at version 0, modify a field, and then write it back. Without locking or version checks, it's possible that the users will overwrite each other's changes.

To prevent this, you can pass the ifVersion parameter to the PUT request. The value for ifVersion should be the value of xata.version from when you retrieved the record. For example, if you want to update the record only if the version is 0, you can send the following request:

  const updatedUser = await xata.db.Users.update(
     name: "Keanu Reave",
     email: "keanu@xata.io",
     ifVersion: 0,

If someone else has updated the record since you have read it, the API will get a 422 Unprocessable Entity response:

  "message": "version condition not met",
  "status": 422

In this case, the TypeScript SDK, returns null.

The way to treat this error depends on your application. You might be able to re-read the record, resolve the conflict, and then re-try the update. Or you might need to show the user a conflict error message.

Next Steps

Great! We can now update data safely in our databases. Let's now explore how we delete data from a database. Alternatively, we can also look into updating data or inserting data. We've got guides for each of these operations.