Explain it simply
Explain it simply
A database is a place where data is stored in an organised way. Inside it are tables, and a table looks a lot like a spreadsheet sheet: the columns are the headings (name, city, country) and each row is one record, one customer.
Unlike a spreadsheet, a database enforces rules. You cannot type text into a number column, you cannot have two rows with the same customer ID, and you cannot record an order for a customer who does not exist. Those rules are why you can trust the data.
Problem → Why → Solution
The problem: everything in one big sheet
Picture a shop that writes every order into one sheet. Each order line repeats the customer's name, city and country. If Ana Trujillo places ten orders, her address exists ten times, and once one copy is misspelled nobody knows which version is right.
order_id,customer,city,country,date
10308,Ana Trujillo,Mexico City,Mexico,2024-09-18
10312,Ana Trujilo,Mexico Cty,Mexico,2024-09-22
10315,ana trujillo,Mexico City,mexico,yesterdayWhy does this go wrong?
The sheet has no rules about what type of data belongs in each column or how one customer is identified. A relational database stores each customer once in a Customers table, and orders point to them by CustomerID number. A date column simply refuses text like 'yesterday'.
Core concept: tables, keys and relationships
One PostgreSQL server can hold many databases. Each database contains schemas (the default one is called public), and schemas contain tables. For now, "a database contains tables" is a good enough picture. The software that manages it all, such as PostgreSQL or MySQL, is called a DBMS (Database Management System).
Every column has a name and a data type. integer holds whole numbers, text holds strings, date holds calendar dates, and numeric(10, 2) holds exact decimals such as money. The data type makes the database check values, so putting 'abc' into CustomerID is an error. A row is one record with one value per column. A value that is not known yet can be NULL, unless the column is declared NOT NULL.
A primary key is the column that tells every row apart. Declare CustomerID as PRIMARY KEY and PostgreSQL rejects a second row with the same ID, and rejects a NULL ID. Names or cities make poor keys: two customers live in Mexico City, and two people can share a name.
A foreign key is a column that points at another table's primary key. Orders.CustomerID REFERENCES Customers.CustomerID, so CustomerID = 2 on order 10308 means "this order belongs to Ana Trujillo". The customer's address lives in one place and is corrected once. Tables linked through keys like this are what make a database "relational".
One more thing to remember: rows in a table have no built-in order. A spreadsheet has fixed positions such as row 1 and row 2, but a database table is a set of rows. You find rows by their ID, and when you need them in a particular order you ask for it in the query with ORDER BY (Lesson 9).
- One customer = one row
- CustomerID tells each row apart
- Each order stores a CustomerID
- Follow the ID back to the customer
Store each fact once; everywhere else refers to it by ID.
General pattern
CREATE TABLE parent_table (
id integer PRIMARY KEY,
name text NOT NULL
);
CREATE TABLE child_table (
id integer PRIMARY KEY,
parent_id integer NOT NULL REFERENCES parent_table (id)
);Each column is written as name, data type, then any rules (PRIMARY KEY, NOT NULL, REFERENCES). The child table's parent_id is a foreign key pointing at the parent's id. Lesson 21 covers CREATE TABLE in full.
Example: build the course's sample tables
Run this script once in your own PostgreSQL database; the queries in the following lessons all use these Customers and Orders tables. At the end it reads both tables back, so you can trace each order's CustomerID to a customer. The order matters: Customers must exist before Orders, because the foreign key in Orders refers to it. Running the script twice fails with relation "customers" already exists, which is harmless.
CREATE TABLE Customers (
CustomerID integer PRIMARY KEY,
CustomerName text NOT NULL,
ContactName text,
City text,
Country text
);
INSERT INTO Customers (CustomerID, CustomerName, ContactName, City, Country) VALUES
(1, 'Alfreds Futterkiste', 'Maria Anders', 'Berlin', 'Germany'),
(2, 'Ana Trujillo', 'Ana Trujillo', 'Mexico City', 'Mexico'),
(3, 'Antonio Moreno', 'Antonio Moreno', 'Mexico City', 'Mexico'),
(4, 'Around the Horn', 'Thomas Hardy', 'London', 'UK');
CREATE TABLE Orders (
OrderID integer PRIMARY KEY,
CustomerID integer NOT NULL REFERENCES Customers (CustomerID),
OrderDate date NOT NULL
);
INSERT INTO Orders (OrderID, CustomerID, OrderDate) VALUES
(10308, 2, '2024-09-18'),
(10309, 4, '2024-09-19'),
(10310, 3, '2024-09-20');
SELECT * FROM Customers;
SELECT * FROM Orders;Code breakdown
- CustomerID
CustomerID integer PRIMARY KEY,Each customer's ID. PRIMARY KEY means no two rows can share a value and the value can never be NULL.
- CustomerName
CustomerName text NOT NULL,A name is required, hence NOT NULL. ContactName, City and Country carry no rule, so they may be left empty (NULL) when unknown.
- INSERT
(2, 'Ana Trujillo', 'Ana Trujillo', 'Mexico City', 'Mexico'),One row: five values in column order. Text goes in single quotes, numbers do not. psql reports INSERT 0 4, meaning four rows went in (the 0 is a legacy field you can ignore).
- Foreign key
CustomerID integer NOT NULL REFERENCES Customers (CustomerID),Every order must point at a CustomerID that really exists in Customers. Inserting an order for customer 99 fails with a foreign key constraint error.
- OrderDate
OrderDate date NOT NULLThe date type accepts an ISO date such as '2024-09-18' and rejects invalid ones such as '2024-13-45'.
CREATE TABLE
INSERT 0 4
CREATE TABLE
INSERT 0 3
customerid | customername | contactname | city | country
------------+---------------------+----------------+-------------+---------
1 | Alfreds Futterkiste | Maria Anders | Berlin | Germany
2 | Ana Trujillo | Ana Trujillo | Mexico City | Mexico
3 | Antonio Moreno | Antonio Moreno | Mexico City | Mexico
4 | Around the Horn | Thomas Hardy | London | UK
(4 rows)
orderid | customerid | orderdate
---------+------------+------------
10308 | 2 | 2024-09-18
10309 | 4 | 2024-09-19
10310 | 3 | 2024-09-20
(3 rows)Reading two tables through an ID
Order 10309 has CustomerID 4. In Customers, ID 4 is Around the Horn in London, so that order ships to London. Right now you are matching the IDs by eye; in Lessons 17-19, JOIN does the same matching inside a single query. Notice also that customer 1, Alfreds Futterkiste, has no orders yet. That is perfectly allowed: a foreign key only checks that every order points at a real customer, not that every customer has an order.
Customers <- Orders
-------------------
Customers Orders
+------------+-----------------+ +---------+------------+
| CustomerID | CustomerName | | OrderID | CustomerID |
+------------+-----------------+ +---------+------------+
| 2 | Ana Trujillo |<---| 10308 | 2 |
| 3 | Antonio Moreno |<---| 10310 | 3 |
| 4 | Around the Horn |<---| 10309 | 4 |
+------------+-----------------+ +---------+------------+
primary key foreign key -> CustomersIn real projects
Where this shows up in real projects
An online shop's database typically has customers, products, orders, order_items and payments, where order_items points at both orders and products through foreign keys. A hospital system has patients, doctors and appointments; a school has students, courses and enrollments. The pattern never changes: one table per kind of thing, foreign keys for the relationships between them.
When a project starts, developers sketch the tables, columns and keys before writing application code. That design is hard to change later, because splitting a table that already holds millions of rows is a major migration. That is why choosing primary keys and data types gets careful attention from day one, often with a simple diagram of the tables and their links.
Common mistakes
Common mistakes
1. Using a name as the primary key
Make CustomerName the primary key and the first customer who shares a name causes a duplicate key error on INSERT. If a customer changes their name, every order referencing it must change too. A meaningless ID number (a surrogate key) is far safer.
2. Storing numbers or dates in text columns
Store OrderDate as text and '18/09/2024', '2024-9-18' and 'yesterday' get mixed together, so sorting by date breaks. Store a price as text and '100' sorts before '9' because text compares character by character. Use real types: date, numeric, integer.
3. Storing an ID without a foreign key
Without REFERENCES, CustomerID is just an integer, and orders pointing at deleted customers (orphans) can pile up. With a foreign key, the database refuses to let that happen.
INSERT INTO Orders VALUES (10311, 99, '2024-09-21');
ERROR: insert or update on table "orders" violates foreign key constraint
"orders_customerid_fkey"Best practices
Best practices
- Give every table a primary key; a meaningless ID number is the simplest and safest choice.
- Pick each column's real type (integer, numeric, date) instead of using text for everything.
- Protect required columns with NOT NULL.
- When one table points at another by ID, declare it as a foreign key with REFERENCES.
Mini challenge
Mini challenge: build a Products table
Create a Products table for the shop's goods, fill it and read it back.
- ProductID is an integer primary key
- ProductName is text and NOT NULL
- Price is numeric(10, 2) and NOT NULL
- Insert three products and read back all three columns by name
-- TODO: CREATE TABLE Products with three columns
-- ProductID -> whole number, unique per product
-- ProductName -> text, required
-- Price -> exact money value, required
-- TODO: insert three products in one statement
-- TODO: read the three columns backExpected: The SELECT returns three rows, and the price column shows two decimal places, e.g. 3.50, 12.00 and 7.25.
Show hint
Copy the shape of the Customers table. For money use numeric(10, 2) rather than a float, so 3.50 is stored exactly.
Show solution
CREATE TABLE Products (
ProductID integer PRIMARY KEY,
ProductName text NOT NULL,
Price numeric(10, 2) NOT NULL
);
INSERT INTO Products (ProductID, ProductName, Price) VALUES
(1, 'Green Tea', 3.50),
(2, 'Coffee Beans', 12.00),
(3, 'Honey', 7.25);
SELECT ProductID, ProductName, Price FROM Products;Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A database contains tables; a table has typed columns and rows (records).
- A primary key identifies each row and rejects duplicates and NULLs.
- A foreign key points at another table's primary key and refuses references to missing records.
- Store each fact once and link to it by ID: that is the heart of relational design.
PostgreSQL SQL Tutorial — PostgreSQL Global Development Group