Full answer
Options
- ORM: Sequelize (model classes, associations, hooks, migrations), TypeORM, MikroORM, Prisma (schema file, generated typed client, its own migration tool). Good for CRUD, relations, validation and consistent access.
- Query builder: Knex, Kysely (very strong TypeScript types), Drizzle (a thin typed layer close to SQL). You write queries as code, the library builds the SQL.
- Raw SQL with pg or postgres.js: full power (window functions, CTEs, bulk operations), no abstraction, manual mapping and typing.
Trade-offs to discuss
- Productivity: ORMs win for the first 80 percent of queries. Migrations, validation and relations come built in.
- Control and performance: reports, analytics and bulk updates are easier in SQL. ORMs may select too many columns or run many small queries.
- Hidden cost: lazy loading in loops causes N+1. Always inspect the SQL that the ORM produces (logging) and use eager loading (include in Sequelize, include or select in Prisma).
- Type safety: Prisma and Kysely give strong types, Sequelize needs manual typing.
- Portability: ORMs hide small dialect differences, but you rarely switch databases, and you lose database specific features unless you use raw queries.
- Team skills and testing: SQL skills stay valuable, and ORMs are easiest when the team still understands SQL.
- Prisma notes (not run in this item): the schema.prisma file defines models, prisma generate creates the client, and prisma migrate manages migrations. Recent versions use a driver adapter and a TypeScript query engine.
A sensible default: an ORM or typed query builder for everyday queries, raw SQL for the few complex ones, parameters always, SQL logging in development, and an index review.
const { Sequelize, DataTypes, Op, QueryTypes } = require('sequelize');
(async () => {
const sqlLog = [];
const sequelize = new Sequelize({
dialect: 'postgres', host: process.env.PGHOST, port: Number(process.env.PGPORT), username: process.env.PGUSER, database: process.env.PGDATABASE,
logging: (sql) => sqlLog.push(sql.replace(/^Executing \(default\): /, '')),
});
const Student = sequelize.define('OrmStudent', {
name: { type: DataTypes.STRING, allowNull: false },
marks: { type: DataTypes.INTEGER, validate: { min: 0, max: 100 } },
}, { tableName: 'orm_students', timestamps: false });
await Student.sync({ force: true });
await Student.bulkCreate([{ name: 'Asha', marks: 78 }, { name: 'Ravi', marks: 64 }, { name: 'Meera', marks: 91 }]);
sqlLog.length = 0;
// 1. The ORM way
const top = await Student.findAll({ where: { marks: { [Op.gte]: 75 } }, order: [['marks', 'DESC']], attributes: ['name', 'marks'] });
console.log('ORM result :', top.map((s) => `${s.name}:${s.marks}`).join(', '));
console.log('ORM SQL :', sqlLog.at(-1));
// 2. Validation happens in the ORM before SQL is sent
try { await Student.create({ name: 'Zoya', marks: 150 }); } catch (err) { console.log('validation :', err.name, '-', err.errors[0].message); }
// 3. Raw SQL for something the model API does not express well, still parameterised
const [stats] = await sequelize.query('SELECT count(*)::int AS n, round(avg(marks), 1)::float AS average FROM orm_students WHERE marks >= :min', { replacements: { min: 60 }, type: QueryTypes.SELECT });
console.log('raw SQL :', JSON.stringify(stats));
await sequelize.query('DROP TABLE orm_students');
await sequelize.close();
})();Sequelize runs against a local PostgreSQL server. The script prints the SQL that the ORM generated, the validation error, and a raw query. Prisma is described in the text only and was not run here. Install first with npm install sequelize pg (run here with sequelize 6.37.8, pg 8.23.1). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): ORM result : Meera:91, Asha:78 ORM SQL : SELECT "name", "marks" FROM "orm_students" AS "OrmStudent" WHERE "OrmStudent"."marks" >= 75 ORDER BY "OrmStudent"."marks" DESC; validation : SequelizeValidationError - Validation max on marks failed raw SQL : {"n":3,"average":77.7}
Key points
- ORMs speed up CRUD and migrations but can hide inefficient queries.
- Query builders stay close to SQL with composition and types.
- Raw SQL gives full control for complex or bulk queries.
- Always log and review the generated SQL.
- Mixing approaches is normal.
Common mistakes
- Never looking at the SQL the ORM generates.
- Using lazy loading inside loops.
- Building raw SQL with string concatenation.
- Avoiding SQL entirely and writing slow ORM code for reports.
- Choosing a tool only because it is popular.
Follow-ups
- How do you see the SQL that Prisma or Sequelize runs?
- When would you pick Kysely or Drizzle?
- How do migrations differ between the tools?
Tips
- Name the three options and one strength of each.
- Say 'N+1' as the main ORM risk.
- Give a balanced recommendation.