Introduction
Sending queries to the database with prisma is extremely convenient. There is no need for creating SQL-Queries, prisma will handle most of the work for me. In this article I will show some example queries.
Dedicated Query Files
While its totally possible to create a query directly within a component, there is a better way. When I create a dedicated file only for a query, I can easily reuse the same query in different places. Another benefit is; all queries are gonna be in one place wich makes it easier for me to maintain them. A good place to store them could be:
src/features/ticket/queriesNow within that folder I can create all queries related to my ticket items like
get-ticket.ts
get-tickets.tsGet Single Item
Here is an example of a query file for fetching one single element
import prisma from "@/lib/prisma";
export const getProject = async (id: string) => {
return await prisma.project.findUnique({
where: {
id,
},
});
};
And accessed in a component like
type ProjectDetailProps = {
params: {
projectId: string;
};
};
const ProjectDetailPage = async ({ params }: ProjectDetailProps) => {
const { projectId } = await params;
const project = await getProject(projectId);
// Needed to make sure project cant be empty
if (!project) {
notFound();
}
return (...)Note: The import of notFound() needs to be exactly:
import { notFound } from "next/navigation";Get List of Items
And here is an example how I can fetch a list and also directly sort it
import prisma from "@/lib/prisma";
export const getTickets = async () => {
return await prisma.ticket.findMany({
orderBy: {
createdAt: "desc",
},
});
};And the access it anywhere in my application with
import { getTickets } from "../queries/get-tickets";
const tickets = await getTickets();Sensitive Data
Itβs common that I will need to fetch user data alongside my tickets. When doing so I need to make sure I only send non sensitive data to the client side.

One way of doing so, is to only include for example the username in the query:
import prisma from "@/lib/prisma";
export const getTicket = async (id: string) => {
return await prisma.ticket.findUnique({
where: {
id,
},
include: {
user: {
select: {
username: true,
},
},
},
});
};Further Queries
There are way more queries than just my 2 examples, I will link below some sources that might be worth a look.
Conclusion
With Prisma I finally have a way to avoid SQL-Queries. Not that I hate them, but I definitely prefer building my application over debugging SQL-Queries. Working with Prisma is just a lot of fun and makes the life as a developer easier in so many ways.