Site icon JD Bots

PostgreSQL Tutorial — Part 6: Create Tables

Featured card for PostgreSQL Tutorial Part 6: Create Tables, with a terminal listing CREATE TABLE authors, CREATE TABLE books and CREATE TABLE customers, and the table list showing 3 rows.

PostgreSQL Tutorial Part 6: Create Tables

A table is where PostgreSQL keeps your data: rows that all have the same columns, each column with a name and a data type. In this part you create tables in PostgreSQL for the bookstore database: authors, books and customers.

You write each table with CREATE TABLE, give every column the type Part 5 chose, and let PostgreSQL number the rows by itself. Then you list the tables, look inside one in psql, and find them in pgAdmin.

This is Part 6 of the PostgreSQL Tutorial. The parts in Module B, Build the Database:

All parts of the PostgreSQL Tutorial

Module A: Start Here

Module B: Build the Database

Module C: Query Data

  • Part 10: SELECT, WHERE, ORDER BY and LIMIT
  • Part 11: LIKE, IN, BETWEEN, NULL and CASE
  • Part 12: GROUP BY and Aggregate Functions
  • Part 13: JOINs Explained
  • Part 14: Subqueries and CTEs
  • Part 15: UNION, INTERSECT and EXCEPT
  • Part 16: String, Number and Conversion Functions
  • Part 17: Dates, Times and Time Zones

Module D: Design and Performance

  • Part 18: Database Design and Normalization
  • Part 19: Views and Materialized Views
  • Part 20: Indexes Explained
  • Part 21: EXPLAIN and Query Performance
  • Part 22: Transactions, Isolation Levels and Locks

Module E: Advanced SQL and Programming

  • Part 23: Window Functions
  • Part 24: Recursive Queries and LATERAL Joins
  • Part 25: JSON and JSONB
  • Part 26: Arrays, Enums, Ranges and Generated Columns
  • Part 27: Full-Text Search
  • Part 28: Functions and Stored Procedures
  • Part 29: Triggers

Module F: Administration and Security

  • Part 30: Users, Roles and Privileges
  • Part 31: Row-Level Security
  • Part 32: Configuration and Restarting the Server
  • Part 33: Allow Remote Connections Securely
  • Part 34: Backup and Restore
  • Part 35: Automate Backups
  • Part 36: VACUUM, ANALYZE and Autovacuum
  • Part 37: Monitoring and Slow Queries
  • Part 38: Table Partitioning
  • Part 39: Streaming Replication
  • Part 40: Upgrade to a New Major Version

Module G: PostgreSQL for Developers

  • Part 41: Connect from C# .NET with Npgsql
  • Part 42: Entity Framework Core with PostgreSQL
  • Part 43: Connect from Python with psycopg
  • Part 44: Connect from Node.js with node-postgres

Module H: Extensions, AI and Cloud

  • Part 45: Extensions
  • Part 46: Vector Search with pgvector
  • Part 47: Azure Database for PostgreSQL
  • Part 48: Migrate to Azure and What to Learn Next

Every command, output and screen on this page is real, from PostgreSQL 19 and pgAdmin 4 9.19 on macOS.

Where the bookstore database is now: Part 4 created it, and Part 5 chose a type for every column of its first tables. It’s still empty. If you’re starting here, create it with this catch-up script, in psql connected to the postgres database:

postgres=#

CREATE DATABASE bookstore;
\c bookstore

Prerequisites

What CREATE TABLE Does

CREATE TABLE adds a new, empty table to the database you’re connected to. You give it three things:

A new table has no rows. Part 8 fills the bookstore’s tables with data.

Step 1: Connect to the bookstore Database

Open Terminal and connect as the postgres user, as Part 2 shows:

Terminal

psql -U postgres

Then switch to bookstore:

postgres=#

\c bookstore

Output

You are now connected to database "bookstore" as user "postgres".

The prompt is now bookstore=#, so the tables you create go into bookstore.

Step 2: Create the authors Table

The first table holds the bookstore’s authors: an ID and a name. Type or paste this statement:

bookstore=#

CREATE TABLE authors (
    author_id integer GENERATED ALWAYS AS IDENTITY,
    name text
);

Output

CREATE TABLE

psql answers CREATE TABLE: the table exists, with no rows yet. Here’s what each part means:

While a statement isn’t finished, psql starts each new line with bookstore(# instead of bookstore=#. The ( means a bracket is still open.

Step 3: Create the books Table

The books table has six columns, each with the type Part 5 chose:

bookstore=#

CREATE TABLE books (
    book_id integer GENERATED ALWAYS AS IDENTITY,
    title text,
    author_id integer,
    price numeric(10,2),
    published_on date,
    in_stock boolean
);

Output

CREATE TABLE

Step 4: Create the customers Table

The last table holds the customers:

bookstore=#

CREATE TABLE customers (
    customer_id integer GENERATED ALWAYS AS IDENTITY,
    name text,
    email text,
    joined_at timestamptz
);

Output

CREATE TABLE

joined_at timestamptz records the moment a customer signed up. PostgreSQL stores it in UTC and shows it in each session’s time zone, as Part 5 explained.

Step 5: List the Tables

psql’s \dt command lists the tables in the database you’re connected to:

bookstore=#

\dt

Output

            List of tables
 Schema |   Name    | Type  |  Owner
--------+-----------+-------+----------
 public | authors   | table | postgres
 public | books     | table | postgres
 public | customers | table | postgres
(3 rows)

All three are there. The Schema column says public. A schema is a folder inside a database, and every new database has one called public, where tables go unless you name another. How to Create a Schema in PostgreSQL shows how to make your own, and How to Set the search_path in PostgreSQL how PostgreSQL finds a table by its name.

How to List Tables in PostgreSQL shows more ways to list tables, including a query for tools that don’t understand \dt.

Step 6: Look Inside a Table

\d and a table’s name describe the table: every column, its type and its settings:

bookstore=#

\d books

Output

                                Table "public.books"
    Column    |     Type      | Collation | Nullable |           Default
--------------+---------------+-----------+----------+------------------------------
 book_id      | integer       |           | not null | generated always as identity
 title        | text          |           |          |
 author_id    | integer       |           |          |
 price        | numeric(10,2) |           |          |
 published_on | date          |           |          |
 in_stock     | boolean       |           |          |

Each row of the output is one column of the table. Nullable says not null for book_id, because an identity column can never be empty, and Default shows that PostgreSQL fills it in. The other columns can be left empty for now; Part 7 adds rules where a value must be there.

How to Describe a Table in PostgreSQL explains every part of this output.

Step 7: See the Tables in pgAdmin

pgAdmin shows the same tables. In the Object Explorer, open Servers › PostgreSQL 19 › Databases › bookstore › Schemas › public › Tables. If pgAdmin was already open, right-click Tables and choose Refresh first. Then open books › Columns to see its columns and their types:

The three tables in pgAdmin, with the columns of books.

pgAdmin can also create a table through a dialog, without SQL: see How to Create a Table in pgAdmin 4.

Clean Up

Keep the three tables: Part 7 adds keys and rules to them. If you want to start this part again, drop them, in psql connected to bookstore:

bookstore=#

DROP TABLE books, authors, customers;

Output

DROP TABLE

Warning: DROP TABLE deletes the tables and every row in them, and it can’t be undone.

How to Drop a Table in PostgreSQL explains DROP TABLE in full.

Common Mistakes

MistakeWhat happensDo this instead
A missing comma between two columnsERROR: syntax error at or near "author_id", pointing at the line after the missing comma.Put a comma after every column except the last.
A type name from another database, such as datetimeERROR: type "datetime" does not existUse PostgreSQL’s names: timestamptz for a moment, date for a day.
Running the same CREATE TABLE twiceERROR: relation "authors" already exists. PostgreSQL calls tables and similar objects relations.The table is already there: check with \dt. To change it, use ALTER TABLE (see the FAQ).

Troubleshooting

ProblemLikely causeFix
\dt says Did not find any tables.You’re connected to another database, such as postgres.Switch with \c bookstore, then run \dt again.
Did not find any relation named "book".The name is misspelled: the table is books.Check the names with \dt.
psql keeps showing bookstore(# or bookstore-#The statement isn’t finished: a bracket is still open, or the semicolon is missing.Type what’s missing, such as ); or ;, and press Return.

FAQ

How do I add, rename or remove a column later?

With ALTER TABLE, without creating the table again: How to Add a Column to a Table in PostgreSQL, How to Rename a Column in PostgreSQL and How to Drop a Column in PostgreSQL show each one.

How do I change a column’s type?

Also with ALTER TABLE, as How to Change a Column’s Data Type in PostgreSQL shows. PostgreSQL converts the values already in the column.

Can I rename a table?

Yes, with ALTER TABLE … RENAME TO: see How to Rename a Table in PostgreSQL.

Why don’t the tables have primary keys yet?

An identity column numbers the rows, but on its own it doesn’t stop two rows from having the same ID: the documentation says that takes a PRIMARY KEY or UNIQUE constraint. Part 7 adds them, along with the foreign key from books to authors.

Does each column need its own line?

No. PostgreSQL ignores line breaks and extra spaces, so a whole CREATE TABLE can be one line. One column per line is easier to read, and a missing comma is easier to spot.

Conclusion

You created the bookstore’s first three tables with CREATE TABLE: authors, books and customers, each with an identity column that numbers its rows. \dt lists them, \d shows their columns, and pgAdmin shows them under Schemas › public › Tables.

Next, Part 7 adds primary keys, a foreign key and other rules, so PostgreSQL refuses data that doesn’t make sense.

← Previous: Part 5: Data Types Explained

Coming next: Part 7: Primary Keys, Foreign Keys and Constraints.

Additional Resources

Postgres, PostgreSQL and the Slonik Logo are trademarks or registered trademarks of the PostgreSQL Community Association of Canada, and used with their permission.

Exit mobile version