Sub topic 8
Creating a Table
This chapter covers CREATE TABLE: column types, constraints, identity columns, and the errors you are most likely to hit. It assumes you can open psql, you have created firstdb in the previous chapter, and you know a table holds rows with a fixed set of named columns.
What a table definition decides
A table definition fixes the shape of your data before any row exists. PostgreSQL stores the definition in its system catalogs and checks every later INSERT and UPDATE against it. If a value has the wrong type or breaks a constraint, the statement fails and no row changes.
A definition has three parts:
- A table name.
- One or more columns, each with a name and a data type.
- Optional constraints that restrict which values are allowed.
Connect to the practice database
Before you create anything, check which database your session is using. A table created in the wrong database is a common first mistake.
\c firstdbThe prompt should read firstdb=#. If it shows postgres=#, you are still in the default database.
The books table
Run this statement in psql:
CREATE TABLE books (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
author text NOT NULL,
published_year integer
);On success, psql prints CREATE TABLE. The statement ends with a semicolon. Without it, psql shows a continuation prompt such as firstdb(# and waits for more input.
Here is how each column is defined:
| Column | Type | Rules | Meaning |
|---|---|---|---|
| `id` | `integer` | Identity, primary key | Generated by the server, unique, never null |
| `title` | `text` | `NOT NULL` | Required |
| `author` | `text` | `NOT NULL` | Required |
| `published_year` | `integer` | None | Optional, so it may be null |
Data types used here
A data type tells PostgreSQL how to store a value and which operations are valid on it.
integeris a 4-byte whole number from -2,147,483,648 to 2,147,483,647.textis a string of any length. PostgreSQL has no speed penalty fortextcompared withvarchar(n), so usevarchar(n)only when the length limit is a real business rule.
Other types you will meet soon:
| Type | Typical use |
|---|---|
| `bigint` | Whole numbers beyond about 2.1 billion |
| `numeric(p, s)` | Exact decimals such as prices |
| `boolean` | True or false |
| `date` | A calendar date |
| `timestamptz` | A moment in time, with time zone handling |
Do not store money in real or double precision. These are binary floating-point types and cannot represent many decimal fractions exactly.
Constraints
A constraint is a rule the database enforces for you. The books table uses three kinds.
NOT NULL
NULL means "no value". NOT NULL rejects it. Columns without NOT NULL, such as published_year, accept nulls. That fits the data here, because a book can exist with an unknown publication year.
PRIMARY KEY
A primary key identifies each row. It combines two rules: values must be unique, and they must not be null. PostgreSQL builds a unique index behind it, so lookups by id are fast. A table may have only one primary key, though the key can span several columns.
Identity columns
GENERATED ALWAYS AS IDENTITY makes PostgreSQL fill in the column from an internal sequence. You do not supply id when you insert.
The word ALWAYS is strict. If an INSERT supplies its own value for id, PostgreSQL refuses it:
INSERT INTO books (id, title, author)
VALUES (100, 'Hyperion', 'Dan Simmons');ERROR: cannot insert a non-DEFAULT value into column "id"
DETAIL: Column "id" is an identity column defined as GENERATED ALWAYS.
HINT: Use OVERRIDING SYSTEM VALUE to override.The alternative is GENERATED BY DEFAULT AS IDENTITY, which allows explicit values. It is convenient when you load data from elsewhere, but it can cause duplicate key errors later. The sequence does not know that you inserted id 100 by hand, and it will eventually try to issue 100 itself.
Older tutorials use serial for the same purpose. It still works, but identity columns follow the SQL standard and behave more predictably, so prefer them in new tables.
How the pieces fit together
The diagram shows what happens when you insert into the table, which is the next chapter's topic. It helps to see now why the definition matters.
Inspect what you created
Use \d to display the definition that PostgreSQL stored:
\d booksThe output lists each column, its type, and its modifiers. You should see not null on id, title, and author, a generated-always identity on id, and a books_pkey index. Note that the index name came from PostgreSQL. You did not choose it.
To list all tables in the current database, run \dt. The books table appears in the public schema. A schema is a namespace inside a database that groups tables. Unqualified names resolve through the search_path setting, which includes public by default, so books and public.books refer to the same table.
Common errors
The table already exists
Running the statement twice fails:
ERROR: relation "books" already existsPostgreSQL calls tables "relations" in many messages. You can make the statement safe to repeat:
CREATE TABLE IF NOT EXISTS books (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
author text NOT NULL,
published_year integer
);This prints a notice and skips creation. It does not compare definitions. If an older books table has different columns, the statement still succeeds without changing it, which can hide a mismatch.
Syntax error near a comma
ERROR: syntax error at or near ")"The usual cause is a trailing comma after the last column. Commas separate column definitions. They do not end them.
Created in the wrong database
If you ran the statement while connected to postgres, books exists there. Check the prompt, switch with \c firstdb, and run it again. Remove the stray copy later with DROP TABLE books; while connected to the database that holds it.
Permission denied
ERROR: permission denied for schema publicYour role may lack CREATE rights on the schema. This is common on PostgreSQL 15 and later, where ordinary roles no longer get that right on public by default. Connecting as the postgres role, as in this tutorial, avoids the problem.
Naming conventions
PostgreSQL folds unquoted identifiers to lower case. Books, BOOKS, and books are the same table. If you write "Books" with double quotes, the name becomes case-sensitive and you must quote it every time. Avoid that. Use lower-case names with underscores, such as published_year, and never use a reserved word like user or order as a table name.
Changing a table later
If you forget a column, you do not have to drop the table. ALTER TABLE changes the definition in place:
ALTER TABLE books ADD COLUMN isbn text;Existing rows get null in the new column. Leave books as defined in this chapter, since the later chapters use it exactly as shown.
Summary of key points
- A table definition lists columns, types, and constraints. PostgreSQL enforces them on every write.
GENERATED ALWAYS AS IDENTITYcreates server-assigned ids and rejects manual values.PRIMARY KEYmeans unique and not null, and it creates an index.- Columns accept nulls unless you add
NOT NULL. - Use
\d booksto confirm the stored definition, and check your prompt before creating anything.
Exercise
A colleague runs INSERT INTO books (id, title, author) VALUES (7, 'Solaris', 'Stanislaw Lem'); against your table and gets an error. Why does it fail, and which two changes to the statement or table would let the insert work?
Show answer
The id column is defined as GENERATED ALWAYS AS IDENTITY, so PostgreSQL rejects any explicit value for it. Fix it by removing id from the column list and value list so the server generates it. Alternatively, add OVERRIDING SYSTEM VALUE to the insert, or redefine the column as GENERATED BY DEFAULT AS IDENTITY.
Exercise
You run CREATE TABLE books (...) and see ERROR: relation "books" already exists. You are not sure whether the existing table has the right columns. What command shows its definition, and why is CREATE TABLE IF NOT EXISTS a poor way to check?
Show answer
Run \d books to see the columns, types, and constraints. CREATE TABLE IF NOT EXISTS only skips creation when a table of that name exists. It does not compare definitions, so a table with different columns would pass silently.