Skip to content

Upserts — Examples

Insert a row, or update it if it already exists — in one round trip. AQL’s unless conflict clause lowers to PostgreSQL’s ON CONFLICT (Insert → Conflicts).

insert User { email := $email }
unless conflict on .email
else (update User set { email := $email });

compiles to:

INSERT INTO "user" ("email")
VALUES ($1)
ON CONFLICT ("email") DO UPDATE SET "email" = $1
RETURNING "created_at", "email", "id", "role", "updated_at";

The conflict target .email must be a unique/exclusive column:

type User extends Base {
required email: str { constraint exclusive; };
}

Drop the else arm to make a conflicting insert a no-op (DO NOTHING) — handy for idempotent seeds:

insert User { email := $email } unless conflict;

Save the upsert as upsert_user.aql; the returned row is the inserted-or-updated User:

const user = await runner.query.upsertUser({ email }); // UpsertUserRow | null