SQL from JavaScript
Node.js programs talk to PostgreSQL through a client library, and the most widely used one is pg, also called node-postgres. It sends your SQL and its values to the server and hands the rows back as plain JavaScript objects, using promises, so it fits naturally with async and await. In this lesson, we will create a connection pool, run a query with $1 parameters, look closely at the JavaScript types that come back (some of them surprise everyone once), insert a row and get its id with RETURNING, run a transaction on a single connection, and close everything cleanly. Every program here was run against the Fee Tracker with node-postgres 8 on Node.js, and the output shown is what it printed.
In One Minute
new pg.Pool({...})creates a pool;pool.query(sql, values)borrows a connection, runs the SQL and gives it back.- Write
$1,$2in the SQL and pass the values in an array, never inside a template literal. - Rows come back as objects:
{ title: 'Java OOP', fee_usd: '500.00' }. NUMERICandbigint(includingcount(*)) arrive as strings, andDATEarrives as aDateat local midnight.- For a transaction, take one client with
pool.connect(), runBEGIN...COMMIT/ROLLBACK, thenclient.release(). - Call
pool.end()when the program finishes.
Setting Up a Pool
Install the client with npm install pg, then create one pool for the whole application in its own module. Every other file imports that same pool:
// db.mjs: one pool for the whole app, shared by every module that imports it.
import pg from 'pg';
export const pool = new pg.Pool({
host: 'localhost',
port: 5432,
database: 'feetracker',
user: 'fee_app',
password: process.env.FEE_DB_PASSWORD,
max: 5, // at most 5 connections
});The password comes from an environment variable, never from the code (Database Hosting). Many apps pass a single connection string instead, such as new pg.Pool({ connectionString: process.env.DATABASE_URL }). Create the pool once. A new pool for every request opens new connections every time, which is slow and can exhaust the server's max_connections (Troubleshooting a Database).
Your First Query
pool.query() takes the SQL text and an array of values, and returns a promise for the result. With await (see Async and Await in the JavaScript course), it reads like ordinary code:
import { pool } from './db.mjs';
const minFee = 300;
const { rows, rowCount } = await pool.query(
'SELECT title, fee_usd FROM courses WHERE fee_usd >= $1 ' +
'ORDER BY fee_usd DESC, title',
[minFee],
);
console.log(`${rowCount} courses`);
for (const row of rows) {
console.log(`${row.title}: $${row.fee_usd}`);
}
console.log(rows[0]);
await pool.end();5 courses
Java Collections: $550.00
Java OOP: $500.00
Java Basics: $450.00
JavaScript Basics: $450.00
SQL Basics: $400.00
{ title: 'Java Collections', fee_usd: '550.00' }Explanation: $1 is a placeholder for the first value in the array; the SQL and the value travel to the server separately, so the value can never change the SQL (SQL Injection). The result object has rows, an array with one object per row, keyed by column name, and rowCount, the number of rows. The ORDER BY ends with title so the two $450 courses always come back in the same order. Look at the last line: fee_usd is '550.00', in quotes. It is a string, not a number.
The SQL by itself is an ordinary query. Here it is with the value written in, so you can run it in Try it and compare the rows with the program's output:
SELECT title, fee_usd
FROM courses
WHERE fee_usd >= 300
ORDER BY fee_usd DESC, title; title | fee_usd
-------------------+---------
Java Collections | 550.00
Java OOP | 500.00
Java Basics | 450.00
JavaScript Basics | 450.00
SQL Basics | 400.00
(5 rows)The Types You Get Back
node-postgres turns each column into a JavaScript value, and a few of the choices matter a lot. Here is payment 5, with a window count(*) added to show how counts arrive:
import { pool } from './db.mjs';
const { rows } = await pool.query(
`SELECT payment_id, amount_usd, paid_on, method,
count(*) OVER () AS total_payments
FROM payments WHERE payment_id = 5`,
);
const p = rows[0];
for (const [column, value] of Object.entries(p)) {
const type = value === null ? 'null' : value.constructor.name;
console.log(`${column.padEnd(14)} ${type.padEnd(7)} ${String(value)}`);
}
// Strings don't add up the way numbers do:
console.log(p.amount_usd + p.amount_usd);
await pool.end();payment_id Number 5
amount_usd String 200.00
paid_on Date Mon Jan 05 2026 00:00:00 GMT-0600 (Central Standard Time)
method null null
total_payments String 1
200.00200.00Explanation:
| SQL type | JavaScript value | Why |
|---|---|---|
INTEGER | Number | It always fits in a JavaScript number |
NUMERIC(8,2) | String | A JavaScript Number can't hold every decimal exactly, so pg doesn't guess |
bigint, including count(*) | String | Values above 253 would lose digits as a Number |
DATE | Date at local midnight | 2026-01-05 became midnight in the computer's own time zone (Dallas time here) |
NULL | null |
Because amount_usd is a string, + joined the two values into '200.00200.00' instead of adding them. The DATE problem is quieter: the same row gives a Date at midnight Central time on a computer in Dallas and at midnight UTC on a server in UTC, and toISOString() on the Dallas one prints 2026-01-05T06:00:00.000Z. Code that formats that date in another time zone can show the day before.
Two common fixes: do the arithmetic in SQL, and choose how a type is parsed:
import pg from 'pg';
import { pool } from './db.mjs';
// Keep DATE values as 'YYYY-MM-DD' text instead of a local-midnight Date.
pg.types.setTypeParser(pg.types.builtins.DATE, (text) => text);
const { rows } = await pool.query(
`SELECT paid_on,
sum(amount_usd) AS total_usd,
count(*)::int AS payments,
sum(amount_usd * 100)::bigint AS total_cents
FROM payments
WHERE paid_on = '2025-12-03'
GROUP BY paid_on`,
);
console.log(rows[0]);
// Money as whole cents is safe to add in JavaScript:
console.log(Number(rows[0].total_cents) + 1999);
await pool.end();{
paid_on: '2025-12-03',
total_usd: '250.00',
payments: 1,
total_cents: '25000'
}
26999Explanation: setTypeParser(pg.types.builtins.DATE, ...) keeps every DATE as the text '2025-12-03', which never shifts with time zones. count(*)::int casts the count to integer in SQL, so it arrives as a Number. The total stays a string, which keeps it exact; to do money math in JavaScript, either work in whole cents (as total_cents does here, 25000 plus 1999 cents) or use a decimal library. The type parser setting is global for the whole program, so set it once, where the pool is created.
Inserting with RETURNING
PostgreSQL's RETURNING clause sends back columns of the rows an INSERT, UPDATE or DELETE changed, so one round trip saves the row and returns its new id:
import { pool } from './db.mjs';
const { rows } = await pool.query(
`INSERT INTO payments
(student_id, course_id, amount_usd, due_on, paid_on, method)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING payment_id, amount_usd`,
[102, 4, '200.00', '2026-01-05', '2026-01-05', 'card'],
);
console.log('saved', rows[0]);
await pool.end();saved { payment_id: 8, amount_usd: '200.00' }Explanation: The values array holds the six values in order, matching $1 to $6. Dates are sent as 'YYYY-MM-DD' strings and money as a string, which PostgreSQL converts to DATE and NUMERIC exactly. RETURNING payment_id, amount_usd returns the new row's id, 8, because the Fee Tracker already had seven payments. For an UPDATE or DELETE, rowCount tells you how many rows changed.
Transactions on One Connection
A transaction must run on a single connection, so you can't use pool.query() for it: each call may borrow a different connection. Take one client from the pool, run BEGIN, your statements, then COMMIT or ROLLBACK, and always release the client:
import { pool } from './db.mjs';
const INSERT = `INSERT INTO payments
(student_id, course_id, amount_usd, due_on, paid_on, method)
VALUES ($1, $2, $3, '2026-01-05', '2026-01-05', 'card')`;
async function countPayments(studentId) {
const { rows } = await pool.query(
'SELECT count(*)::int AS n FROM payments WHERE student_id = $1',
[studentId],
);
return rows[0].n;
}
async function payTwoCourses(studentId) {
const client = await pool.connect(); // one connection for the transaction
try {
await client.query('BEGIN');
await client.query(INSERT, [studentId, 1, '450.00']);
await client.query(INSERT, [studentId, 4, '-200.00']); // a bug
await client.query('COMMIT');
} catch (err) {
await client.query('ROLLBACK');
console.log(`Rolled back: ${err.code} ${err.message}`);
} finally {
client.release(); // give the connection back to the pool
}
}
console.log("Advitha's payments before:", await countPayments(102));
await payTwoCourses(102);
console.log("Advitha's payments after:", await countPayments(102));
await pool.end();Advitha's payments before: 0
Rolled back: 23514 new row for relation "payments" violates check constraint "payments_amount_usd_check"
Advitha's payments after: 0Explanation: The first INSERT succeeded inside the transaction; the second broke the CHECK (amount_usd > 0) constraint and threw an error whose err.code is 23514, the standard SQLSTATE code for a check violation. The catch sent ROLLBACK, which undid the first payment too, so Advitha has 0 payments before and after. The finally block calls client.release() whether the transaction worked or not. A client that is never released is lost to the pool, and after max leaks (5 here) every later pool.connect() waits forever.
err.code | Meaning |
|---|---|
23505 | Unique violation (a duplicate key) |
23503 | Foreign key violation |
23514 | Check violation |
23502 | Not-null violation |
40001 / 40P01 | Serialization failure / deadlock: retry the transaction |
Check err.code, not the message text, to decide what to do.
Closing Up
pool.end() closes every connection in the pool. A short script, like the ones in this lesson, should call it at the end, or Node.js keeps running while idle connections stay open (the pool closes idle connections after 10 seconds by default). A long-running web server keeps its pool open for its whole life, and only calls pool.end() when it shuts down.
Common Mistakes
Building SQL with template literals. It invites SQL injection. Use $1 placeholders and a values array.
Doing math on NUMERIC values. They are strings: '200.00' + '200.00' is '200.00200.00'. Do the math in SQL, cast counts with ::int, or use whole cents.
Trusting DATE objects across time zones. Keep dates as text with a type parser, or use TIMESTAMPTZ for real moments in time.
Running a transaction with pool.query(). Each call can use a different connection. Use pool.connect() and one client.
Forgetting client.release(). The pool runs out of connections. Release in finally.
Creating a pool per request. Create one pool when the app starts and share it.
Interview Corner
How do you prevent SQL injection with node-postgres?
Use placeholders ($1, $2) in the SQL and pass the values as an array: pool.query('... WHERE id = $1', [id]). Never build SQL with template literals or +.
Why does node-postgres return NUMERIC and bigint values as strings?
JavaScript numbers are 64-bit floating point: they can't store every decimal exactly or integers above 2^53. Returning strings keeps the exact value; you choose how to convert it.
How do you run a transaction with a pool?
const client = await pool.connect(), then BEGIN, the statements and COMMIT on that client, with ROLLBACK in catch and client.release() in finally.
What is the difference between pool.query and pool.connect?
pool.query borrows a connection for one query and returns it automatically. pool.connect gives you a client to keep for several queries, such as a transaction, and you must release it yourself.
Practice
Challenge: Export an async function unpaidStudents() that returns an array of first names of students with no payments, in alphabetical order.
import { pool } from './db.mjs';
export async function unpaidStudents() {
const { rows } = await pool.query(
`SELECT first_name FROM students s
WHERE NOT EXISTS (SELECT 1 FROM payments p
WHERE p.student_id = s.student_id)
ORDER BY first_name`,
);
return rows.map((row) => row.first_name);
}
console.log('Unpaid:', await unpaidStudents());
await pool.end();Unpaid: [ 'Advitha' ]NOT EXISTS finds students without a payment (EXISTS), and rows.map turns the row objects into a plain array of names. Only Advitha has never paid. The function uses pool.query, which borrows and returns a connection by itself, because it runs a single statement.
Key Takeaways
| You want to | Use |
|---|---|
| Create a pool | new pg.Pool({ host, database, user, password, max }) |
| Run one query | await pool.query('... WHERE id = $1', [id]) |
| Read rows | const { rows, rowCount } = await pool.query(...) |
| Get a new id | INSERT ... RETURNING payment_id |
| Run a transaction | pool.connect(), BEGIN, COMMIT / ROLLBACK, client.release() |
| Count as a number | count(*)::int |
| Keep dates as text | pg.types.setTypeParser(pg.types.builtins.DATE, (t) => t) |
| Close everything | await pool.end() |
Was this tutorial helpful?