After this lesson, you will be able to: Understand how relational databases work, write basic SQL queries, and connect a database to a Node.js backend.
Databases are how your backend remembers things between requests. This lesson covers the relational model (rows, tables, primary keys), the four core SQL operations, and how to connect PostgreSQL to a Node.js app.
A relational database is a collection of tables. Each table has columns (the fields, like name and email) and rows (the records). Each row has a unique primary key, usually called id. Tables relate to each other with foreign keys: a posts table can have a userId that references the id in users.
Diagram coming soon!
Two database tables side by side, users (id, name, email) on the left, posts (id, userId, title, body) on the right, with an arrow connecting posts.userId to users.id
Create, Read, Update, Delete, "CRUD".
-- Create-- ReadSELECT * FROM users;SELECT name, email FROM users WHERE id = 1;-- UpdateUPDATE users SET name = 'Alex Chen' WHERE id = 1;-- DeleteDELETE FROM users WHERE id = 1;
Joins combine related rows from different tables.
-- Get every post with its author's nameSELECT posts.title, users.name AS authorFROM postsJOIN users ON posts.user_id = users.id;
The pg package is the most common PostgreSQL driver for Node.
// In the in-browser editor shell: npm install pgconst { Pool } = require("pg");const pool = new Pool({ connectionString: process.env.DATABASE_URL });app.get("/api/users", async (req, res) => {const result = await pool.query("SELECT id, name FROM users");res.json(result.rows);});app.post("/api/users", async (req, res) => {const { name, email } = req.body;// $1 and $2 are parameters, safe from SQL injectionawait pool.query("INSERT INTO users (name, email) VALUES ($1, $2)", [name, email]);res.status(201).json({ ok: true });});
Use the free SQL sandbox at sqliteonline.com to run real queries, no install required.
Go to sqliteonline.com and pick PostgreSQL
In the editor, run: CREATE TABLE students (id SERIAL PRIMARY KEY, name TEXT, grade INT);
Insert three rows with INSERT INTO
Run SELECT * FROM students to see them
Update one row's grade
Delete one row, then re-run SELECT to confirm
What does it guarantee about a row in a table?
Sign in and purchase access to unlock this lesson.