Skip to main content

Week 3

Before we get into PostgreSQL, we need to understand why we use databases in the first place. Right now, if our apps use dictionaries to store our data. The problem is that the data disappears when the server restarts, creating a problem in the future. A database allows us to store our data permanently so it survives restarts, crashes, and can support concurrent users.

There are two categories of databases


Relational (SQL)Non-Relational (NoSQL)
StructureTables with rows and columnsSimilar to JSON
SchemaFixed, predefinedFlexible, schema-less
RelationshipsTables link with keysHandled in the app's code
Query LanguageSQLVaries but usually none
Best forStructured data that relates to each otherUnstructured or rapidly changing data
ExamplesPostgreSQL, MySQLMongoDB, Redis

image.png

 

What is a relational database?

A relational database organizes data into tables. Each table represents one thing (a resource, a user, an order, etc). Each row is one record and each column is an attribute of that record, with a defined data type.

idfirst_namelast_nameemail
1MiguelMerlinmmerlin@stevens.edu
2NishitSharmansharma11@stevens.edu

Because these tables are relational, that means they can be linked to each other. An orders table can reference a user table, so every order knows which user placed it. 

 

What is PostgreSQL?

PostgreSQL is an open source Relational Database Management System (RDBMS). The RDBMS is a software layer that sits on top of your data. It enforces rules, handles queries, and manages connections.

 

Tables and Schema

When you create a table in PostgreSQL, you define its schema, the column names and what type of data each column holds. You do this with CREATE TABLE

CREATE TABLE users (
    id    SERIAL PRIMARY KEY,
    name  VARCHAR(100) NOT NULL,
    email VARCHAR(255)
);

You have to define this schema otherwise, PostgreSQL will reject any data that doesn't fit the schema

Data Types

Every column has a data type that constrains what values it can store:

TypeWhat it storesExample
INTEGERWhole numbers42
SERIALAuto-incrementing integers (use it for IDs)1, 2, 3, ...
VARCHAR(n)Text up to n characters"Nishit Sharma"
TEXTUnlimited length textLong descriptions
BOOLEANTrue/Falsetrue
DATECalendar date2026-3-25
NUMERICDecimal numbers19.99

Primary Keys and Foreign Keys

A primary key is a column that uniquely identifies every row in a table. No two rows can share the same primary key. SERIAL PRIMARY KEY makes PostgreSQL auto assign a new integer ID to each row you insert.

A foreign Key is a column in one table that references the primary key of another table. This creates the relationship between tables

CREATE TABLE orders (
    id          SERIAL PRIMARY KEY,
    user_id     INTEGER REFERENCES users(id),
    amount      NUMERIC,
    order_date  DATE
);

In this example, user_id is a foreign key, and it must match an existing id in the users table. If you try to insert an order with a user_id that doesn't exist, PostgreSQL will reject it automatically.

 

Basic SQL

SQL (Structured Query Language) is the language we will use. Every operation you will perform (creating tables, inserting data, and reading data) is written in SQL.

CREATE TABLE

Defines a new table and its schema:

CREATE TABLE resources (
    id            SERIAL PRIMARY KEY,
    name          VARCHAR(255) NOT NULL,
    category      VARCHAR(50),
    description   TEXT
);

NOT NULL means that the column is required, PostgreSQL won't let you insert a row without a value there.

 

INSERT (Create)

Adds a new row to a table:

INSERT INTO resources (name, category, description)
VALUES ('City Food Bank', 'Food', 'Free weekly groceries for families.');

 

SELECT (Read)

Retrieves rows from a table:

-- Get everything
SELECT * FROM resources;

-- Get specific columns
SELECT name, category FROM resources;

-- Filter with WHERE
SELECT * FROM resources WHERE category = 'Food';

 

UPDATE

Changes an existing row:

UPDATE resources
SET description = 'Updated description here.'
WHERE id = 1;

Make sure to include a WHERE clause on UPDATE otherwise you will update every row in the table

 

DELETE

Removes a row:

DELETE FROM resources WHERE id = 1;

 

Relationships between tables

The most common relationship in web apps is one-to-many. This means that one resource can have many referrals, one user can have many orders.

-- One user
CREATE TABLE users (
    id   SERIAL PRIMARY KEY,
    name VARCHAR(100)
);

-- Many orders belonging to one user
CREATE TABLE orders (
    id       SERIAL PRIMARY KEY,
    user_id  INTEGER REFERENCES users(id),
    amount   NUMERIC
);
SELECT users.name, orders.amount
FROM orders
JOIN users ON orders.user_id = users.id;

This pulls the user's name from the users table and matches it to their orders using the foreign key relationship