Warming up the neural circuits...
Now that you have PostgreSQL running, it's time to build. By the end of this module you will:
In PostgreSQL, every project usually gets its own Database. This keeps things isolated and organized.
-- Create a new database
CREATE DATABASE shop_db;
-- List all databases to verify
-- \l
-- Connect to your new database
-- \c shop_dbCaution: Be careful with DROP DATABASE shop_db;. It deletes the entire database and all its data permanently. In production, this command is restricted to high-level admins.
A table is where the actual data lives. When you create a table, you must define the Columns, their Data Types, and their Rules (Constraints).
CREATE TABLE products (
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
price INTEGER NOT NULL,
description TEXT,
in_stock BOOLEAN DEFAULT true,
created_at TIMESTAMP DEFAULT NOW()
);id SERIAL PRIMARY KEY:
SERIAL tells Postgres to auto-increment this number (1, 2, 3...) automatically.PRIMARY KEY ensures every product has a unique ID (the most important constraint).VARCHAR(100): Variable character string, max 100 letters. Good for names.NOT NULL: This column must have a value. It cannot be empty.DEFAULT true: If you don't provide a value, it will automatically be set to true.Choosing the right data type is the difference between a fast, reliable database and a slow, buggy one.
| Category | Type | Best For | Professional Tip |
|---|---|---|---|
| Whole Numbers | INTEGER | IDs, counts, age | Use BIGINT if you expect billions of rows. |
| Money/Math | NUMERIC | Prices, interest rates | Never use floating points (REAL) for money. |
| Short Text | VARCHAR(n) | Names, emails, titles | Limits help prevent "garbage" data entry. |
| Long Text | TEXT | Descriptions, comments | In Postgres, TEXT has no performance penalty over VARCHAR. |
| Truth | BOOLEAN | active, deleted, verified | Defaults are your best friend here. |
| Time | TIMESTAMPTZ | created_at, updated_at | Always use WITH TIME ZONE to avoid time-zone bugs. |
Constraints are automated rules that prevent "bad" data from entering your system. It's better to have a database error than a silent bug in your app.
NULL (empty) values where they don't belong.email in a users table).CHECK (price > 0)).CREATE TABLE users (
id SERIAL PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
age INTEGER CHECK (age >= 13),
role VARCHAR(20) DEFAULT 'user'
);To code like a senior engineer, follow these industry standards:
created_at, not createdAt or CreatedAt.users, products, orders.CREATE TABLE).id as the primary key name in every table.learning_hub.learning_hub.courses with these columns:
id (auto-incrementing ID)title (required text)instructor (text)price (number, must be positive)is_published (true/false, default false)Done? Run \dt and \d courses to see your work. In the next module, we'll learn how to actually put data into these tables and read it back!