Prisma IDB FaviconPrisma IDB
CRUD Operations

findFirst

Get the first matching record

Retrieve the first record matching your conditions.

const user = await client.user.findFirst({
  where: { active: true },
  orderBy: { createdAt: "desc" },
});

if (user) {
  console.log("Found:", user.name);
} else {
  console.log("No match found");
}

Return Type

Returns the first matching record or null if no match:

const user: User | null = await client.user.findFirst({
  where: {
    /* ... */
  },
});

if (user === null) {
  // No record matched
}

For error handling, use findFirstOrThrow.

Filtering

Use the same where syntax as findMany:

const user = await client.user.findFirst({
  where: {
    email: "alice@example.com",
  },
});

const admin = await client.user.findFirst({
  where: {
    role: "admin",
    active: true,
  },
});

Ordering

Control which record is returned when multiple match:

// Most recently created
const user = await client.user.findFirst({
  where: { active: true },
  orderBy: { createdAt: "desc" },
});

// Highest priority
const todo = await client.todo.findFirst({
  where: { done: false },
  orderBy: { priority: "desc" },
});

Selection

Control returned fields:

const user = await client.user.findFirst({
  where: { active: true },
  select: { id: true, name: true },
});

Relations

Include related records:

const user = await client.user.findFirst({
  where: { email: "alice@example.com" },
  include: { profile: true },
});

console.log(user?.profile?.bio);

Use Cases

Last Created Record

const lastCreated = await client.user.findFirst({
  orderBy: { createdAt: "desc" },
});

Find or Create Pattern

let user = await client.user.findFirst({
  where: { email },
});

if (!user) {
  user = await client.user.create({
    data: { email, name },
  });
}

Soft Deletes

const user = await client.user.findFirst({
  where: {
    id: userId,
    deletedAt: null, // Not soft-deleted
  },
});

Error Handling

Use findFirstOrThrow if not finding a record is an error:

try {
  const user = await client.user.findFirstOrThrow({
    where: { email: "admin@example.com" },
  });
} catch (error) {
  console.log("No admin user found");
}

See Also

On this page