Hi @Tanavya 👋

Why doesn't the original method work? Am I misunderstanding something?

The original method you attempted, which included both select and include operations, didn't produce the desired result because the select operation is primarily used to specify which scalar fields to include in the query result, while the include operation is used to specify related models or fields to include in the query result.

When you used both select and include together in the validator definition, the include operation might have overridden the select operation, resulting in all fields being included in the generated type, including those specified in the select operation.

In contrast, when you used only the select operation in the validator definition:

const userArgs = Prisma.validator<Prisma.UserDefaultArgs>()({
  select: { email: true, name: true, posts: true },
});

You explicitly specified the fields you wanted to include in the generated type, which ensured that only those fields were included and that the include operation didn't interfere with the selection of scalar fields.

How do I get a type where some fields are optional and can also include relations? For example to reiterate, for my use case I would like fields like id, createdAt, updatedAt to be optional. So I want a more general type like UserModel which includes relations and each sub-model and the "root" level User model can have fields that can be undefined, but are still required in the schema. This way I can use the same model as both input and output for create and get methods.

If you want to create a type where some fields are optional and can also include relations, you would have to manually create these types in your application code. Here's an example:

type PartialUser = Partial<Prisma.UserCreateInput & {{
  posts: Prisma.PostCreateNestedManyWithoutAuthorInput;
}}>;

In this example, PartialUser is a type that includes all fields of the User model and the posts relation, and all these fields are optional. However, this approach increases the maintenance burden upon changes to the Prisma schema as you need to manually maintain the types.

🌐
Prisma
prisma.io › home › select fields › select fields › select fields › select fields
Select fields | Prisma Documentation
By default, Prisma Client returns all scalar fields for a model and no relations. Use select and include to make the result smaller, clearer, and more intentional.
🌐
Brendonovich
prisma.brendonovich.dev › reading-data › select-include
Select & Include - Prisma Client Rust - Brendonovich
This is why the select and include functions aren't just structs, they can be passed arguments defined within the macros using the following syntax: post::include!((filters: Vec<comment::WhereParam>, skip: i64, take: i64) => post_with_comments { comments(filters).skip(skip).take(take) }) async fn do_query() -> Vec<post_only_title::Data> { let filters = vec![comment::content::contains("prisma".to_string())]; let skip = 5; let take = 5; client .post() .find_many(vec![]) .select(post_only_title::select(filters, skip, take)) .exec() .await .unwrap() } // Generated type is equivalent to pub mod post_with_comments { pub struct Data { id: String, title: String, comments: Vec<comment::Data> } pub fn select(filters: Vec<comment::WhereParam>, skip: i64, take: i64) // return type is an internal detail }
Discussions

node.js - NestJS Prisma ORM - Using 'select' versus 'include' when fetching data records? - Stack Overflow
I'm trying to fetch data records from a Postgres database in NestJS (Node.JS environment). I'm using Prisma as my Object Relational Mapper (ORM) in TypeScript. I'm having trouble choosing which que... More on stackoverflow.com
🌐 stackoverflow.com
PrismaClientValidationError: "Please either use include or select, but not both at the same time."
If your code runs successfully without the "Please either use include or select, but not both at the same time." error, then Prisma might have changed its behavior in recent versions. More on github.com
🌐 github.com
1
February 13, 2025
Optionally Including 'select' and 'include'
I've gotten myself in a bind trying to create a method that works on top of Prisma's API. The problem I have is trying to create a single method to handle both 'select' and 'include', From my under... More on github.com
🌐 github.com
2
2
May 29, 2020
Confusion about Include and select API
Hi everyone, I am a beginner and I read document but have confusion: What's the meaning of “include” and what is the difference between “select” and “include”. Thank you More on github.com
🌐 github.com
2
1
June 8, 2022
Top answer
1 of 1
4

Hi @Tanavya 👋

Why doesn't the original method work? Am I misunderstanding something?

The original method you attempted, which included both select and include operations, didn't produce the desired result because the select operation is primarily used to specify which scalar fields to include in the query result, while the include operation is used to specify related models or fields to include in the query result.

When you used both select and include together in the validator definition, the include operation might have overridden the select operation, resulting in all fields being included in the generated type, including those specified in the select operation.

In contrast, when you used only the select operation in the validator definition:

const userArgs = Prisma.validator<Prisma.UserDefaultArgs>()({
  select: { email: true, name: true, posts: true },
});

You explicitly specified the fields you wanted to include in the generated type, which ensured that only those fields were included and that the include operation didn't interfere with the selection of scalar fields.

How do I get a type where some fields are optional and can also include relations? For example to reiterate, for my use case I would like fields like id, createdAt, updatedAt to be optional. So I want a more general type like UserModel which includes relations and each sub-model and the "root" level User model can have fields that can be undefined, but are still required in the schema. This way I can use the same model as both input and output for create and get methods.

If you want to create a type where some fields are optional and can also include relations, you would have to manually create these types in your application code. Here's an example:

type PartialUser = Partial<Prisma.UserCreateInput & {{
  posts: Prisma.PostCreateNestedManyWithoutAuthorInput;
}}>;

In this example, PartialUser is a type that includes all fields of the User model and the posts relation, and all these fields are optional. However, this approach increases the maintenance burden upon changes to the Prisma schema as you need to manually maintain the types.

Top answer
1 of 1
25

It's explained in the documentations of Select fields and Relation Queries That include and select have different usage:

By default, when a query returns records [..], the result includes the default selection set:

All scalar fields defined in the Prisma schema [..and] None of the relations

To change this behavior, you can use:

(1) Select:

allows you to either return a limited subset of fields instead of all fields:

const getUser: object | null = await prisma.user.findUnique({
  where: {
    id: 22,
  },
  select: {
    email: true,
    name: true,
  },
})

// Result
{
  name: "Alice",
  email: "[email protected]",
}

or include relations and select relation fields (nested usage):

const users = await prisma.user.findMany({
  select: {
    name: true,
    posts: {
      select: {
        title: true,
      },
    },
  },
})

(2) Include:

allows you to return some or all relation fields (which are not returned by default as mentioned before):

const getPosts = await prisma.post.findMany({
  where: {
    title: {
      contains: 'cookies',
    },
  },
  include: {
    author: true, // Return all fields
  },
})

// Result:
;[
  {
    id: 17,
    title: 'How to make cookies',
    published: true,
    authorId: 16,
    comments: null,
    views: 0,
    likes: 0,
    author: {
      id: 16,
      name: null,
      email: '[email protected]',
      profileViews: 0,
      role: 'USER',
      coinflips: [],
    },
  },
  {
    id: 21,
    title: 'How to make cookies',
    published: true,
    authorId: 19,
    comments: null,
    views: 0,
    likes: 0,
    author: {
      id: 19,
      name: null,
      email: '[email protected]',
      profileViews: 0,
      role: 'USER',
      coinflips: [],
    },
  },
]

(3) Select within Include:

Finally, you can use Select within Include, to return a subset of the relation fields.

const users = await prisma.user.findMany({
  // Returns all user fields
  include: {
    posts: {
      select: {
        title: true,
      },
    },
  },
})
🌐
Prisma
prisma.io › home › relation queries › relation queries › relation queries › relation queries
Relation queries (Concepts) | Prisma Documentation
Nested reads allow you to read related data from multiple tables in your database - such as a user and that user's posts. You can: Use include to include related records, such as a user's posts or profile, in the query response. Use a nested ...
🌐
Prisma
prisma.io › home › crud › crud › crud › crud
CRUD (Reference) | Prisma Documentation
June 3, 2022 - const tablenames = await prisma.$queryRaw< Array<{ tablename: string }> >`SELECT tablename FROM pg_tables WHERE schemaname='public'`; const tables = tablenames .map(({ tablename }) => tablename) .filter((name) => name !== "_prisma_migrations") .map((name) => `"public"."${name}"`) .join(", "); try { await prisma.$executeRawUnsafe(`TRUNCATE TABLE ${tables} CASCADE;`); } catch (error) { console.log({ error }); } ... const u = await prisma.user.create({ include: { posts: { include: { categories: true, }, }, }, data: { email: "emma@prisma.io", posts: { create: [ { title: "My first post", categories
🌐
GitHub
github.com › prisma › prisma › issues › 26324
PrismaClientValidationError: "Please either use include or select, but not both at the same time." · Issue #26324 · prisma/prisma
February 13, 2025 - This code, however, produces a compile-time error: Type '{ include: { user: true; }; select: { id: true; name: true; }; }' is not assignable to type '"Please either choose select or include."'.' const pattern3 = await this.prismaService.courses.findFirst({ select: { id: true, title: true, user: { select: { id: true, name: true, courses: true } } } });
Author   prisma
Find elsewhere
🌐
PalJS
paljs.com › plugins › select
GraphQL Enhancement Plugins | Packages | PalJS
// Fetches ALL fields and ALL relations const users = await prisma.user.findMany({ include: { posts: { include: { comments: { include: { author: true } } } }, profile: true, }, }); ... // Only fetches fields requested in the GraphQL query const select = new PrismaSelect(info).value; const users = await prisma.user.findMany(select); // For query: { users { id email posts { title } } } // Generates: { select: { id: true, email: true, posts: { select: { title: true } } } }
🌐
GitHub
github.com › prisma › prisma › discussions › 2603
Optionally Including 'select' and 'include' · prisma/prisma · Discussion #2603
May 29, 2020 - Please either use `include` or `select`, but not both at the same time. Is there a problem with my implementation or potentially a better way to go about this? Beta Was this translation helpful? Give feedback. ... That pointed me in the right direction. Thanks for the help! ... There was an error while loading. Please reload this page. Something went wrong. There was an error while loading. Please reload this page. ... async function main(select?: Prisma.UserSelect, include?: Prisma.UserInclude) { await prisma.user.create({ data: { email: 'u1@g.com', password: 'user1', }, ...(!select && include && { include }), ...(!include && select && { select }), }) } main({ name: true, })
Author   prisma
🌐
DEV Community
dev.to › this-is-learning › its-prisma-time-select-3lie
It's Prisma Time - Select - DEV Community
January 11, 2022 - const posts = await prisma.post.findMany({ include: { authors: { select: { author: true, }, }, comments: true, }, });
🌐
Medium
medium.com › @mustafakemalgordesli › prisma-select-include-nasıl-kullanılır-586a83c0ca0e
Prisma Select & Include Nasıl Kullanılır | by Mustafa Kemal GORDESLI | Medium
November 2, 2023 - const user = await prisma.user... false, deleted: false, authorId: 1 } ] } */ include ifadesi, ilişkili tablolar arasında veri çekmek için kullanılır....
🌐
Jottup
jottup.com › home › nodejs › optimize queries with prisma: using include & select effectively
Optimize Queries with Prisma: Include & Select Tips | Jottup
March 28, 2025 - Always specify the fields you need using 'select' to avoid over-fetching. Use 'include' to fetch related data only when necessary. Leverage Prisma's filtering capabilities to reduce the data set size early.
🌐
Prisma
prisma.io › home › excluding fields › excluding fields › excluding fields › excluding fields
Excluding fields | Prisma Documentation
Prisma Client API reference · Edit on GitHub · Select fields · Learn how to return only the fields and relations you need with select and include in Prisma Client. Relation queries · Prisma Client provides convenient queries for working with relations, such as a fluent API, nested writes (transactions), nested reads and relation filters ·
🌐
Prisma Client Rust
oicnp.com › rust-prisma › reading-data › select-include
Select & Include | Prisma Client Rust - OICNP
This is why the select and include functions aren’t just structs, they can be passed arguments defined within the macros using the following syntax: post::include!((filters: Vec<comment::WhereParam>, skip: i64, take: i64) => post_with_comments { comments(filters).skip(skip).take(take) }) async fn do_query() -> Vec<post_only_title::Data> { let filters = vec![comment::content::contains("prisma".to_string())]; let skip = 5; let take = 5; client .post() .find_many(vec![]) .select(post_only_title::select(filters, skip, take)) .exec() .await .unwrap() } // Generated type is equivalent to pub mod post_with_comments { pub struct Data { id: String, title: String, comments: Vec<comment::Data> } pub fn select(filters: Vec<comment::WhereParam>, skip: i64, take: i64) // return type is an internal detail }
🌐
GitHub
github.com › prisma › prisma › issues › 21982
Extended Prisma Clients and nested include/select statements allow both `include` and `select` without causing a type error · Issue #21982 · prisma/prisma
November 16, 2023 - Query a model on either a standard or extended Prisma Client with a select or include statement containing both a select and include statement.
Author   prisma
🌐
Prisma Client Python
prisma-client-py.readthedocs.io › en › v0.9.0 › reference › selecting-fields
Selecting Fields - Prisma Client Python
As you can see you can still query against fields that aren't defined on the model itself but Prisma Client Python will only select the fields that are present. See the Model Actions documentation for more details on writing queries. ... This feature is experimental and subject to change. See this issue for discussion. If in some cases you're writing a lot of queries that need to fetch the same relations over and over again it can be cumbersome and error-prone to have to explicitly specify them in include.
🌐
Prisma Client Python
prisma-client-py.readthedocs.io › en › stable › reference › selecting-fields
Selecting Fields - Prisma Client Python - Read the Docs
As you can see you can still query against fields that aren't defined on the model itself but Prisma Client Python will only select the fields that are present. See the Model Actions documentation for more details on writing queries. ... This feature is experimental and subject to change. See this issue for discussion. If in some cases you're writing a lot of queries that need to fetch the same relations over and over again it can be cumbersome and error-prone to have to explicitly specify them in include.