Raw Driver, Query Builder or ORM: Comparing Three Approaches

There are three common ways for code to work with a database. They sit at different heights above the database, like steps on a ladder. This comparison explains each in plain terms and suggests which suits which kind of beginner project.

The three approaches

1. Raw driver. You write SQL yourself and send it through the driver, the library that talks to the database.

rows = conn.execute("SELECT name FROM pets WHERE species = ?", ("cat",)).fetchall()

2. Query builder. A library builds SQL from method calls. You still think in tables and columns, but the library assembles the text.

// Knex.js style
const rows = await knex("pets").select("name").where({ species: "cat" });

3. ORM (object-relational mapper). Tables become classes and rows become objects. You mostly think in objects.

# Django style
cats = Pet.objects.filter(species="cat").values_list("name", flat=True)

All three use a driver underneath.

Side by side

QuestionRaw driverQuery builderORM
How much SQL do you write?All of itLittle, but you think in SQLVery little
Learning curveLearn SQLLearn SQL plus the builderLearn the ORM, ideally SQL too
Safety against injectionYes, if you use placeholdersYes by defaultYes by default
Seeing what runsObviousCan print the SQLNeeds logging switched on
Handling relationshipsYou write JOINsYou write JOINs with helpersOften automatic
Moving between databasesSQL may need tweaksOften easierOften easier
Best forLearning SQL, small scriptsApps that want control without string buildingLarger apps with many tables and forms

A verdict by use case

Your projectSensible starting point
Learning SQL itselfRaw driver
A small script or data toolRaw driver
A web app with a framework that includes an ORMThe framework's ORM, with query logging on
A Node.js or Python service where you like writing SQL but want helpQuery builder
Complex reportsRaw SQL, even inside an ORM-based app

Common beginner mistakes with each

Mixing approaches is normal

Many real apps use an ORM for everyday pages and drop to raw SQL for a tricky report. That is not cheating. Choose the simplest tool that expresses the query clearly.

Related pages

Counting the cost of learning an ORM before SQL looks at learning order, and Database Drivers in 11 Slides explains the layer underneath all three.

A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.

Related pages on this site