How can we optimize DB query based on only argument passed in the Apollo GraphQL Query

On the server side, for every query if we are using findMany then by default it is fetching all the parameters/columns from the table, can I modify it somehow to pass only the sent parameters in the query and optimize it?


model Category {
  id         Int                @id @default(autoincrement())
  name       String             @unique
  createdAt  DateTime           @default(now())
  updatedAt  DateTime           @updatedAt
  iconURL    String?


query getCategory {
  getCategory {

Server Side:

prisma:query SELECT "public"."Category"."id", "public"."Category"."name", "public"."Category"."createdAt", "public"."Category"."updatedAt", "public"."Category"."iconURL" FROM "public"."Category" WHERE 1=1 ORDER BY "public"."Category"."name" ASC OFFSET $1

Hey @Jay_Bhatt, it looks like you’re using Prisma and if you are defining your schema based on Prisma, they might be better suited to help answer your question.

If you are defining the schema in another way and having Prisma be a backing datasource, it would look like you are only creating a resolver for Query.getCategory which is returning that prisma query. You would need to define further resolvers and possibly restructure your schema to make that work.

If you had a schema like this:

type Query {
  getCategory: [Category]
type Category {
  id: Int
  name: String

You could define your resolvers like this:

const resolvers = {
  Query: {
    getCategory(parent,args,context) {
      return context.prisma.query('query SELECT "public"."Category"."id" FROM "public"."Category" WHERE 1=1 ORDER BY "public"."Category"."name" ASC OFFSET $1'
  Category: {
    name({id}, args, context) {
      return context.prisma.query(`query SELECT "public"."Category"."id", "public"."Category"."name", "public"."Category"."createdAt", "public"."Category"."updatedAt", "public"."Category"."iconURL" FROM "public"."Category" WHERE "public"."Category"."id"=${id} ORDER BY "public"."Category"."name" ASC OFFSET $1`);

The resolvers are pseudocode, meaning they definitely won’t work. I’m just giving an example of creating a resolver for the type’s fields. Do you want to actually have multiple prisma queries like that? Probably not but you probably want to rearrange things around to get the optimization you like. Teams commonly do this by using @deprecated on the old field where the new field implements the design optimizations. You probably always want to sprinkle in dataloader for this stuff.

If you want to talk about it more, join us in our new Discord server and feel free to ping me (@watson).