CREATE TABLE: types and constraints
1810 min
Now we learn to build a database rather than read one. Try this lesson’s commands in your own personal database: Practice → Free play — there you can create and drop any table you like.
Creating a database
CREATE DATABASE kutubxona;To connect to the new database in PostgreSQL: \c kutubxona. To list databases: \l.
Creating a table
CREATE TABLE books (
id ..., -- primary key (see below)
title varchar(200) NOT NULL,
author varchar(100) NOT NULL,
year int,
price decimal(10, 2) DEFAULT 0,
isbn varchar(20) UNIQUE
);Each column has a name, a type and, if needed, constraints.
The main types
| Type | What it holds | Example |
|---|---|---|
int / bigint |
whole number | 42 |
decimal(p, s) |
exact decimal (for money) | 18000.50 |
varchar(n) |
text of up to n characters | 'Otabek' |
text |
long text | an article |
date |
date | '2026-11-14' |
boolean |
yes / no | true |
In PostgreSQL date-and-time is timestamp, and decimals are numeric (decimal works too).
Never store money in
float: it is an approximate number, and0.1 + 0.2can come out as0.30000000000000004. Money isdecimal.
Automatic numbers: the primary key
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEYThe older serial also works: id serial PRIMARY KEY.
The database numbers the rows itself: 1, 2, 3… You do not write id in an INSERT.
Constraints
| Constraint | Meaning |
|---|---|
NOT NULL |
must not be empty |
UNIQUE |
must not repeat |
DEFAULT x |
x when no value is given |
CHECK (condition) |
the condition must hold: CHECK (price >= 0) |
PRIMARY KEY |
NOT NULL + UNIQUE, the row’s number |
REFERENCES |
a foreign key |
A foreign key
CREATE TABLE loans (
id bigint PRIMARY KEY ...,
book_id bigint NOT NULL,
reader varchar(100) NOT NULL,
taken_at date NOT NULL DEFAULT CURRENT_DATE,
FOREIGN KEY (book_id) REFERENCES books (id)
);The rules:
- the parent table (
books) is created first; - the foreign-key column has the same type as the parent key (
bigint↔bigint); - you cannot lend a book that does not exist, and you cannot delete a book that is on loan.
Seeing a table’s structure
\d books — columns, types, keys. To list tables: \dt.
Exercise
In free play, create the kutubxona database and build the books and loans tables as shown above. Then try inserting a row with a book_id that does not exist and see which error you get. For step-by-step practice, missions 2 and 4 in the Practice section cover exactly this.
Remember
CREATE TABLE name (column type constraints, …);- Money is
decimal, a date isdate, text isvarchar(n). - Write foreign keys as a separate
FOREIGN KEYline, in MySQL and PostgreSQL alike.