Sub topic 8
Creating a Table
Prerequisites and the table model
Assume PostgreSQL is installed, the server is running, and you are connected to the firstdb database with psql. You should also understand that a database stores related data in tables.
A table is a collection of rows with a fixed set of columns. A column is a named field with a data type. A data type controls what values the column can store. A row is one complete record in the table.
For a small library, each row in a books table can represent one book:
| Column | Type | Purpose |
|---|---|---|
| `id` | `integer` | Unique identifier |
| `title` | `text` | Book title |
| `author` | `text` | Author name |
| `published_year` | `integer` | Publication year, if known |
Defining the table
Use CREATE TABLE to define a table and its columns:
CREATE TABLE books (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
author text NOT NULL,
published_year integer
);The id column has several parts:
integerstores whole numbers.GENERATED ALWAYS AS IDENTITYtells PostgreSQL to generate a new number for each row.PRIMARY KEYidentifies each row uniquely. A primary key cannot contain duplicate or missing values.
The title and author columns use the text type. NOT NULL means every row must provide a value for these columns. The published_year column does not have NOT NULL, so it may be left empty when the year is unknown. An empty value in this context is represented by NULL.
The semicolon ends the SQL statement. PostgreSQL creates the table only after it receives the complete statement.
Constraints and common errors
A constraint is a rule that PostgreSQL checks when data is inserted or changed. PRIMARY KEY and NOT NULL are constraints.
A common error is trying to create the same table twice:
ERROR: relation "books" already existsIn PostgreSQL, a relation can be a table or another table-like object. If you are practicing and want to recreate the table, remove it first:
DROP TABLE books;DROP TABLE permanently removes the table and its rows. Use it only when you are sure the data is disposable. Otherwise, keep the existing table and inspect it before changing anything.
Another common mistake is choosing a type that cannot represent the intended values. Use integer for a year, but use text for a title because titles contain letters, spaces, and punctuation.
After creating the table, you can inspect its definition in psql with:
\d booksThis displays the columns, types, identity behavior, and constraints. The \d command is a psql meta-command, not SQL, so it does not need a semicolon.
Exercise
Which part of the table definition ensures that every book has a title, while the publication year may be unknown?
Show answer
title text NOT NULL requires a title, while published_year integer allows NULL.