18
you are viewing a single comment's thread
view the rest of the comments
[-] inzen@lemmy.world 0 points 2 months ago

I don't understand the usecase for this. Why would I want to create sql queries dynamically? Seems like a testing and index optimaziation nightmare. Maybe I'm just lacking.

[-] Kache@lemmy.zip 1 points 2 months ago* (last edited 2 months ago)

What do you mean? SQL query builders exist in pretty much every lang

[-] inzen@lemmy.world 1 points 2 months ago

I have never used one and I don't quite understand the benefits. I have used some orm's but I prefer to raw dog SQL.

[-] vitonsky@programming.dev 2 points 2 months ago* (last edited 2 months ago)

When you use query builder, you write a raw SQL code.

The benifit is you can insert user input right in string, and your query remain secure against injections. Additionally, a Nano Queries let you compose queries, and extend it, so you may build complex queries simply.

Let's say you develop a site to search something by its features, for example a movies. Your SQL query may easy takes 100-500 lines. Some part of this query will be a basic, some will be optional depends on provided filters.

With a query builder you may conditionally extend your query like that

if (userInput.rating > 0) {
  filter.and(sql`rating >= ${userInput.rating}`);
}

That's all Query Builder does. It let you avoid to write code like that

const values = [];
const getPlaceholder = (value) => {
  values.push(value);
  return `$${values.length}`;
};

const where = [];
if (year) {
  where.push(`release_year = ${getPlaceholder(year)}`);
}
if (rating) {
  where.push(`rating >= ${getPlaceholder(rating)}`);
}

db.query(
  `SELECT title FROM movies ${where.length ? 'WHERE ' + where.join(' AND ') : ''} LIMIT 100`,
  values,
);
load more comments (1 replies)
load more comments (1 replies)
load more comments (1 replies)
this post was submitted on 26 Jan 2026
18 points (90.9% liked)

Programming

26634 readers
41 users here now

Welcome to the main community in programming.dev! Feel free to post anything relating to programming here!

Cross posting is strongly encouraged in the instance. If you feel your post or another person's post makes sense in another community cross post into it.

Hope you enjoy the instance!

Rules

Rules

  • Follow the programming.dev instance rules
  • Keep content related to programming in some way
  • If you're posting long videos try to add in some form of tldr for those who don't want to watch videos

Wormhole

Follow the wormhole through a path of communities !webdev@programming.dev



founded 2 years ago
MODERATORS