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.
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 › crud › crud › crud › crud
CRUD (Reference) | Prisma Documentation
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 }); }
🌐
Brendonovich
prisma.brendonovich.dev › reading-data › select-include
Select & Include – Prisma Client Rust
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 }
🌐
Prisma Client Python
prisma-client-py.readthedocs.io › en › stable › 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.
🌐
GitHub
github.com › prisma › prisma › issues › 24708
Add "select as" support · Issue #24708 · prisma/prisma
July 5, 2024 - // Prisma will generate type like this for result type UserWithFullName = { fullName: string; }; const users = prisma.user.findMany({ select: { name: true, }, }); const usersWithFullName: UserWithFullName[] = users.map((user) => ({ ...user, fullName: user.name, }));
Author   prisma
Find elsewhere
🌐
Prisma
prisma.io › home › relation queries › relation queries › relation queries › relation queries
Relation queries (Concepts) | Prisma Documentation
A key feature of Prisma Client is the ability to query relations between two or more models. Relation queries include: Nested reads (sometimes referred to as eager loading) via select and include
🌐
Prisma Health
prismahealth.org
Prisma Health
As South Carolina’s largest private, non-profit healthcare system, Prisma Health is here to create a better state of health for South Carolinians.
🌐
Run, Code & Learn
blog.delpuppo.net › its-prisma-time-select
It's Prisma Time - Select
January 11, 2022 - As you can notice, using the select ... When we use the select option, Prisma returns an object that respects our selection, so the typescript compiler can detect the right fields of the objects....
🌐
WEX
wexinc.com › homepage › products › employee benefits › benefit accounts › hsa
WEX HSA Health Savings Account | WEX Inc.
April 28, 2026 - WEX Inc. helps benefits admins simplify health savings account management while offering employees new ways to pay for medical expenses, save for retirement and invest.
🌐
Prisma
prisma.io › home › type safety overview › type safety overview › type safety overview
Type safety | Prisma Documentation
Going back to the UserSelect type, if you were to use dot notation on the created object userEmail, you would have access to all of the fields on the User model that can be interacted with using a select statement. model User { id Int @id @default(autoincrement()) email String @unique name String? posts Post[] profile Profile? } import { Prisma } from "../path/to/generated/prisma/client"; const userEmail: Prisma.UserSelect = { email: true, }; // properties available on the typed object userEmail.id; userEmail.email; userEmail.name; userEmail.posts; userEmail.profile;
🌐
Prisma
prisma.io › dataguide › postgresql › reading-and-querying-data › basic-select
Basic Select | PostgreSQL Basic Queries | Prisma's Data Guide
The `SELECT` command is the main way to query the data within tables and views in PostgreSQL. This guide demonstrates the basic syntax and operation of this highly flexible command.
🌐
NestJS
docs.nestjs.com › recipes › prisma
Prisma | NestJS - A progressive Node.js framework
Prisma is an open-source ORM for Node.js and TypeScript. It is used as an alternative to writing plain SQL, or using another database access tool such as SQL query builders (like knex.js) or ORMs (like TypeORM and Sequelize).
🌐
Prisma Health
prismahealth.org › locations › hospitals › blount-memorial-hospital
Prisma Health Blount Memorial Hospital
Prisma Health is a private, nonprofit health company serving more than 1.6 million patients in South Carolina and Tennessee.
Call   +18659837211
Address   907 East Lamar Alexander Parkway, 37804, Maryville
🌐
Aetna
aetna.com › individuals-families › using-your-aetna-benefits › secure-member-account.html
Member Website: Secure Account Registration & Login | Aetna
Applies to: Aetna Choice® POS, Aetna Choice POS II, Aetna Medicare℠ Plan (PPO), Aetna Medicare Plan (HMO), all Aetna HealthFund® products, Aetna Health Network Only℠, Aetna Health Network Option℠, Aetna Open Access® Elect Choice®, Aetna Open Access HMO, Aetna Open Access Managed Choice®, Open Access Aetna Select℠, Elect Choice, HMO, Managed Choice POS, Open Choice®, Quality Point-of-Service® (QPOS®), and Aetna Select℠ benefits plans and all products that may include the Aexcel®, Choose and Save℠, Aetna Performance Network or Savings Plus networks.
🌐
Prisma
prisma.io › dataguide › mysql › reading-and-querying-data › basic-select
Basic Select | MySQL Basic Queries | Prisma's Data Guide
The `SELECT` command is the main way to query the data within tables and views in MySQL. This guide demonstrates the basic syntax and operation of this highly flexible command.
🌐
The BMJ
bmj.com › content › 372 › bmj.n71
The PRISMA 2020 statement: an updated guideline for reporting systematic reviews | The BMJ
March 29, 2021 - The PRISMA 2020 statement provides updated reporting guidance for systematic reviews that reflects advances in methods to identify, select, appraise, and synthesise studies
🌐
Prisma Client Python
prisma-client-py.readthedocs.io › en › stable › reference › operations
Query Operations - Prisma Client Python
In lieu of more extensive documentation, this page documents query operations on the prisma client such as creating, finding, updating and deleting records.
🌐
GitHub
github.com › prisma › prisma › issues › 19347
Nested Select not working · Issue #19347 · prisma/prisma
May 19, 2023 - Bug description This should work: But it throws an error like this: How to reproduce Try to run a nested select query. Expected behavior It should run, according to the docs. Prisma information inventory_order_details Json? @default("{}"...
Author   prisma