Skip to content

Commit

Permalink
fix: wrap DISTINCT ON in subquery to restore createdAt ordering
Browse files Browse the repository at this point in the history
PostgreSQL's DISTINCT ON requires ORDER BY to start with the DISTINCT
column, so the outer query must re-order by createdAt DESC for proper
pagination ordering (most recent threads first).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
  • Loading branch information
Eliezer Steinbock and Claude Opus 4.5 committed Jan 6, 2026
1 parent 851f37d commit 140a1bc
Showing 1 changed file with 10 additions and 7 deletions.
17 changes: 10 additions & 7 deletions apps/web/app/(app)/[emailAccountId]/reply-zero/fetch-trackers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,16 @@ export async function getPaginatedThreadTrackers({

const [trackers, total] = await Promise.all([
prisma.$queryRaw<ThreadTracker[]>`
SELECT DISTINCT ON ("threadId") *
FROM "ThreadTracker"
WHERE "emailAccountId" = ${emailAccountId}
AND "resolved" = false
AND "type" = ${type}::text::"ThreadTrackerType"
${dateClause}
ORDER BY "threadId", "createdAt" DESC
SELECT * FROM (
SELECT DISTINCT ON ("threadId") *
FROM "ThreadTracker"
WHERE "emailAccountId" = ${emailAccountId}
AND "resolved" = false
AND "type" = ${type}::text::"ThreadTrackerType"
${dateClause}
ORDER BY "threadId", "createdAt" DESC
) AS distinct_threads
ORDER BY "createdAt" DESC
LIMIT ${PAGE_SIZE}
OFFSET ${skip}
`,
Expand Down

0 comments on commit 140a1bc

Please sign in to comment.