one prisma findMany with three includes takes 4.2s, hand written sql is 80ms Prisma
Postgres 16, about 120k rows in the child table. The call is findMany({ where: { orgId }, include: { items: true, tags: true, owner: true }, take: 50 }). pg_stat_statements shows four separate statements, and the slow one is a select on items with an IN list of 50 ids doing a sequential scan. The equivalent single query with joins that I wrote by hand runs in 80ms. Is this just what the ORM does?
@layer_shift_lu · 2mo ago · 3 replies
Separate queries per relation is the default strategy, yes — it fetches parents, then children with an
IN, and stitches them in JS. That is usually fine. What is not fine is the sequential scan.Check for an index on
items.post_id. Prisma creates the foreign key constraint but not an index on the referencing column, and Postgres does not create one for you either. An unindexed FK plus anINlist of 50 is exactly the 4-second shape you are describing.Secondary: turn on the relation-join strategy if you want a single query with lateral joins, and stop using bare
includein favour ofselectso you are not shipping every column of three tables to render a list.Reply
Report
@gradschool_gary · 2mo ago
There was no index on
items.post_id. Added it, 4.2s to 110ms, no other changes. Feeling both relieved and stupid, which I gather is the standard outcome here.Reply
Report
@peer_review_pat · 2mo ago
It is the single most common slow query I get asked about. People add
@relationand assume the index came with it. Worth a one-off audit query listing FK columns with no index — most codebases have a few.Reply
Report