Connecting to a Database
The ways backend code talks to a database (raw drivers, query builders, and ORMs) and how a connection is made.
What is it?
Your app and your database are separate programs. They talk over a network connection (even on the same machine), using a connection string with everything needed to reach the database: host, port, username, password, and database name. For example: postgres://user:pass@localhost:5432/mydb.
On top of that connection, you choose how directly you write SQL:
- A driver (like
pgin Node orpsycopg2in Python) sends SQL strings and returns rows. Full control. - A query builder (like Knex, or SQLAlchemy Core) builds queries with function calls that still map closely to SQL.
- An ORM (like Prisma, Sequelize, or SQLAlchemy's ORM layer) lets you work with rows as objects and generates the SQL for you.
Explain like I'm 10
A raw driver is like talking to a bank teller in exact banking terms. A query builder is like filling in a structured form that asks for the same details. An ORM is like the bank's app: you tap 'send money' and it handles the paperwork. Convenient, but you control less of what happens.
Examples
A connection string and a raw query
const { Pool } = require("pg");
// postgres://user:password@localhost:5432/mydb
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const result = await pool.query(
"SELECT * FROM users WHERE id = $1",
[userId]
);
console.log(result.rows);The connection string tells the driver where and how to connect. The query is plain SQL, with $1 as a safe placeholder for the value.
The same query at three levels of abstraction
// Raw driver
await pool.query("SELECT * FROM users WHERE active = $1", [true]);
// Query builder (Knex)
await knex("users").where({ active: true });
// ORM (Prisma)
await prisma.user.findMany({ where: { active: true } });All three run equivalent SQL. They differ only in how much SQL you write by hand and how much the library generates.
Full CRUD through a raw driver, inside route handlers
// Create
app.post("/users", async (req, res) => {
const result = await pool.query(
"INSERT INTO users (name, email) VALUES ($1, $2) RETURNING *",
[req.body.name, req.body.email]
);
res.status(201).json(result.rows[0]);
});
// Read
app.get("/users/:id", async (req, res) => {
const result = await pool.query("SELECT * FROM users WHERE id = $1", [req.params.id]);
if (result.rows.length === 0) return res.status(404).json({ error: "not found" });
res.json(result.rows[0]);
});
// Update
app.put("/users/:id", async (req, res) => {
const result = await pool.query(
"UPDATE users SET name = $1, email = $2 WHERE id = $3 RETURNING *",
[req.body.name, req.body.email, req.params.id]
);
res.json(result.rows[0]);
});
// Delete
app.delete("/users/:id", async (req, res) => {
await pool.query("DELETE FROM users WHERE id = $1", [req.params.id]);
res.status(204).end();
});The four basic CRUD operations, each wired to the matching HTTP method and route. This is what 'connecting to a database' looks like end to end in a real API, not just one SELECT.
Wrapping multiple queries in a transaction
app.post("/transfer", async (req, res) => {
const client = await pool.connect();
try {
await client.query("BEGIN");
await client.query(
"UPDATE accounts SET balance = balance - $1 WHERE id = $2",
[req.body.amount, req.body.fromId]
);
await client.query(
"UPDATE accounts SET balance = balance + $1 WHERE id = $2",
[req.body.amount, req.body.toId]
);
await client.query("COMMIT");
res.status(204).end();
} catch (err) {
await client.query("ROLLBACK");
throw err;
} finally {
client.release();
}
});A money transfer needs both updates to happen together or not at all. This checks out one dedicated connection from the pool, runs both queries as one transaction, and rolls back entirely if either fails. Money can't leave one account without arriving in the other.
How it works
The app reads connection details (usually from an environment variable, never hardcoded) and passes them to a driver. The driver opens a TCP connection to the database and authenticates. Real apps don't open a new connection per query. They keep a small pool of open connections to reuse (see connection pooling).
A query builder or ORM sits on top of that same driver. In the end, everything becomes SQL text sent over the connection. The abstraction only decides how much SQL you write and how much it generates.
Why does it exist?
A database speaks its own wire protocol, not JavaScript or Python. Without a driver to translate between your language's data types and that protocol, your code couldn't talk to it at all.
Query builders and ORMs add productivity on top: they generate repetitive SQL, map rows to familiar objects, and provide tools like migrations that a raw driver doesn't include.
When to use it
- Raw driver: when you need full control, or run a few simple, performance-sensitive queries.
- Query builder: when you want dynamic, composable queries that are safer than hand-built SQL strings.
- ORM: for typical CRUD-heavy apps, where models, relations, and built-in migrations are worth giving up some fine-grained SQL control.
When not to use it
Don't force complex analytical or reporting queries through an ORM's query API. It often produces slower, harder-to-read SQL than writing it yourself, and most ORMs let you drop down to raw SQL for exactly this. For a tiny script with one or two queries, a full ORM is usually more setup than the task needs.
Common mistakes
Hardcoding database credentials in source code instead of reading them from environment variables.
Building SQL by concatenating strings with user input, which opens the door to SQL injection, instead of using parameterized placeholders.
Opening a new database connection for every request instead of reusing a pool. It's slow and can exhaust the database's connection limit under load.
Forgetting to call client.release() after a transaction in every code path, including failures. This leaks a connection from the pool until it runs dry.
Practice exercises
- Easy:
Break the connection string postgres://app:secret@db.internal:5432/orders into its host, port, user, password, and database name.
- Medium:
Rewrite this unsafe query to use a parameterized placeholder instead of string concatenation: db.query("SELECT * FROM users WHERE email = '" + email + "'").
- Hard:
Explain what would go wrong, and why, if every HTTP request opened and closed its own database connection instead of borrowing one from a pool.
Interview questions
What's the difference between a database driver, a query builder, and an ORM?
A driver sends raw SQL and returns rows, with no abstraction. A query builder builds SQL through function calls that still map closely to it. An ORM maps rows to objects and generates the SQL for you, trading some control for productivity.
What does a database connection string typically contain?
The protocol, host, port, username, password, and database name needed to connect.
Why should database queries use parameterized placeholders instead of string concatenation?
To prevent SQL injection. The driver substitutes values safely instead of treating attacker-controlled input as part of the SQL.
What is connection pooling, and why is it used instead of opening a new connection per request?
A pool keeps a set of open database connections ready to reuse. Opening a TCP connection and authenticating for every request is slow and, under load, can exhaust the database's connection limit. Borrowing a connection and returning it avoids both costs.
What determines an appropriate pool size for an application?
A balance between the app's expected concurrency and the database's connection limit, which is shared with every other service using it. Too small, and requests queue for a free connection under load. Too large, and you risk exhausting the database's capacity, especially with several app instances each running their own pool.
Why does `pool.query()` work fine for single, independent queries but not for a transaction spanning multiple queries?
pool.query() borrows any free connection for one call and returns it right after. BEGIN/COMMIT are connection-scoped, so every statement in a transaction must run on the same connection. You check out one client with pool.connect() and reuse it for the whole transaction.
What are the four ACID properties a transaction is meant to provide?
Atomicity: all operations succeed together or none do. Consistency: the database moves from one valid state to another, respecting its constraints. Isolation: concurrent transactions don't see each other's uncommitted changes. Durability: once committed, a change survives even a crash right after.
What does ROLLBACK actually undo, and what does it leave unaffected?
It undoes every change since the matching BEGIN in that transaction. It doesn't affect transactions committed before, or anything outside the database, like an email already sent by the same request.
Why is forgetting `client.release()` in every code path, including a thrown error, a serious bug rather than a minor cleanup oversight?
A client checked out with pool.connect() and never released stays unavailable forever. Repeated leaks shrink the pool until no connections remain, and every request that needs one hangs or times out. It usually shows up much later and far from the code that caused it.
Why is `client.release()` typically placed in a `finally` block rather than just at the end of the `try`?
finally runs whether the try succeeds or throws, so the connection always goes back to the pool. At the end of try, it would be skipped whenever an error occurs.
What's a deadlock in the context of database transactions, and how can it happen with two concurrent transfers?
Two transactions each hold a lock the other needs and both wait. E.g. transaction A locks account 1 then tries account 2, while B locks account 2 then tries account 1. Neither can proceed, so the database usually detects this and aborts one so the other can continue.
How would you reduce the risk of that kind of deadlock between two concurrent transfers?
Acquire locks (e.g. update rows) in the same agreed order in every transaction, such as always locking the lower account id first, whichever is sender or receiver. Then two transactions can never wait on each other in a circle.
What is the N+1 query problem, and how does it commonly happen when using an ORM?
You fetch a list of N records, then run a separate query per record for related data, like each order's customer. That's 1 + N queries instead of a couple. It often happens by accident with ORM lazy loading, where touching a relation inside a loop quietly runs a new query each time.
How do ORMs typically let you avoid the N+1 problem?
Eager loading. You tell the ORM up front to fetch the related data in the same query, or one extra batched query, with something like .include(), instead of a lazy query per access.
What's the difference between an ORM's lazy loading and eager loading for a related record?
Lazy loading fetches a related record only when code accesses it. It defers the query but risks N+1 in a loop. Eager loading fetches related data up front with the original query, trading one possibly larger query for many small ones later.
What's a database migration, and why do ORMs typically include tooling for them?
A versioned, incremental schema change, like adding a column, applied in order so every environment's schema matches what the code expects. ORMs include tooling because schema changes must happen safely alongside code changes, and tracking raw ALTER TABLE scripts by hand across environments is error-prone.
Why is a database index useful, and what's the tradeoff of adding one?
An index lets the database find matching rows without scanning the whole table, which speeds up reads on large tables a lot. The tradeoff: every index must be updated on each INSERT/UPDATE/DELETE of the indexed column, so more indexes mean slower writes and more storage.
What's a prepared statement, and how does it relate to preventing SQL injection?
The SQL structure and the parameter values are sent separately. The database compiles the template once and substitutes values strictly as data, never as SQL syntax. That's why placeholders like $1 are immune to injection and string concatenation isn't.
Why can't a column name or table name be parameterized the same way as a value, like `$1`?
Placeholders like $1 are only allowed where the SQL grammar expects a value, not an identifier like a column or table name. A dynamic identifier, such as a user-chosen sort column, must be checked against an allow-list of known-safe names instead.
Give an example of an app that uses parameterized queries but is still vulnerable to SQL injection.
One that concatenates a user-supplied string into an ORDER BY clause or dynamic sort column, since placeholders can't parameterize identifiers. The WHERE clause uses $1 safely, but that one concatenated fragment still lets an attacker inject arbitrary SQL.
What's the difference between a foreign key constraint and just remembering an id in application code without one?
The database enforces a foreign key. It refuses to insert a row pointing to a missing parent, and refuses to delete a parent that's still referenced unless a cascade is set. Relying only on app code leaves consistency open to bugs, direct database edits, or another service bypassing the app.
What does `ON DELETE CASCADE` do on a foreign key, and what's a risk of using it without thinking it through?
It deletes dependent rows automatically when the parent is deleted, e.g. deleting a user also deletes their orders. The risk: one delete can silently cascade through much more data than intended, especially several relationships deep, with no confirmation of what it removes.
What's the difference between optimistic and pessimistic locking when two requests might update the same row concurrently?
Pessimistic locking takes a real database lock on the row before reading it, like SELECT ... FOR UPDATE, blocking other transactions until it finishes. Optimistic locking reads a version number or timestamp, and the update only succeeds if it hasn't changed since; otherwise it fails and the caller retries. It trades upfront blocking for detecting conflicts afterward.
Why might an ORM's default behavior of committing each save or query as its own separate transaction be insufficient for a multi-step operation?
If both steps must succeed or fail together, like moving money between two records, committing each step separately means a failure partway through leaves the operation half-done. You have to tell the ORM explicitly to wrap the whole sequence in one transaction.
What's a connection timeout, and why does a pool need one?
A limit on how long to wait for a free connection, or for the database to respond, before raising an error instead of hanging. Without one, a request waiting on a connection could tie up server resources forever if none is ever freed.
Why isn't retry logic for a failed database query something you'd blindly apply to every query?
Retrying is only safe for read-only or idempotent operations. A write may have succeeded on the database but failed to acknowledge because of a network blip. Retrying it can apply it twice, like a duplicate INSERT.
Why would a health-check endpoint run a trivial query, like SELECT 1, against the database rather than just returning 200 OK unconditionally?
It checks that the app can actually reach and use the database right now, not just that the web process is alive. A server that lost its database connection or exhausted its pool would otherwise report healthy while every real request fails.
Why should you close or drain a connection pool gracefully during app shutdown, rather than letting the process exit abruptly?
An abrupt exit can cut off in-flight queries or transactions, and the database may treat those connections as open until it notices they're gone. Ending the pool explicitly lets in-flight work finish (or stop cleanly) and closes connections properly, freeing them on the database right away.
What's the tradeoff between choosing a UUID versus an auto-incrementing integer as a primary key, from a database-connection perspective?
An auto-incrementing integer is smaller and slightly faster to index and join, but reveals roughly how many rows exist and can collide if generated in two places. A UUID is larger and a bit slower to index, but the app can generate it safely before inserting, with no round trip to get an id.
How does a query builder like Knex offer more safety against SQL injection than hand-built string concatenation, while still allowing dynamic queries?
It builds the parameterized query from function calls like .where({ active: true }), using placeholders for every value you pass. You can build conditions in code without ever concatenating a value into the SQL string.
What's a downside of letting an ORM generate the SQL for a complex reporting or analytical query, compared to writing that SQL directly?
ORM query APIs are designed for common CRUD patterns. For something like a multi-table aggregation with custom grouping, they may generate needlessly complex, slow, or hard-to-read SQL. Most ORMs let you drop to raw SQL for these cases.
What does `RETURNING *` save you from having to do after an INSERT?
A second SELECT. Without it, getting the new row's full data, including any auto-generated id, needs a separate query. RETURNING * returns the row in the same round trip.
Why can't every incoming HTTP request simply open and close its own fresh database connection instead of using a pool?
Opening a TCP connection and authenticating has real overhead, and doing it per request repeats that cost every time. Databases also cap total simultaneous connections, and a busy app opening one per concurrent request can easily hit that cap, so new connections, and requests, start failing.
What's a read replica, and what kind of query would you route to one instead of the primary database?
A copy of the database kept continuously updated from the primary and used to serve read-only queries, taking read load off the primary. Route SELECT-only queries that can tolerate slightly stale data to it. All writes still go to the primary.