© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
Drizzle TeamDT
Drizzle Team•3y ago•
27 replies
SKUZZIE

Upsert with multi-column unique index?

What is the correct way to do an upsert with a multi-column unique index?
I have this model:
export const dailyStats = pgTable(
  "daily_stats",
  {
    ad_id: text("ad_id")
      .references(() => ads.id)
      .primaryKey(),
    created_at: timestamp("created_at").notNull().defaultNow(),
    updated_at: timestamp("updated_at").notNull().defaultNow(),

    date: date("date").notNull(),

    ...statObject,
  },
  (t) => ({
    ad_and_date: uniqueIndex("ad_and_date").on(t.ad_id, t.date),
  })
);
export const dailyStats = pgTable(
  "daily_stats",
  {
    ad_id: text("ad_id")
      .references(() => ads.id)
      .primaryKey(),
    created_at: timestamp("created_at").notNull().defaultNow(),
    updated_at: timestamp("updated_at").notNull().defaultNow(),

    date: date("date").notNull(),

    ...statObject,
  },
  (t) => ({
    ad_and_date: uniqueIndex("ad_and_date").on(t.ad_id, t.date),
  })
);


And I'm trying to do an upsert like this:
await db
        .insert(dailyStats)
        .values({
          ad_id: dbAd.id,
          date: date.toISOString(),
          ...dailyStatsInsert,
        })
        .onConflictDoUpdate({
          target: [dailyStats.ad_id, dailyStats.date],
          set: dailyStatsInsert,
        });
await db
        .insert(dailyStats)
        .values({
          ad_id: dbAd.id,
          date: date.toISOString(),
          ...dailyStatsInsert,
        })
        .onConflictDoUpdate({
          target: [dailyStats.ad_id, dailyStats.date],
          set: dailyStatsInsert,
        });


But I'm getting the
duplicate key value violates unique constraint
duplicate key value violates unique constraint
error even though I have the
target
target
of the
onConflictDoUpdate
onConflictDoUpdate
set to those two columns.

What am I doing wrong?
Drizzle TeamJoin
The official Discord for all Drizzle related projects, such as Drizzle ORM, Drizzle Kit, Drizzle Studio and more!
11,879Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

upsert with excluded using column name
Drizzle TeamDTDrizzle Team / help
2y ago
Unique Index Constraints with Multiple Columns
Drizzle TeamDTDrizzle Team / help
12mo ago
bug: three column unique index no change never detected
Drizzle TeamDTDrizzle Team / help
3y ago
Set unique index length
Drizzle TeamDTDrizzle Team / help
3y ago