Exercises
Objectives
By the end of this lesson, you should be able to:
- Build a complete CRUD layer with Prisma Client, from reading to bulk operations
- Combine filtering, sorting, and pagination in a single, realistic query
- Rebuild a raw SQL exercise from Module 2 using Prisma Client instead
⚠️ A note on verification: as throughout this module, the Prisma CLI can’t run inside this course’s own sandboxed tooling, so the expected output below reflects Prisma Client’s stable, documented behavior rather than this course’s own live execution. Run every step yourself, on your own machine, against a real database.
Exercise: Rebuilding the Store Inventory
This exercise rebuilds Module 2’s store inventory exercise (raw SQL) with Prisma Client instead.
a) Model it. Add a Product model (id, name, stock) to your schema, and migrate it.
b) Seed it. Using create, insert Keyboard (stock: 5) and Mouse (stock: 10).
c) Read with a filter. Use findUnique or findFirst to look up Keyboard by name (add @unique to name if using findUnique).
d) Reduce stock, safely. Write a function that reduces a product’s stock by a given amount, but throws an error first if the current stock is too low, following the same logic Module 2’s transaction used:
async function placeOrder(productName, quantity) {
const product = await prisma.product.findFirst({ where: { name: productName } });
if (product.stock < quantity) {
throw new Error('Not enough stock');
}
return prisma.product.update({
where: { id: product.id },
data: { stock: product.stock - quantity }
});
}
Call it once successfully (reduce Keyboard by 2), and once with a quantity that should fail (reduce by 100), confirming the error is thrown and stock is unchanged after the failed call.
e) List and sort. Fetch every product sorted by stock ascending.
f) Paginate. Add five more products, then fetch them two at a time using take and skip, confirming each page returns different products.
g) Bulk update. Use updateMany to set every product with stock under 3 to stock: 0 (out of stock), and confirm the returned count matches how many products that affected.
h) Compare to Module 2. Write one paragraph comparing this exercise to Module 2’s raw SQL version, what’s shorter, what’s the same, and whether the underlying logic (check stock, then update) genuinely changed at all.
Recap
This module replaced Modules 1 and 2’s raw SQL with Prisma Client’s query API: reading with findMany/findUnique/findFirst, writing with create/update/delete and their bulk equivalents, and sorting and pagination with orderBy/take/skip, all generating the same parameterized, injection-safe SQL underneath.
This is the final PostgreSQL module in this course. Next module: MongoDB, a genuinely different way of modeling and querying data.