@@ -456,16 +456,24 @@ export async function executeQuery(
456456 offset,
457457 } )
458458
459+ // Skip the count sub-query if the count is already cached — saves a full table scan
460+ // on every page navigation after the first (page 2, 3, ... all share the same countCacheKey).
461+ const cachedCount = await cache . getCount ( countCacheKey )
459462 const [ rows , countResult ] = await Promise . all ( [
460463 qx . select ( mainQuery , params ) ,
461- qx . selectOne ( countQuery , params ) ,
464+ cachedCount === null ? qx . selectOne ( countQuery , params ) : Promise . resolve ( null ) ,
462465 ] )
463466
464- const count = parseInt ( countResult . count , 10 )
467+ const count = cachedCount !== null ? cachedCount : parseInt ( countResult ? .count ?? '0' , 10 )
465468 const memberIds = rows . map ( ( org ) => org . id )
466469
467470 if ( memberIds . length === 0 ) {
468- return { rows : [ ] , count, limit, offset }
471+ const emptyResult = { rows : [ ] , count, limit, offset }
472+ await Promise . all ( [
473+ cache . set ( cacheKey , emptyResult , 21600 ) ,
474+ cachedCount === null ? cache . setCount ( countCacheKey , count , 21600 ) : Promise . resolve ( ) ,
475+ ] )
476+ return emptyResult
469477 }
470478
471479 const [ memberOrganizations , identities , memberSegments , maintainerRoles ] = await Promise . all ( [
0 commit comments