© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
Drizzle TeamDT
Drizzle Team•9mo ago•
7 replies
Deen24ID

Issues from a WITH clause (CTE).

I have the following postgreSQL schema:

export const price = pgTable("price", {
  id: uuid().primaryKey().defaultRandom().notNull(),
  name: varchar({ length: 255 }).notNull(),
  buy: integer().notNull(),
  sell: integer().notNull(),
  lastUpdatedAt: timestamp({ withTimezone: true, mode: "string" })
    .defaultNow()
    .notNull(),
});
export const price = pgTable("price", {
  id: uuid().primaryKey().defaultRandom().notNull(),
  name: varchar({ length: 255 }).notNull(),
  buy: integer().notNull(),
  sell: integer().notNull(),
  lastUpdatedAt: timestamp({ withTimezone: true, mode: "string" })
    .defaultNow()
    .notNull(),
});


In the entries the same name can be repeated in many rows. For each name, I just want to keep the rows with the highest
lastUpdatedAt
lastUpdatedAt
, keeping other columns along. I can get these values using the following SQL query:

WITH priceLast as (SELECT name, MAX(price."lastUpdatedAt") as lastUpdatedAt FROM price GROUP BY name)
SELECT 
  price.id as id, 
  priceLast.name as name, 
  priceLast.lastUpdatedAt as lastUpdatedAt,
  price.buy as buy,
  price.sell as sell
FROM priceLast INNER JOIN price ON
priceLast.lastupdatedat = price."lastUpdatedAt" AND priceLast.name = price.name
WITH priceLast as (SELECT name, MAX(price."lastUpdatedAt") as lastUpdatedAt FROM price GROUP BY name)
SELECT 
  price.id as id, 
  priceLast.name as name, 
  priceLast.lastUpdatedAt as lastUpdatedAt,
  price.buy as buy,
  price.sell as sell
FROM priceLast INNER JOIN price ON
priceLast.lastupdatedat = price."lastUpdatedAt" AND priceLast.name = price.name


But, I can't rewrite this in drizzle. Any help is greatly appreciated. Thanks!
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

Getting type from a CTE
Drizzle TeamDTDrizzle Team / help
10mo ago
INSERT with CTE
Drizzle TeamDTDrizzle Team / help
2mo ago
Update with CTE
Drizzle TeamDTDrizzle Team / help
8mo ago
CTE / WITH + alias
Drizzle TeamDTDrizzle Team / help
13mo ago